commit 56ee41aa6c5aab5eec73e67ced174080f3a10eb3 Author: naudachu Date: Mon May 13 21:20:32 2024 +0500 init diff --git a/README.md b/README.md new file mode 100644 index 0000000..cc58e96 --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +``` +npm install +npm run dev +``` + +``` +npm run deploy +``` diff --git a/node_modules/.bin/acorn b/node_modules/.bin/acorn new file mode 120000 index 0000000..cf76760 --- /dev/null +++ b/node_modules/.bin/acorn @@ -0,0 +1 @@ +../acorn/bin/acorn \ No newline at end of file diff --git a/node_modules/.bin/esbuild b/node_modules/.bin/esbuild new file mode 120000 index 0000000..c83ac07 --- /dev/null +++ b/node_modules/.bin/esbuild @@ -0,0 +1 @@ +../esbuild/bin/esbuild \ No newline at end of file diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/node_modules/.bin/miniflare b/node_modules/.bin/miniflare new file mode 120000 index 0000000..69b1982 --- /dev/null +++ b/node_modules/.bin/miniflare @@ -0,0 +1 @@ +../miniflare/bootstrap.js \ No newline at end of file diff --git a/node_modules/.bin/mustache b/node_modules/.bin/mustache new file mode 120000 index 0000000..f8b7197 --- /dev/null +++ b/node_modules/.bin/mustache @@ -0,0 +1 @@ +../mustache/bin/mustache \ No newline at end of file diff --git a/node_modules/.bin/nanoid b/node_modules/.bin/nanoid new file mode 120000 index 0000000..e2be547 --- /dev/null +++ b/node_modules/.bin/nanoid @@ -0,0 +1 @@ +../nanoid/bin/nanoid.cjs \ No newline at end of file diff --git a/node_modules/.bin/resolve b/node_modules/.bin/resolve new file mode 120000 index 0000000..b6afda6 --- /dev/null +++ b/node_modules/.bin/resolve @@ -0,0 +1 @@ +../resolve/bin/resolve \ No newline at end of file diff --git a/node_modules/.bin/workerd b/node_modules/.bin/workerd new file mode 120000 index 0000000..1b2e13a --- /dev/null +++ b/node_modules/.bin/workerd @@ -0,0 +1 @@ +../workerd/bin/workerd \ No newline at end of file diff --git a/node_modules/.bin/wrangler b/node_modules/.bin/wrangler new file mode 120000 index 0000000..dc4c14f --- /dev/null +++ b/node_modules/.bin/wrangler @@ -0,0 +1 @@ +../wrangler/bin/wrangler.js \ No newline at end of file diff --git a/node_modules/.bin/wrangler2 b/node_modules/.bin/wrangler2 new file mode 120000 index 0000000..dc4c14f --- /dev/null +++ b/node_modules/.bin/wrangler2 @@ -0,0 +1 @@ +../wrangler/bin/wrangler.js \ No newline at end of file diff --git a/node_modules/.cache/wrangler/user-id.json b/node_modules/.cache/wrangler/user-id.json new file mode 100644 index 0000000..96b1e62 --- /dev/null +++ b/node_modules/.cache/wrangler/user-id.json @@ -0,0 +1,3 @@ +{ + "userId": "ad1d0e4c7015e13a515c12756a2a6ede" +} \ No newline at end of file diff --git a/node_modules/.cache/wrangler/wrangler-account.json b/node_modules/.cache/wrangler/wrangler-account.json new file mode 100644 index 0000000..35842e3 --- /dev/null +++ b/node_modules/.cache/wrangler/wrangler-account.json @@ -0,0 +1,6 @@ +{ + "account": { + "id": "668f77372ab4b05320529bb83c2928ea", + "name": "Regdomains111@proton.me's Account" + } +} \ No newline at end of file diff --git a/node_modules/.mf/cf.json b/node_modules/.mf/cf.json new file mode 100644 index 0000000..ff71dcb --- /dev/null +++ b/node_modules/.mf/cf.json @@ -0,0 +1 @@ +{"clientTcpRtt":23,"longitude":"60.65240","httpProtocol":"HTTP/1.1","tlsCipher":"AEAD-AES256-GCM-SHA384","continent":"EU","asn":28890,"clientAcceptEncoding":"br, gzip, deflate","country":"RU","tlsClientExtensionsSha1":"Y7DIC8A6G0/aXviZ8ie/xDbJb7g=","verifiedBotCategory":"","tlsClientAuth":{"certIssuerDNLegacy":"","certIssuerSKI":"","certSubjectDNRFC2253":"","certSubjectDNLegacy":"","certFingerprintSHA256":"","certNotBefore":"","certSKI":"","certSerial":"","certIssuerDN":"","certVerified":"NONE","certNotAfter":"","certSubjectDN":"","certPresented":"0","certRevoked":"0","certIssuerSerial":"","certIssuerDNRFC2253":"","certFingerprintSHA1":""},"tlsExportedAuthenticator":{"clientFinished":"0fc4d9e28c3d34e0c852c6bae52476baacdcee5d3e00ac612eca6bac7e7a643a850c4cf6f57b2caeaf38b07904c6cdcd","clientHandshake":"e94834865fcf1e1cd64f77e8f4ef8d93b2409a737580ddd0f25492501a48e1442319d2313a4e14385dbb93fc36043081","serverHandshake":"6e49bc5f8ec3bbd6e63af7a420607d515cad384d4b7cc62eb7bbdd68cb87356f9836f146c0874fe93241e1924f5a9206","serverFinished":"5b07f3883068f426d1b9dc494040ce47818e2c1e1ee6e7d5e68fb118b9eb4832e05ad456d029336dcaf043e280afe59e"},"tlsVersion":"TLSv1.3","city":"Yekaterinburg","timezone":"Asia/Yekaterinburg","colo":"DME","tlsClientHelloLength":"380","edgeRequestKeepAliveStatus":1,"postalCode":"620066","region":"Sverdlovsk Oblast","latitude":"56.84390","requestPriority":"","regionCode":"SVE","asOrganization":"Insys","tlsClientRandom":"GWdMwqExACWZOQ8G7QEPQpzBqWgXy21ul7PY3QkCudg=","botManagement":{"corporateProxy":false,"verifiedBot":false,"jsDetection":{"passed":false},"staticResource":false,"detectionIds":{},"score":99}} \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..47a82b5 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,886 @@ +{ + "name": "one-link", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@cloudflare/kv-asset-handler": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.3.2.tgz", + "integrity": "sha512-EeEjMobfuJrwoctj7FA1y1KEbM0+Q1xSjobIEyie9k4haVEBB7vkDvsasw1pM3rO39mL2akxIAzLMUAtrMHZhA==", + "dev": true, + "dependencies": { + "mime": "^3.0.0" + }, + "engines": { + "node": ">=16.13" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20240419.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20240419.0.tgz", + "integrity": "sha512-z4etQSPiD5Gcjs962LiC7ZdmXnN6SGof5KrYoFiSI9X9kUvpuGH/lnjVVPd+NnVNeDU2kzmcAIgyZjkjTaqVXQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workers-types": { + "version": "4.20240512.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20240512.0.tgz", + "integrity": "sha512-o2yTEWg+YK/I1t/Me+dA0oarO0aCbjibp6wSeaw52DSE9tDyKJ7S+Qdyw/XsMrKn4t8kF6f/YOba+9O4MJfW9w==", + "dev": true + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild-plugins/node-globals-polyfill": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@esbuild-plugins/node-globals-polyfill/-/node-globals-polyfill-0.2.3.tgz", + "integrity": "sha512-r3MIryXDeXDOZh7ih1l/yE9ZLORCd5e8vWg02azWRGj5SPTuoh69A2AIyn0Z31V/kHBfZ4HgWJ+OK3GTTwLmnw==", + "dev": true, + "peerDependencies": { + "esbuild": "*" + } + }, + "node_modules/@esbuild-plugins/node-modules-polyfill": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/@esbuild-plugins/node-modules-polyfill/-/node-modules-polyfill-0.2.2.tgz", + "integrity": "sha512-LXV7QsWJxRuMYvKbiznh+U1ilIop3g2TeKRzUxOG5X3YITc8JyyTa90BmLwqqv0YnX4v32CSlG+vsziZp9dMvA==", + "dev": true, + "dependencies": { + "escape-string-regexp": "^4.0.0", + "rollup-plugin-node-polyfills": "^0.2.1" + }, + "peerDependencies": { + "esbuild": "*" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.19.tgz", + "integrity": "sha512-80wEoCfF/hFKM6WE1FyBHc9SfUblloAWx6FJkFWTWiCoht9Mc0ARGEM47e67W9rI09YoUxJL68WHfDRYEAvOhg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@fastify/busboy": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz", + "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==", + "dev": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@types/node": { + "version": "20.12.11", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.12.11.tgz", + "integrity": "sha512-vDg9PZ/zi+Nqp6boSOT7plNuthRugEKixDv5sFTIpkE89MmNtEArAShI4mxuX2+UrLEe9pxC1vm2cjm9YlWbJw==", + "dev": true, + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/node-forge": { + "version": "1.3.11", + "resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.11.tgz", + "integrity": "sha512-FQx220y22OKNTqaByeBGqHWYz4cl94tpcxeFdvBo3wjG6XPBuZ0BNgNZRV5J5TFmmcsJ4IzsLkmGRiQbnYsBEQ==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/acorn": { + "version": "8.11.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", + "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.2.tgz", + "integrity": "sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/as-table": { + "version": "1.0.55", + "resolved": "https://registry.npmjs.org/as-table/-/as-table-1.0.55.tgz", + "integrity": "sha512-xvsWESUJn0JN421Xb9MQw6AsMHRCUknCe0Wjlxvjud80mU4E6hQf1A6NzQKcYNmYw62MfzEtXc+badstZP3JpQ==", + "dev": true, + "dependencies": { + "printable-characters": "^1.0.42" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/blake3-wasm": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", + "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", + "dev": true + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/capnp-ts": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/capnp-ts/-/capnp-ts-0.7.0.tgz", + "integrity": "sha512-XKxXAC3HVPv7r674zP0VC3RTXz+/JKhfyw94ljvF80yynK6VkTnqE3jMuN8b3dUVmmc43TjyxjW4KTsmB3c86g==", + "dev": true, + "dependencies": { + "debug": "^4.3.1", + "tslib": "^2.2.0" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-2.0.2.tgz", + "integrity": "sha512-ND9qDTLc6diwj+Xe5cdAgVTbLVdXbtxTJRXRhli8Mowuaan+0EJOtdqJ0QCHNSSPyoXGx9HX2/VMnKeC34AChA==", + "dev": true + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/esbuild": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.19.tgz", + "integrity": "sha512-XQ0jAPFkK/u3LcVRcvVHQcTIqD6E2H1fvZMA5dQPSOWb3suUbWbfbRf94pjc0bNzRYLfIrDRQXr7X+LHIm5oHw==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/android-arm": "0.17.19", + "@esbuild/android-arm64": "0.17.19", + "@esbuild/android-x64": "0.17.19", + "@esbuild/darwin-arm64": "0.17.19", + "@esbuild/darwin-x64": "0.17.19", + "@esbuild/freebsd-arm64": "0.17.19", + "@esbuild/freebsd-x64": "0.17.19", + "@esbuild/linux-arm": "0.17.19", + "@esbuild/linux-arm64": "0.17.19", + "@esbuild/linux-ia32": "0.17.19", + "@esbuild/linux-loong64": "0.17.19", + "@esbuild/linux-mips64el": "0.17.19", + "@esbuild/linux-ppc64": "0.17.19", + "@esbuild/linux-riscv64": "0.17.19", + "@esbuild/linux-s390x": "0.17.19", + "@esbuild/linux-x64": "0.17.19", + "@esbuild/netbsd-x64": "0.17.19", + "@esbuild/openbsd-x64": "0.17.19", + "@esbuild/sunos-x64": "0.17.19", + "@esbuild/win32-arm64": "0.17.19", + "@esbuild/win32-ia32": "0.17.19", + "@esbuild/win32-x64": "0.17.19" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/estree-walker": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", + "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", + "dev": true + }, + "node_modules/exit-hook": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-2.2.1.tgz", + "integrity": "sha512-eNTPlAD67BmP31LDINZ3U7HSF8l57TxOY2PmBJ1shpCvpnxBF93mWCE8YHBnXs8qiUZJc9WDcWIeC3a2HIAMfw==", + "dev": true, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "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==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-source": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/get-source/-/get-source-2.0.12.tgz", + "integrity": "sha512-X5+4+iD+HoSeEED+uwrQ07BOQr0kEDFMVqqpBuI+RaZBpBpHCuXxo70bjar6f0b0u/DQJsJ7ssurpP0V60Az+w==", + "dev": true, + "dependencies": { + "data-uri-to-buffer": "^2.0.0", + "source-map": "^0.6.1" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.3.6.tgz", + "integrity": "sha512-2IqXwrxWF4tG2AR7b5tMYn+KEnWK8UvdC/NUSbOKWj/Kj11OJqel58FxyiXLK5CcKLiL8aGtTe4lkBKXyaHMBQ==", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.13.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz", + "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==", + "dev": true, + "dependencies": { + "hasown": "^2.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/magic-string": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz", + "integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.8" + } + }, + "node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "dev": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/miniflare": { + "version": "3.20240419.1", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-3.20240419.1.tgz", + "integrity": "sha512-Q9n0W07uUD/u0c/b03E4iogeXOAMjZnE3P7B5Yi8sPaZAx6TYWwjurGBja+Pg2yILN2iMaliEobfVyAKss33cA==", + "dev": true, + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "acorn": "^8.8.0", + "acorn-walk": "^8.2.0", + "capnp-ts": "^0.7.0", + "exit-hook": "^2.2.1", + "glob-to-regexp": "^0.4.1", + "stoppable": "^1.1.0", + "undici": "^5.28.2", + "workerd": "1.20240419.0", + "ws": "^8.11.0", + "youch": "^3.2.2", + "zod": "^3.20.6" + }, + "bin": { + "miniflare": "bootstrap.js" + }, + "engines": { + "node": ">=16.13" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "dev": true, + "bin": { + "mustache": "bin/mustache" + } + }, + "node_modules/nanoid": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", + "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-forge": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz", + "integrity": "sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==", + "dev": true, + "engines": { + "node": ">= 6.13.0" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/path-to-regexp": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.2.2.tgz", + "integrity": "sha512-GQX3SSMokngb36+whdpRXE+3f9V8UzyAorlYvOGx87ufGHehNTn5lCxrKtLyZ4Yl/wEKnNnr98ZzOwwDZV5ogw==", + "dev": true + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/printable-characters": { + "version": "1.0.42", + "resolved": "https://registry.npmjs.org/printable-characters/-/printable-characters-1.0.42.tgz", + "integrity": "sha512-dKp+C4iXWK4vVYZmYSd0KBH5F/h1HoZRsbJ82AVKRO3PEo8L4lBS/vLwhVtpwwuYcoIsVY+1JYKR268yn480uQ==", + "dev": true + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "dev": true, + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve.exports": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.2.tgz", + "integrity": "sha512-X2UW6Nw3n/aMgDVy+0rSqgHlv39WZAlZrXCdnbyEiKm17DSqHX4MmQMaST3FbeWR5FTuRcUwYAziZajji0Y7mg==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/rollup-plugin-inject": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rollup-plugin-inject/-/rollup-plugin-inject-3.0.2.tgz", + "integrity": "sha512-ptg9PQwzs3orn4jkgXJ74bfs5vYz1NCZlSQMBUA0wKcGp5i5pA1AO3fOUEte8enhGUC+iapTCzEWw2jEFFUO/w==", + "deprecated": "This package has been deprecated and is no longer maintained. Please use @rollup/plugin-inject.", + "dev": true, + "dependencies": { + "estree-walker": "^0.6.1", + "magic-string": "^0.25.3", + "rollup-pluginutils": "^2.8.1" + } + }, + "node_modules/rollup-plugin-node-polyfills": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/rollup-plugin-node-polyfills/-/rollup-plugin-node-polyfills-0.2.1.tgz", + "integrity": "sha512-4kCrKPTJ6sK4/gLL/U5QzVT8cxJcofO0OU74tnB19F40cmuAKSzH5/siithxlofFEjwvw1YAhPmbvGNA6jEroA==", + "dev": true, + "dependencies": { + "rollup-plugin-inject": "^3.0.0" + } + }, + "node_modules/rollup-pluginutils": { + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz", + "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==", + "dev": true, + "dependencies": { + "estree-walker": "^0.6.1" + } + }, + "node_modules/selfsigned": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-2.4.1.tgz", + "integrity": "sha512-th5B4L2U+eGLq1TVh7zNRGBapioSORUeymIydxgFpwww9d2qyKvtuPU2jJuHvYAwwqi2Y596QBL3eEqcPEYL8Q==", + "dev": true, + "dependencies": { + "@types/node-forge": "^1.3.0", + "node-forge": "^1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "deprecated": "Please use @jridgewell/sourcemap-codec instead", + "dev": true + }, + "node_modules/stacktracey": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/stacktracey/-/stacktracey-2.1.8.tgz", + "integrity": "sha512-Kpij9riA+UNg7TnphqjH7/CzctQ/owJGNbFkfEeve4Z4uxT5+JapVLFXcsurIfN34gnTWZNJ/f7NMG0E8JDzTw==", + "dev": true, + "dependencies": { + "as-table": "^1.0.36", + "get-source": "^2.0.12" + } + }, + "node_modules/stoppable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz", + "integrity": "sha512-KXDYZ9dszj6bzvnEMRYvxgeTHU74QBFL54XKtP3nyMuJ81CFYtABZ3bAzL2EdFUaEwJOBOgENyFj3R7oTzDyyw==", + "dev": true, + "engines": { + "node": ">=4", + "npm": ">=6" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==", + "dev": true + }, + "node_modules/undici": { + "version": "5.28.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.4.tgz", + "integrity": "sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==", + "dev": true, + "dependencies": { + "@fastify/busboy": "^2.0.0" + }, + "engines": { + "node": ">=14.0" + } + }, + "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==", + "dev": true + }, + "node_modules/workerd": { + "version": "1.20240419.0", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20240419.0.tgz", + "integrity": "sha512-9yV98KpkQgG+bdEsKEW8i1AYZgxns6NVSfdOVEB2Ue1pTMtIEYfUyqUE+O2amisRrfaC3Pw4EvjtTmVaoetfeg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20240419.0", + "@cloudflare/workerd-darwin-arm64": "1.20240419.0", + "@cloudflare/workerd-linux-64": "1.20240419.0", + "@cloudflare/workerd-linux-arm64": "1.20240419.0", + "@cloudflare/workerd-windows-64": "1.20240419.0" + } + }, + "node_modules/wrangler": { + "version": "3.55.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-3.55.0.tgz", + "integrity": "sha512-VhtCioKxOdVqkHa8jQ6C6bX3by2Ko0uM0DKzrA+6lBZvfDUlGDWSOPiG+1fOHBHj2JTVBntxWCztXP6L+Udr8w==", + "dev": true, + "dependencies": { + "@cloudflare/kv-asset-handler": "0.3.2", + "@esbuild-plugins/node-globals-polyfill": "^0.2.3", + "@esbuild-plugins/node-modules-polyfill": "^0.2.2", + "blake3-wasm": "^2.1.5", + "chokidar": "^3.5.3", + "esbuild": "0.17.19", + "miniflare": "3.20240419.1", + "nanoid": "^3.3.3", + "path-to-regexp": "^6.2.0", + "resolve": "^1.22.8", + "resolve.exports": "^2.0.2", + "selfsigned": "^2.0.1", + "source-map": "0.6.1", + "xxhash-wasm": "^1.0.1" + }, + "bin": { + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=16.17.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "peerDependencies": { + "@cloudflare/workers-types": "^4.20240419.0" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.17.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.0.tgz", + "integrity": "sha512-uJq6108EgZMAl20KagGkzCKfMEjxmKvZHG7Tlq0Z6nOky7YF7aq4mOx6xK8TJ/i1LeK4Qus7INktacctDgY8Ow==", + "dev": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xxhash-wasm": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.0.2.tgz", + "integrity": "sha512-ibF0Or+FivM9lNrg+HGJfVX8WJqgo+kCLDc4vx6xMeTce7Aj+DLttKbxxRR/gNLSAelRc1omAPlJ77N/Jem07A==", + "dev": true + }, + "node_modules/youch": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/youch/-/youch-3.3.3.tgz", + "integrity": "sha512-qSFXUk3UZBLfggAW3dJKg0BMblG5biqSF8M34E06o5CSsZtH92u9Hqmj2RzGiHDi64fhe83+4tENFP2DB6t6ZA==", + "dev": true, + "dependencies": { + "cookie": "^0.5.0", + "mustache": "^4.2.0", + "stacktracey": "^2.1.8" + } + }, + "node_modules/zod": { + "version": "3.23.8", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", + "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/node_modules/@cloudflare/kv-asset-handler/README.md b/node_modules/@cloudflare/kv-asset-handler/README.md new file mode 100644 index 0000000..467b4e4 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/README.md @@ -0,0 +1,346 @@ +# @cloudflare/kv-asset-handler + +[![npm](https://img.shields.io/npm/v/@cloudflare/kv-asset-handler.svg)](https://www.npmjs.com/package/@cloudflare/kv-asset-handler)   +[![Run npm tests](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml)   +[![Lint Markdown](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml)   + +`kv-asset-handler` is an open-source library for managing the retrieval of static assets from [Workers KV](https://developers.cloudflare.com/workers/runtime-apis/kv) inside of a [Cloudflare Workers](https://workers.dev) function. `kv-asset-handler` is designed for use with [Workers Sites](https://developers.cloudflare.com/workers/platform/sites), a feature included in [Wrangler](https://github.com/cloudflare/wrangler), our command-line tool for deploying Workers projects. + +`kv-asset-handler` runs as part of a Cloudflare Workers function, so it allows you to customize _how_ and _when_ your static assets are loaded, as well as customize how those assets behave before they're sent to the client. + +Most users and sites will not need these customizations, and just want to serve their statically built applications. For that simple use-case, you can check out [Cloudflare Pages](https://pages.cloudflare.com), our batteries-included approach to deploying static sites on Cloudflare's edge network. Workers Sites was designed as a precursor to Cloudflare Pages, so check out Pages if you just want to deploy your static site without any special customizations! + +For users who _do_ want to customize their assets, and want to build complex experiences on top of their static assets, `kv-asset-handler` (and the default [Workers Sites template](https://github.com/cloudflare/worker-sites-template), which is provided for use with Wrangler + Workers Sites) allows you to customize caching behavior, headers, and anything else about how your Workers function loads the static assets for your site stored in Workers KV. + +The Cloudflare Workers Discord server is an active place where Workers users get help, share feedback, and collaborate on making our platform better. The `#workers` channel in particular is a great place to chat about `kv-asset-handler`, and building cool experiences for your users using these tools! If you have questions, want to share what you're working on, or give feedback, [join us in Discord and say hello](https://discord.cloudflare.com)! + +- [Installation](#installation) +- [Usage](#usage) +- [`getAssetFromKV`](#getassetfromkv) + - [Example](#example) + * [Return](#return) + * [Optional Arguments](#optional-arguments) + - [`mapRequestToAsset`](#maprequesttoasset) + - [Example](#example-1) + - [`cacheControl`](#cachecontrol) + - [`browserTTL`](#browserttl) + - [`edgeTTL`](#edgettl) + - [`bypassCache`](#bypasscache) + - [`ASSET_NAMESPACE` (required for ES Modules)](#asset_namespace-required-for-es-modules) + - [`ASSET_MANIFEST` (required for ES Modules)](#asset_manifest-required-for-es-modules) + - [`defaultETag`](#defaultetag-optional) + +* [Helper functions](#helper-functions) + - [`mapRequestToAsset`](#maprequesttoasset-1) + - [`serveSinglePageApp`](#servesinglepageapp) +* [Cache revalidation and etags](#cache-revalidation-and-etags) + +## Installation + +Add this package to your `package.json` by running this in the root of your +project's directory: + +``` +npm i @cloudflare/kv-asset-handler +``` + +## Usage + +This package was designed to work with [Worker Sites](https://workers.cloudflare.com/sites). + +## `getAssetFromKV` + +getAssetFromKV(Evt) => Promise + +`getAssetFromKV` is an async function that takes an `Evt` object (containing a `Request` and a [`waitUntil`](https://developers.cloudflare.com/workers/runtime-apis/fetch-event#waituntil)) and returns a `Response` object if the request matches an asset in KV, otherwise it will throw a `KVError`. + +#### Example + +This example checks for the existence of a value in KV, and returns it if it's there, and returns a 404 if it is not. It also serves index.html from `/`. + +### Return + +`getAssetFromKV` returns a `Promise` with `Response` being the body of the asset requested. + +Known errors to be thrown are: + +- MethodNotAllowedError +- NotFoundError +- InternalError + +#### ES Modules + +```js +import manifestJSON from "__STATIC_CONTENT_MANIFEST"; +import { + getAssetFromKV, + MethodNotAllowedError, + NotFoundError, +} from "@cloudflare/kv-asset-handler"; + +const assetManifest = JSON.parse(manifestJSON); + +export default { + async fetch(request, env, ctx) { + if (request.url.includes("/docs")) { + try { + return await getAssetFromKV( + { + request, + waitUntil(promise) { + return ctx.waitUntil(promise); + }, + }, + { + ASSET_NAMESPACE: env.__STATIC_CONTENT, + ASSET_MANIFEST: assetManifest, + } + ); + } catch (e) { + if (e instanceof NotFoundError) { + // ... + } else if (e instanceof MethodNotAllowedError) { + // ... + } else { + return new Response("An unexpected error occurred", { status: 500 }); + } + } + } else return fetch(request); + }, +}; +``` + +#### Service Worker + +```js +import { + getAssetFromKV, + MethodNotAllowedError, + NotFoundError, +} from "@cloudflare/kv-asset-handler"; + +addEventListener("fetch", (event) => { + event.respondWith(handleEvent(event)); +}); + +async function handleEvent(event) { + if (event.request.url.includes("/docs")) { + try { + return await getAssetFromKV(event); + } catch (e) { + if (e instanceof NotFoundError) { + // ... + } else if (e instanceof MethodNotAllowedError) { + // ... + } else { + return new Response("An unexpected error occurred", { status: 500 }); + } + } + } else return fetch(event.request); +} +``` + +### Optional Arguments + +You can customize the behavior of `getAssetFromKV` by passing the following properties as an object into the second argument. + +``` +getAssetFromKV(event, { mapRequestToAsset: ... }) +``` + +#### `mapRequestToAsset` + +mapRequestToAsset(Request) => Request + +Maps the incoming request to the value that will be looked up in Cloudflare's KV + +By default, mapRequestToAsset is set to the exported function [`mapRequestToAsset`](#maprequesttoasset-1). This works for most static site generators, but you can customize this behavior by passing your own function as `mapRequestToAsset`. The function should take a `Request` object as its only argument, and return a new `Request` object with an updated path to be looked up in the asset manifest/KV. + +For SPA mapping pass in the [`serveSinglePageApp`](#servesinglepageapp) function + +#### Example + +Strip `/docs` from any incoming request before looking up an asset in Cloudflare's KV. + +```js +import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler' +... +const customKeyModifier = request => { + let url = request.url + //custom key mapping optional + url = url.replace('/docs', '').replace(/^\/+/, '') + return mapRequestToAsset(new Request(url, request)) +} +let asset = await getAssetFromKV(event, { mapRequestToAsset: customKeyModifier }) +``` + +#### `cacheControl` + +type: object + +`cacheControl` allows you to configure options for both the Cloudflare Cache accessed by your Worker, and the browser cache headers sent along with your Workers' responses. The default values are as follows: + +```javascript +let cacheControl = { + browserTTL: null, // do not set cache control ttl on responses + edgeTTL: 2 * 60 * 60 * 24, // 2 days + bypassCache: false, // do not bypass Cloudflare's cache +}; +``` + +##### `browserTTL` + +type: number | null +nullable: true + +Sets the `Cache-Control: max-age` header on the response returned from the Worker. By default set to `null` which will not add the header at all. + +##### `edgeTTL` + +type: number | null +nullable: true + +Sets the `Cache-Control: max-age` header on the response used as the edge cache key. By default set to 2 days (`2 * 60 * 60 * 24`). When null will not cache on the edge at all. + +##### `bypassCache` + +type: boolean + +Determines whether to cache requests on Cloudflare's edge cache. By default set to `false` (recommended for production builds). Useful for development when you need to eliminate the cache's effect on testing. + +#### `ASSET_NAMESPACE` (required for ES Modules) + +type: KV Namespace Binding + +The binding name to the KV Namespace populated with key/value entries of files for the Worker to serve. By default, Workers Sites uses a [binding to a Workers KV Namespace](https://developers.cloudflare.com/workers/reference/storage/api/#namespaces) named `__STATIC_CONTENT`. + +It is further assumed that this namespace consists of static assets such as HTML, CSS, JavaScript, or image files, keyed off of a relative path that roughly matches the assumed URL pathname of the incoming request. + +In ES Modules format, this argument is required, and can be gotten from `env`. + +##### ES Module + +```js +return getAssetFromKV( + { + request, + waitUntil(promise) { + return ctx.waitUntil(promise) + }, + }, + { + ASSET_NAMESPACE: env.__STATIC_CONTENT, + }, +) +``` + +##### Service Worker + +``` +return getAssetFromKV(event, { ASSET_NAMESPACE: MY_NAMESPACE }) +``` + +#### `ASSET_MANIFEST` (required for ES Modules) + +type: text blob (JSON formatted) or object + +The mapping of requested file path to the key stored on Cloudflare. + +Workers Sites with Wrangler bundles up a text blob that maps request paths to content-hashed keys that are generated by Wrangler as a cache-busting measure. If this option/binding is not present, the function will fallback to using the raw pathname to look up your asset in KV. If, for whatever reason, you have rolled your own implementation of this, you can include your own by passing a stringified JSON object where the keys are expected paths, and the values are the expected keys in your KV namespace. + +In ES Modules format, this argument is required, and can be imported. + +##### ES Module + +```js +import manifestJSON from '__STATIC_CONTENT_MANIFEST' +let manifest = JSON.parse(manifestJSON) +manifest['index.html'] = 'index.special.html' + +return getAssetFromKV( + { + request, + waitUntil(promise) { + return ctx.waitUntil(promise) + }, + }, + { + ASSET_MANIFEST: manifest, + // ... + }, +) +``` + +##### Service Worker + +``` +let assetManifest = { "index.html": "index.special.html" } +return getAssetFromKV(event, { ASSET_MANIFEST: assetManifest }) +``` + +#### `defaultMimeType` (optional) + +type: string + +This is the mime type that will be used for files with unrecognized or missing extensions. The default value is `'text/plain'`. + +If you are serving a static site and would like to use extensionless HTML files instead of index.html files, set this to `'text/html'`. + +#### `defaultDocument` (optional) + +type: string + +This is the default document that will be concatenated for requests ends in `'/'` or without a valid mime type like `'/about'` or `'/about.me'`. The default value is `'index.html'`. + +#### `defaultETag` (optional) + +type: `'strong' | 'weak'` + +This determines the format of the response [ETag header](https://developer.mozilla.org/docs/Web/HTTP/Headers/ETag). If the resource is in the cache, the ETag will always be weakened before being returned. +The default value is `'strong'`. + +# Helper functions + +## `mapRequestToAsset` + +mapRequestToAsset(Request) => Request + +The default function for mapping incoming requests to keys in Cloudflare's KV. + +Takes any path that ends in `/` or evaluates to an HTML file and appends `index.html` or `/index.html` for lookup in your Workers KV namespace. + +## `serveSinglePageApp` + +serveSinglePageApp(Request) => Request + +A custom handler for mapping requests to a single root: `index.html`. The most common use case is single-page applications - frameworks with in-app routing - such as React Router, VueJS, etc. It takes zero arguments. + +```js +import { getAssetFromKV, serveSinglePageApp } from '@cloudflare/kv-asset-handler' +... +let asset = await getAssetFromKV(event, { mapRequestToAsset: serveSinglePageApp }) +``` + +# Cache revalidation and etags + +All responses served from cache (including those with `cf-cache-status: MISS`) include an `etag` response header that identifies the version of the resource. The `etag` value is identical to the path key used in the `ASSET_MANIFEST`. It is updated each time an asset changes and looks like this: `etag: ..` (ex. `etag: index.54321.html`). + +Resources served with an `etag` allow browsers to use the `if-none-match` request header to make conditional requests for that resource in the future. This has two major benefits: + +- When a request's `if-none-match` value matches the `etag` of the resource in Cloudflare cache, Cloudflare will send a `304 Not Modified` response without a body, saving bandwidth. +- Changes to a file on the server are immediately reflected in the browser - even when the cache control directive `max-age` is unexpired. + +#### Disable the `etag` + +To turn `etags` **off**, you must bypass cache: + +```js +/* Turn etags off */ +let cacheControl = { + bypassCache: true, +}; +``` + +#### Syntax and comparison context + +`kv-asset-handler` sets and evaluates etags as [strong validators](https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests#Strong_validation). To preserve `etag` integrity, the format of the value deviates from the [RFC2616 recommendation to enclose the `etag` with quotation marks](https://tools.ietf.org/html/rfc2616#section-3.11). This is intentional. Cloudflare cache applies the `W/` prefix to all `etags` that use quoted-strings -- a process that converts the `etag` to a "weak validator" when served to a client. diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts new file mode 100644 index 0000000..5c0ce61 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts @@ -0,0 +1,36 @@ +import { CacheControl, InternalError, MethodNotAllowedError, NotFoundError, Options } from "./types"; +declare global { + var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string; +} +/** + * maps the path of incoming request to the request pathKey to look up + * in bucket and in cache + * e.g. for a path '/' returns '/index.html' which serves + * the content of bucket/index.html + * @param {Request} request incoming request + */ +declare const mapRequestToAsset: (request: Request, options?: Partial) => Request; +/** + * maps the path of incoming request to /index.html if it evaluates to + * any HTML file. + * @param {Request} request incoming request + */ +declare function serveSinglePageApp(request: Request, options?: Partial): Request; +/** + * takes the path of the incoming request, gathers the appropriate content from KV, and returns + * the response + * + * @param {FetchEvent} event the fetch event of the triggered request + * @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options + * @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser + * @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up + * @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references + * @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV + * */ +type Evt = { + request: Request; + waitUntil: (promise: Promise) => void; +}; +declare const getAssetFromKV: (event: Evt, options?: Partial) => Promise; +export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp }; +export { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError, }; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/index.js b/node_modules/@cloudflare/kv-asset-handler/dist/index.js new file mode 100644 index 0000000..654a333 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/index.js @@ -0,0 +1,275 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.serveSinglePageApp = exports.mapRequestToAsset = exports.getAssetFromKV = void 0; +const mime = require("mime"); +const types_1 = require("./types"); +Object.defineProperty(exports, "InternalError", { enumerable: true, get: function () { return types_1.InternalError; } }); +Object.defineProperty(exports, "MethodNotAllowedError", { enumerable: true, get: function () { return types_1.MethodNotAllowedError; } }); +Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return types_1.NotFoundError; } }); +const defaultCacheControl = { + browserTTL: null, + edgeTTL: 2 * 60 * 60 * 24, + bypassCache: false, // do not bypass Cloudflare's cache +}; +const parseStringAsObject = (maybeString) => typeof maybeString === "string" + ? JSON.parse(maybeString) + : maybeString; +const getAssetFromKVDefaultOptions = { + ASSET_NAMESPACE: typeof __STATIC_CONTENT !== "undefined" ? __STATIC_CONTENT : undefined, + ASSET_MANIFEST: typeof __STATIC_CONTENT_MANIFEST !== "undefined" + ? parseStringAsObject(__STATIC_CONTENT_MANIFEST) + : {}, + cacheControl: defaultCacheControl, + defaultMimeType: "text/plain", + defaultDocument: "index.html", + pathIsEncoded: false, + defaultETag: "strong", +}; +function assignOptions(options) { + // Assign any missing options passed in to the default + // options.mapRequestToAsset is handled manually later + return Object.assign({}, getAssetFromKVDefaultOptions, options); +} +/** + * maps the path of incoming request to the request pathKey to look up + * in bucket and in cache + * e.g. for a path '/' returns '/index.html' which serves + * the content of bucket/index.html + * @param {Request} request incoming request + */ +const mapRequestToAsset = (request, options) => { + options = assignOptions(options); + const parsedUrl = new URL(request.url); + let pathname = parsedUrl.pathname; + if (pathname.endsWith("/")) { + // If path looks like a directory append options.defaultDocument + // e.g. If path is /about/ -> /about/index.html + pathname = pathname.concat(options.defaultDocument); + } + else if (!mime.getType(pathname)) { + // If path doesn't look like valid content + // e.g. /about.me -> /about.me/index.html + pathname = pathname.concat("/" + options.defaultDocument); + } + parsedUrl.pathname = pathname; + return new Request(parsedUrl.toString(), request); +}; +exports.mapRequestToAsset = mapRequestToAsset; +/** + * maps the path of incoming request to /index.html if it evaluates to + * any HTML file. + * @param {Request} request incoming request + */ +function serveSinglePageApp(request, options) { + options = assignOptions(options); + // First apply the default handler, which already has logic to detect + // paths that should map to HTML files. + request = mapRequestToAsset(request, options); + const parsedUrl = new URL(request.url); + // Detect if the default handler decided to map to + // a HTML file in some specific directory. + if (parsedUrl.pathname.endsWith(".html")) { + // If expected HTML file was missing, just return the root index.html (or options.defaultDocument) + return new Request(`${parsedUrl.origin}/${options.defaultDocument}`, request); + } + else { + // The default handler decided this is not an HTML page. It's probably + // an image, CSS, or JS file. Leave it as-is. + return request; + } +} +exports.serveSinglePageApp = serveSinglePageApp; +const getAssetFromKV = async (event, options) => { + options = assignOptions(options); + const request = event.request; + const ASSET_NAMESPACE = options.ASSET_NAMESPACE; + const ASSET_MANIFEST = parseStringAsObject(options.ASSET_MANIFEST); + if (typeof ASSET_NAMESPACE === "undefined") { + throw new types_1.InternalError(`there is no KV namespace bound to the script`); + } + const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, ""); // strip any preceding /'s + let pathIsEncoded = options.pathIsEncoded; + let requestKey; + // if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions + // otherwise handle request as normal, with default mapRequestToAsset below + if (options.mapRequestToAsset) { + requestKey = options.mapRequestToAsset(request); + } + else if (ASSET_MANIFEST[rawPathKey]) { + requestKey = request; + } + else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) { + pathIsEncoded = true; + requestKey = request; + } + else { + const mappedRequest = mapRequestToAsset(request); + const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(/^\/+/, ""); + if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) { + pathIsEncoded = true; + requestKey = mappedRequest; + } + else { + // use default mapRequestToAsset + requestKey = mapRequestToAsset(request, options); + } + } + const SUPPORTED_METHODS = ["GET", "HEAD"]; + if (!SUPPORTED_METHODS.includes(requestKey.method)) { + throw new types_1.MethodNotAllowedError(`${requestKey.method} is not a valid request method`); + } + const parsedUrl = new URL(requestKey.url); + const pathname = pathIsEncoded + ? decodeURIComponent(parsedUrl.pathname) + : parsedUrl.pathname; // decode percentage encoded path only when necessary + // pathKey is the file path to look up in the manifest + let pathKey = pathname.replace(/^\/+/, ""); // remove prepended / + // @ts-ignore + const cache = caches.default; + let mimeType = mime.getType(pathKey) || options.defaultMimeType; + if (mimeType.startsWith("text") || mimeType === "application/javascript") { + mimeType += "; charset=utf-8"; + } + let shouldEdgeCache = false; // false if storing in KV by raw file path i.e. no hash + // check manifest for map from file path to hash + if (typeof ASSET_MANIFEST !== "undefined") { + if (ASSET_MANIFEST[pathKey]) { + pathKey = ASSET_MANIFEST[pathKey]; + // if path key is in asset manifest, we can assume it contains a content hash and can be cached + shouldEdgeCache = true; + } + } + // TODO this excludes search params from cache, investigate ideal behavior + let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request); + // if argument passed in for cacheControl is a function then + // evaluate that function. otherwise return the Object passed in + // or default Object + const evalCacheOpts = (() => { + switch (typeof options.cacheControl) { + case "function": + return options.cacheControl(request); + case "object": + return options.cacheControl; + default: + return defaultCacheControl; + } + })(); + // formats the etag depending on the response context. if the entityId + // is invalid, returns an empty string (instead of null) to prevent the + // the potentially disastrous scenario where the value of the Etag resp + // header is "null". Could be modified in future to base64 encode etc + const formatETag = (entityId = pathKey, validatorType = options.defaultETag) => { + if (!entityId) { + return ""; + } + switch (validatorType) { + case "weak": + if (!entityId.startsWith("W/")) { + if (entityId.startsWith(`"`) && entityId.endsWith(`"`)) { + return `W/${entityId}`; + } + return `W/"${entityId}"`; + } + return entityId; + case "strong": + if (entityId.startsWith(`W/"`)) { + entityId = entityId.replace("W/", ""); + } + if (!entityId.endsWith(`"`)) { + entityId = `"${entityId}"`; + } + return entityId; + default: + return ""; + } + }; + options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts); + // override shouldEdgeCache if options say to bypassCache + if (options.cacheControl.bypassCache || + options.cacheControl.edgeTTL === null || + request.method == "HEAD") { + shouldEdgeCache = false; + } + // only set max-age if explicitly passed in a number as an arg + const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === "number"; + let response = null; + if (shouldEdgeCache) { + response = await cache.match(cacheKey); + } + if (response) { + if (response.status > 300 && response.status < 400) { + if (response.body && "cancel" in Object.getPrototypeOf(response.body)) { + // Body exists and environment supports readable streams + response.body.cancel(); + } + else { + // Environment doesnt support readable streams, or null repsonse body. Nothing to do + } + response = new Response(null, response); + } + else { + // fixes #165 + let opts = { + headers: new Headers(response.headers), + status: 0, + statusText: "", + }; + opts.headers.set("cf-cache-status", "HIT"); + if (response.status) { + opts.status = response.status; + opts.statusText = response.statusText; + } + else if (opts.headers.has("Content-Range")) { + opts.status = 206; + opts.statusText = "Partial Content"; + } + else { + opts.status = 200; + opts.statusText = "OK"; + } + response = new Response(response.body, opts); + } + } + else { + const body = await ASSET_NAMESPACE.get(pathKey, "arrayBuffer"); + if (body === null) { + throw new types_1.NotFoundError(`could not find ${pathKey} in your content namespace`); + } + response = new Response(body); + if (shouldEdgeCache) { + response.headers.set("Accept-Ranges", "bytes"); + response.headers.set("Content-Length", String(body.byteLength)); + // set etag before cache insertion + if (!response.headers.has("etag")) { + response.headers.set("etag", formatETag(pathKey)); + } + // determine Cloudflare cache behavior + response.headers.set("Cache-Control", `max-age=${options.cacheControl.edgeTTL}`); + event.waitUntil(cache.put(cacheKey, response.clone())); + response.headers.set("CF-Cache-Status", "MISS"); + } + } + response.headers.set("Content-Type", mimeType); + if (response.status === 304) { + let etag = formatETag(response.headers.get("etag")); + let ifNoneMatch = cacheKey.headers.get("if-none-match"); + let proxyCacheStatus = response.headers.get("CF-Cache-Status"); + if (etag) { + if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === "MISS") { + response.headers.set("CF-Cache-Status", "EXPIRED"); + } + else { + response.headers.set("CF-Cache-Status", "REVALIDATED"); + } + response.headers.set("etag", formatETag(etag, "weak")); + } + } + if (shouldSetBrowserCache) { + response.headers.set("Cache-Control", `max-age=${options.cacheControl.browserTTL}`); + } + else { + response.headers.delete("Cache-Control"); + } + return response; +}; +exports.getAssetFromKV = getAssetFromKV; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts new file mode 100644 index 0000000..f829335 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts @@ -0,0 +1,14 @@ +export declare const getEvent: (request: Request) => any; +export declare const mockKV: (store: any) => { + get: (path: string) => any; +}; +export declare const mockManifest: () => string; +export declare const mockCaches: () => { + default: { + match(key: any): Promise; + put(key: any, val: Response): Promise; + }; +}; +export declare function mockRequestScope(): void; +export declare function mockGlobalScope(): void; +export declare const sleep: (milliseconds: number) => Promise; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/mocks.js b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.js new file mode 100644 index 0000000..53fceb9 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.js @@ -0,0 +1,148 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sleep = exports.mockGlobalScope = exports.mockRequestScope = exports.mockCaches = exports.mockManifest = exports.mockKV = exports.getEvent = void 0; +const makeServiceWorkerEnv = require("service-worker-mock"); +const HASH = "123HASHBROWN"; +const getEvent = (request) => { + const waitUntil = async (callback) => { + await callback; + }; + return { + request, + waitUntil, + }; +}; +exports.getEvent = getEvent; +const store = { + "key1.123HASHBROWN.txt": "val1", + "key1.123HASHBROWN.png": "val1", + "index.123HASHBROWN.html": "index.html", + "cache.123HASHBROWN.html": "cache me if you can", + "测试.123HASHBROWN.html": "My filename is non-ascii", + "%not-really-percent-encoded.123HASHBROWN.html": "browser percent encoded", + "%2F.123HASHBROWN.html": "user percent encoded", + "你好.123HASHBROWN.html": "I shouldnt be served", + "%E4%BD%A0%E5%A5%BD.123HASHBROWN.html": "Im important", + "nohash.txt": "no hash but still got some result", + "sub/blah.123HASHBROWN.png": "picturedis", + "sub/index.123HASHBROWN.html": "picturedis", + "client.123HASHBROWN": "important file", + "client.123HASHBROWN/index.html": "Im here but serve my big bro above", + "image.123HASHBROWN.png": "imagepng", + "image.123HASHBROWN.webp": "imagewebp", + "你好/index.123HASHBROWN.html": "My path is non-ascii", +}; +const mockKV = (store) => { + return { + get: (path) => store[path] || null, + }; +}; +exports.mockKV = mockKV; +const mockManifest = () => { + return JSON.stringify({ + "key1.txt": `key1.${HASH}.txt`, + "key1.png": `key1.${HASH}.png`, + "cache.html": `cache.${HASH}.html`, + "测试.html": `测试.${HASH}.html`, + "你好.html": `你好.${HASH}.html`, + "%not-really-percent-encoded.html": `%not-really-percent-encoded.${HASH}.html`, + "%2F.html": `%2F.${HASH}.html`, + "%E4%BD%A0%E5%A5%BD.html": `%E4%BD%A0%E5%A5%BD.${HASH}.html`, + "index.html": `index.${HASH}.html`, + "sub/blah.png": `sub/blah.${HASH}.png`, + "sub/index.html": `sub/index.${HASH}.html`, + client: `client.${HASH}`, + "client/index.html": `client.${HASH}`, + "image.png": `image.${HASH}.png`, + "image.webp": `image.${HASH}.webp`, + "你好/index.html": `你好/index.${HASH}.html`, + }); +}; +exports.mockManifest = mockManifest; +let cacheStore = new Map(); +const mockCaches = () => { + return { + default: { + async match(key) { + let cacheKey = { + url: key.url, + headers: {}, + }; + let response; + if (key.headers.has("if-none-match")) { + let makeStrongEtag = key.headers + .get("if-none-match") + .replace("W/", ""); + Reflect.set(cacheKey.headers, "etag", makeStrongEtag); + response = cacheStore.get(JSON.stringify(cacheKey)); + } + else { + // if client doesn't send if-none-match, we need to iterate through these keys + // and just test the URL + const activeCacheKeys = Array.from(cacheStore.keys()); + for (const cacheStoreKey of activeCacheKeys) { + if (JSON.parse(cacheStoreKey).url === key.url) { + response = cacheStore.get(cacheStoreKey); + } + } + } + // TODO: write test to accomodate for rare scenarios with where range requests accomodate etags + if (response && !key.headers.has("if-none-match")) { + // this appears overly verbose, but is necessary to document edge cache behavior + // The Range request header triggers the response header Content-Range ... + const range = key.headers.get("range"); + if (range) { + response.headers.set("content-range", `bytes ${range.split("=").pop()}/${response.headers.get("content-length")}`); + } + // ... which we are using in this repository to set status 206 + if (response.headers.has("content-range")) { + response.status = 206; + } + else { + response.status = 200; + } + let etag = response.headers.get("etag"); + if (etag && !etag.includes("W/")) { + response.headers.set("etag", `W/${etag}`); + } + } + return response; + }, + async put(key, val) { + let headers = new Headers(val.headers); + let url = new URL(key.url); + let resWithBody = new Response(val.body, { headers, status: 200 }); + let resNoBody = new Response(null, { headers, status: 304 }); + let cacheKey = { + url: key.url, + headers: { + etag: `"${url.pathname.replace("/", "")}"`, + }, + }; + cacheStore.set(JSON.stringify(cacheKey), resNoBody); + cacheKey.headers = {}; + cacheStore.set(JSON.stringify(cacheKey), resWithBody); + return; + }, + }, + }; +}; +exports.mockCaches = mockCaches; +// mocks functionality used inside worker request +function mockRequestScope() { + Object.assign(global, makeServiceWorkerEnv()); + Object.assign(global, { __STATIC_CONTENT_MANIFEST: (0, exports.mockManifest)() }); + Object.assign(global, { __STATIC_CONTENT: (0, exports.mockKV)(store) }); + Object.assign(global, { caches: (0, exports.mockCaches)() }); +} +exports.mockRequestScope = mockRequestScope; +// mocks functionality used on global isolate scope. such as the KV namespace bind +function mockGlobalScope() { + Object.assign(global, { __STATIC_CONTENT_MANIFEST: (0, exports.mockManifest)() }); + Object.assign(global, { __STATIC_CONTENT: (0, exports.mockKV)(store) }); +} +exports.mockGlobalScope = mockGlobalScope; +const sleep = (milliseconds) => { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +}; +exports.sleep = sleep; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts new file mode 100644 index 0000000..e836b61 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts @@ -0,0 +1,29 @@ +export type CacheControl = { + browserTTL: number; + edgeTTL: number; + bypassCache: boolean; +}; +export type AssetManifestType = Record; +export type Options = { + cacheControl: ((req: Request) => Partial) | Partial; + ASSET_NAMESPACE: any; + ASSET_MANIFEST: AssetManifestType | string; + mapRequestToAsset?: (req: Request, options?: Partial) => Request; + defaultMimeType: string; + defaultDocument: string; + pathIsEncoded: boolean; + defaultETag: "strong" | "weak"; +}; +export declare class KVError extends Error { + constructor(message?: string, status?: number); + status: number; +} +export declare class MethodNotAllowedError extends KVError { + constructor(message?: string, status?: number); +} +export declare class NotFoundError extends KVError { + constructor(message?: string, status?: number); +} +export declare class InternalError extends KVError { + constructor(message?: string, status?: number); +} diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/types.js b/node_modules/@cloudflare/kv-asset-handler/dist/types.js new file mode 100644 index 0000000..ba08c1b --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/types.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.KVError = void 0; +class KVError extends Error { + constructor(message, status = 500) { + super(message); + // see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain + this.name = KVError.name; // stack traces display correctly now + this.status = status; + } +} +exports.KVError = KVError; +class MethodNotAllowedError extends KVError { + constructor(message = `Not a valid request method`, status = 405) { + super(message, status); + } +} +exports.MethodNotAllowedError = MethodNotAllowedError; +class NotFoundError extends KVError { + constructor(message = `Not Found`, status = 404) { + super(message, status); + } +} +exports.NotFoundError = NotFoundError; +class InternalError extends KVError { + constructor(message = `Internal Error in KV Asset Handler`, status = 500) { + super(message, status); + } +} +exports.InternalError = InternalError; diff --git a/node_modules/@cloudflare/kv-asset-handler/package.json b/node_modules/@cloudflare/kv-asset-handler/package.json new file mode 100644 index 0000000..efd7292 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/package.json @@ -0,0 +1,57 @@ +{ + "name": "@cloudflare/kv-asset-handler", + "version": "0.3.2", + "description": "Routes requests to KV assets", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "repository": { + "type": "git", + "url": "git+https://github.com/cloudflare/workers-sdk.git", + "directory": "packages/kv-asset-handler" + }, + "keywords": [ + "kv", + "cloudflare", + "workers", + "wrangler", + "assets" + ], + "files": [ + "src", + "dist", + "!src/test", + "!dist/test" + ], + "author": "wrangler@cloudflare.com", + "license": "MIT OR Apache-2.0", + "bugs": { + "url": "https://github.com/cloudflare/workers-sdk/issues" + }, + "homepage": "https://github.com/cloudflare/workers-sdk#readme", + "dependencies": { + "mime": "^3.0.0" + }, + "devDependencies": { + "@ava/typescript": "^4.1.0", + "@cloudflare/workers-types": "^4.20240419.0", + "@types/mime": "^3.0.4", + "@types/node": "^18.11.12", + "ava": "^6.0.1", + "service-worker-mock": "^2.0.5" + }, + "engines": { + "node": ">=16.13" + }, + "publishConfig": { + "access": "public" + }, + "workers-sdk": { + "prerelease": true + }, + "scripts": { + "build": "tsc -d", + "pretest": "npm run build", + "test": "ava dist/test/*.js --verbose", + "test:ci": "npm run build && ava dist/test/*.js --verbose" + } +} \ No newline at end of file diff --git a/node_modules/@cloudflare/kv-asset-handler/src/index.ts b/node_modules/@cloudflare/kv-asset-handler/src/index.ts new file mode 100644 index 0000000..d4ef5f8 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/index.ts @@ -0,0 +1,355 @@ +import * as mime from "mime"; +import { + AssetManifestType, + CacheControl, + InternalError, + MethodNotAllowedError, + NotFoundError, + Options, +} from "./types"; + +declare global { + var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string; +} + +const defaultCacheControl: CacheControl = { + browserTTL: null, + edgeTTL: 2 * 60 * 60 * 24, // 2 days + bypassCache: false, // do not bypass Cloudflare's cache +}; + +const parseStringAsObject = (maybeString: string | T): T => + typeof maybeString === "string" + ? (JSON.parse(maybeString) as T) + : maybeString; + +const getAssetFromKVDefaultOptions: Partial = { + ASSET_NAMESPACE: + typeof __STATIC_CONTENT !== "undefined" ? __STATIC_CONTENT : undefined, + ASSET_MANIFEST: + typeof __STATIC_CONTENT_MANIFEST !== "undefined" + ? parseStringAsObject(__STATIC_CONTENT_MANIFEST) + : {}, + cacheControl: defaultCacheControl, + defaultMimeType: "text/plain", + defaultDocument: "index.html", + pathIsEncoded: false, + defaultETag: "strong", +}; + +function assignOptions(options?: Partial): Options { + // Assign any missing options passed in to the default + // options.mapRequestToAsset is handled manually later + return Object.assign({}, getAssetFromKVDefaultOptions, options); +} + +/** + * maps the path of incoming request to the request pathKey to look up + * in bucket and in cache + * e.g. for a path '/' returns '/index.html' which serves + * the content of bucket/index.html + * @param {Request} request incoming request + */ +const mapRequestToAsset = (request: Request, options?: Partial) => { + options = assignOptions(options); + + const parsedUrl = new URL(request.url); + let pathname = parsedUrl.pathname; + + if (pathname.endsWith("/")) { + // If path looks like a directory append options.defaultDocument + // e.g. If path is /about/ -> /about/index.html + pathname = pathname.concat(options.defaultDocument); + } else if (!mime.getType(pathname)) { + // If path doesn't look like valid content + // e.g. /about.me -> /about.me/index.html + pathname = pathname.concat("/" + options.defaultDocument); + } + + parsedUrl.pathname = pathname; + return new Request(parsedUrl.toString(), request); +}; + +/** + * maps the path of incoming request to /index.html if it evaluates to + * any HTML file. + * @param {Request} request incoming request + */ +function serveSinglePageApp( + request: Request, + options?: Partial +): Request { + options = assignOptions(options); + + // First apply the default handler, which already has logic to detect + // paths that should map to HTML files. + request = mapRequestToAsset(request, options); + + const parsedUrl = new URL(request.url); + + // Detect if the default handler decided to map to + // a HTML file in some specific directory. + if (parsedUrl.pathname.endsWith(".html")) { + // If expected HTML file was missing, just return the root index.html (or options.defaultDocument) + return new Request( + `${parsedUrl.origin}/${options.defaultDocument}`, + request + ); + } else { + // The default handler decided this is not an HTML page. It's probably + // an image, CSS, or JS file. Leave it as-is. + return request; + } +} + +/** + * takes the path of the incoming request, gathers the appropriate content from KV, and returns + * the response + * + * @param {FetchEvent} event the fetch event of the triggered request + * @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options + * @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser + * @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up + * @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references + * @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV + * */ + +type Evt = { + request: Request; + waitUntil: (promise: Promise) => void; +}; + +const getAssetFromKV = async ( + event: Evt, + options?: Partial +): Promise => { + options = assignOptions(options); + + const request = event.request; + const ASSET_NAMESPACE = options.ASSET_NAMESPACE; + const ASSET_MANIFEST = parseStringAsObject( + options.ASSET_MANIFEST + ); + + if (typeof ASSET_NAMESPACE === "undefined") { + throw new InternalError(`there is no KV namespace bound to the script`); + } + + const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, ""); // strip any preceding /'s + let pathIsEncoded = options.pathIsEncoded; + let requestKey; + // if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions + // otherwise handle request as normal, with default mapRequestToAsset below + if (options.mapRequestToAsset) { + requestKey = options.mapRequestToAsset(request); + } else if (ASSET_MANIFEST[rawPathKey]) { + requestKey = request; + } else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) { + pathIsEncoded = true; + requestKey = request; + } else { + const mappedRequest = mapRequestToAsset(request); + const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace( + /^\/+/, + "" + ); + if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) { + pathIsEncoded = true; + requestKey = mappedRequest; + } else { + // use default mapRequestToAsset + requestKey = mapRequestToAsset(request, options); + } + } + + const SUPPORTED_METHODS = ["GET", "HEAD"]; + if (!SUPPORTED_METHODS.includes(requestKey.method)) { + throw new MethodNotAllowedError( + `${requestKey.method} is not a valid request method` + ); + } + + const parsedUrl = new URL(requestKey.url); + const pathname = pathIsEncoded + ? decodeURIComponent(parsedUrl.pathname) + : parsedUrl.pathname; // decode percentage encoded path only when necessary + + // pathKey is the file path to look up in the manifest + let pathKey = pathname.replace(/^\/+/, ""); // remove prepended / + + // @ts-ignore + const cache = caches.default; + let mimeType = mime.getType(pathKey) || options.defaultMimeType; + if (mimeType.startsWith("text") || mimeType === "application/javascript") { + mimeType += "; charset=utf-8"; + } + + let shouldEdgeCache = false; // false if storing in KV by raw file path i.e. no hash + // check manifest for map from file path to hash + if (typeof ASSET_MANIFEST !== "undefined") { + if (ASSET_MANIFEST[pathKey]) { + pathKey = ASSET_MANIFEST[pathKey]; + // if path key is in asset manifest, we can assume it contains a content hash and can be cached + shouldEdgeCache = true; + } + } + + // TODO this excludes search params from cache, investigate ideal behavior + let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request); + + // if argument passed in for cacheControl is a function then + // evaluate that function. otherwise return the Object passed in + // or default Object + const evalCacheOpts = (() => { + switch (typeof options.cacheControl) { + case "function": + return options.cacheControl(request); + case "object": + return options.cacheControl; + default: + return defaultCacheControl; + } + })(); + + // formats the etag depending on the response context. if the entityId + // is invalid, returns an empty string (instead of null) to prevent the + // the potentially disastrous scenario where the value of the Etag resp + // header is "null". Could be modified in future to base64 encode etc + const formatETag = ( + entityId: any = pathKey, + validatorType: string = options.defaultETag + ) => { + if (!entityId) { + return ""; + } + switch (validatorType) { + case "weak": + if (!entityId.startsWith("W/")) { + if (entityId.startsWith(`"`) && entityId.endsWith(`"`)) { + return `W/${entityId}`; + } + return `W/"${entityId}"`; + } + return entityId; + case "strong": + if (entityId.startsWith(`W/"`)) { + entityId = entityId.replace("W/", ""); + } + if (!entityId.endsWith(`"`)) { + entityId = `"${entityId}"`; + } + return entityId; + default: + return ""; + } + }; + + options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts); + + // override shouldEdgeCache if options say to bypassCache + if ( + options.cacheControl.bypassCache || + options.cacheControl.edgeTTL === null || + request.method == "HEAD" + ) { + shouldEdgeCache = false; + } + // only set max-age if explicitly passed in a number as an arg + const shouldSetBrowserCache = + typeof options.cacheControl.browserTTL === "number"; + + let response = null; + if (shouldEdgeCache) { + response = await cache.match(cacheKey); + } + + if (response) { + if (response.status > 300 && response.status < 400) { + if (response.body && "cancel" in Object.getPrototypeOf(response.body)) { + // Body exists and environment supports readable streams + response.body.cancel(); + } else { + // Environment doesnt support readable streams, or null repsonse body. Nothing to do + } + response = new Response(null, response); + } else { + // fixes #165 + let opts = { + headers: new Headers(response.headers), + status: 0, + statusText: "", + }; + + opts.headers.set("cf-cache-status", "HIT"); + + if (response.status) { + opts.status = response.status; + opts.statusText = response.statusText; + } else if (opts.headers.has("Content-Range")) { + opts.status = 206; + opts.statusText = "Partial Content"; + } else { + opts.status = 200; + opts.statusText = "OK"; + } + response = new Response(response.body, opts); + } + } else { + const body = await ASSET_NAMESPACE.get(pathKey, "arrayBuffer"); + if (body === null) { + throw new NotFoundError( + `could not find ${pathKey} in your content namespace` + ); + } + response = new Response(body); + + if (shouldEdgeCache) { + response.headers.set("Accept-Ranges", "bytes"); + response.headers.set("Content-Length", String(body.byteLength)); + // set etag before cache insertion + if (!response.headers.has("etag")) { + response.headers.set("etag", formatETag(pathKey)); + } + // determine Cloudflare cache behavior + response.headers.set( + "Cache-Control", + `max-age=${options.cacheControl.edgeTTL}` + ); + event.waitUntil(cache.put(cacheKey, response.clone())); + response.headers.set("CF-Cache-Status", "MISS"); + } + } + response.headers.set("Content-Type", mimeType); + + if (response.status === 304) { + let etag = formatETag(response.headers.get("etag")); + let ifNoneMatch = cacheKey.headers.get("if-none-match"); + let proxyCacheStatus = response.headers.get("CF-Cache-Status"); + if (etag) { + if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === "MISS") { + response.headers.set("CF-Cache-Status", "EXPIRED"); + } else { + response.headers.set("CF-Cache-Status", "REVALIDATED"); + } + response.headers.set("etag", formatETag(etag, "weak")); + } + } + if (shouldSetBrowserCache) { + response.headers.set( + "Cache-Control", + `max-age=${options.cacheControl.browserTTL}` + ); + } else { + response.headers.delete("Cache-Control"); + } + return response; +}; + +export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp }; +export { + Options, + CacheControl, + MethodNotAllowedError, + NotFoundError, + InternalError, +}; diff --git a/node_modules/@cloudflare/kv-asset-handler/src/mocks.ts b/node_modules/@cloudflare/kv-asset-handler/src/mocks.ts new file mode 100644 index 0000000..f3943a9 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/mocks.ts @@ -0,0 +1,152 @@ +const makeServiceWorkerEnv = require("service-worker-mock"); + +const HASH = "123HASHBROWN"; + +export const getEvent = (request: Request): any => { + const waitUntil = async (callback: any) => { + await callback; + }; + return { + request, + waitUntil, + }; +}; +const store: any = { + "key1.123HASHBROWN.txt": "val1", + "key1.123HASHBROWN.png": "val1", + "index.123HASHBROWN.html": "index.html", + "cache.123HASHBROWN.html": "cache me if you can", + "测试.123HASHBROWN.html": "My filename is non-ascii", + "%not-really-percent-encoded.123HASHBROWN.html": "browser percent encoded", + "%2F.123HASHBROWN.html": "user percent encoded", + "你好.123HASHBROWN.html": "I shouldnt be served", + "%E4%BD%A0%E5%A5%BD.123HASHBROWN.html": "Im important", + "nohash.txt": "no hash but still got some result", + "sub/blah.123HASHBROWN.png": "picturedis", + "sub/index.123HASHBROWN.html": "picturedis", + "client.123HASHBROWN": "important file", + "client.123HASHBROWN/index.html": "Im here but serve my big bro above", + "image.123HASHBROWN.png": "imagepng", + "image.123HASHBROWN.webp": "imagewebp", + "你好/index.123HASHBROWN.html": "My path is non-ascii", +}; +export const mockKV = (store: any) => { + return { + get: (path: string) => store[path] || null, + }; +}; + +export const mockManifest = () => { + return JSON.stringify({ + "key1.txt": `key1.${HASH}.txt`, + "key1.png": `key1.${HASH}.png`, + "cache.html": `cache.${HASH}.html`, + "测试.html": `测试.${HASH}.html`, + "你好.html": `你好.${HASH}.html`, + "%not-really-percent-encoded.html": `%not-really-percent-encoded.${HASH}.html`, + "%2F.html": `%2F.${HASH}.html`, + "%E4%BD%A0%E5%A5%BD.html": `%E4%BD%A0%E5%A5%BD.${HASH}.html`, + "index.html": `index.${HASH}.html`, + "sub/blah.png": `sub/blah.${HASH}.png`, + "sub/index.html": `sub/index.${HASH}.html`, + client: `client.${HASH}`, + "client/index.html": `client.${HASH}`, + "image.png": `image.${HASH}.png`, + "image.webp": `image.${HASH}.webp`, + "你好/index.html": `你好/index.${HASH}.html`, + }); +}; + +let cacheStore: any = new Map(); +interface CacheKey { + url: object; + headers: object; +} +export const mockCaches = () => { + return { + default: { + async match(key: any) { + let cacheKey: CacheKey = { + url: key.url, + headers: {}, + }; + let response; + if (key.headers.has("if-none-match")) { + let makeStrongEtag = key.headers + .get("if-none-match") + .replace("W/", ""); + Reflect.set(cacheKey.headers, "etag", makeStrongEtag); + response = cacheStore.get(JSON.stringify(cacheKey)); + } else { + // if client doesn't send if-none-match, we need to iterate through these keys + // and just test the URL + const activeCacheKeys: Array = Array.from(cacheStore.keys()); + for (const cacheStoreKey of activeCacheKeys) { + if (JSON.parse(cacheStoreKey).url === key.url) { + response = cacheStore.get(cacheStoreKey); + } + } + } + // TODO: write test to accomodate for rare scenarios with where range requests accomodate etags + if (response && !key.headers.has("if-none-match")) { + // this appears overly verbose, but is necessary to document edge cache behavior + // The Range request header triggers the response header Content-Range ... + const range = key.headers.get("range"); + if (range) { + response.headers.set( + "content-range", + `bytes ${range.split("=").pop()}/${response.headers.get( + "content-length" + )}` + ); + } + // ... which we are using in this repository to set status 206 + if (response.headers.has("content-range")) { + response.status = 206; + } else { + response.status = 200; + } + let etag = response.headers.get("etag"); + if (etag && !etag.includes("W/")) { + response.headers.set("etag", `W/${etag}`); + } + } + return response; + }, + async put(key: any, val: Response) { + let headers = new Headers(val.headers); + let url = new URL(key.url); + let resWithBody = new Response(val.body, { headers, status: 200 }); + let resNoBody = new Response(null, { headers, status: 304 }); + let cacheKey: CacheKey = { + url: key.url, + headers: { + etag: `"${url.pathname.replace("/", "")}"`, + }, + }; + cacheStore.set(JSON.stringify(cacheKey), resNoBody); + cacheKey.headers = {}; + cacheStore.set(JSON.stringify(cacheKey), resWithBody); + return; + }, + }, + }; +}; + +// mocks functionality used inside worker request +export function mockRequestScope() { + Object.assign(global, makeServiceWorkerEnv()); + Object.assign(global, { __STATIC_CONTENT_MANIFEST: mockManifest() }); + Object.assign(global, { __STATIC_CONTENT: mockKV(store) }); + Object.assign(global, { caches: mockCaches() }); +} + +// mocks functionality used on global isolate scope. such as the KV namespace bind +export function mockGlobalScope() { + Object.assign(global, { __STATIC_CONTENT_MANIFEST: mockManifest() }); + Object.assign(global, { __STATIC_CONTENT: mockKV(store) }); +} + +export const sleep = (milliseconds: number) => { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +}; diff --git a/node_modules/@cloudflare/kv-asset-handler/src/types.ts b/node_modules/@cloudflare/kv-asset-handler/src/types.ts new file mode 100644 index 0000000..03ea856 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/types.ts @@ -0,0 +1,52 @@ +export type CacheControl = { + browserTTL: number; + edgeTTL: number; + bypassCache: boolean; +}; + +export type AssetManifestType = Record; + +export type Options = { + cacheControl: + | ((req: Request) => Partial) + | Partial; + ASSET_NAMESPACE: any; + ASSET_MANIFEST: AssetManifestType | string; + mapRequestToAsset?: (req: Request, options?: Partial) => Request; + defaultMimeType: string; + defaultDocument: string; + pathIsEncoded: boolean; + defaultETag: "strong" | "weak"; +}; + +export class KVError extends Error { + constructor(message?: string, status: number = 500) { + super(message); + // see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain + this.name = KVError.name; // stack traces display correctly now + this.status = status; + } + status: number; +} +export class MethodNotAllowedError extends KVError { + constructor( + message: string = `Not a valid request method`, + status: number = 405 + ) { + super(message, status); + } +} +export class NotFoundError extends KVError { + constructor(message: string = `Not Found`, status: number = 404) { + super(message, status); + } +} +export class InternalError extends KVError { + constructor( + message: string = `Internal Error in KV Asset Handler`, + status: number = 500 + ) { + super(message, status); + } +} diff --git a/node_modules/@cloudflare/workerd-darwin-arm64/README.md b/node_modules/@cloudflare/workerd-darwin-arm64/README.md new file mode 100644 index 0000000..bf9bc65 --- /dev/null +++ b/node_modules/@cloudflare/workerd-darwin-arm64/README.md @@ -0,0 +1,6 @@ +# 👷 `workerd` for macOS ARM 64-bit, Cloudflare's JavaScript/Wasm Runtime + +`workerd` is a JavaScript / Wasm server runtime based on the same code that powers +[Cloudflare Workers](https://workers.dev). + +See https://github.com/cloudflare/workerd for details. diff --git a/node_modules/@cloudflare/workerd-darwin-arm64/bin/workerd b/node_modules/@cloudflare/workerd-darwin-arm64/bin/workerd new file mode 100755 index 0000000..ebbc707 Binary files /dev/null and b/node_modules/@cloudflare/workerd-darwin-arm64/bin/workerd differ diff --git a/node_modules/@cloudflare/workerd-darwin-arm64/package.json b/node_modules/@cloudflare/workerd-darwin-arm64/package.json new file mode 100644 index 0000000..deca629 --- /dev/null +++ b/node_modules/@cloudflare/workerd-darwin-arm64/package.json @@ -0,0 +1,17 @@ +{ + "name": "@cloudflare/workerd-darwin-arm64", + "description": "👷 workerd for macOS ARM 64-bit, Cloudflare's JavaScript/Wasm Runtime", + "repository": "https://github.com/cloudflare/workerd", + "license": "Apache-2.0", + "preferUnplugged": false, + "engines": { + "node": ">=16" + }, + "os": [ + "darwin" + ], + "cpu": [ + "arm64" + ], + "version": "1.20240419.0" +} diff --git a/node_modules/@cloudflare/workers-types/2021-11-03/index.d.ts b/node_modules/@cloudflare/workers-types/2021-11-03/index.d.ts new file mode 100755 index 0000000..67d8fc4 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2021-11-03/index.d.ts @@ -0,0 +1,4848 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + readonly type: string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + readonly eventPhase: number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + readonly composed: boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + readonly bubbles: boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + readonly cancelable: boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + readonly defaultPrevented: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + readonly returnValue: boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + readonly currentTarget?: EventTarget; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + readonly srcElement?: EventTarget; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + readonly timeStamp: number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + readonly isTrusted: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + cancelBubble: boolean; + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + readonly aborted: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + readonly reason: any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [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/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + readonly lastModified: number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + readonly subtle: SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + readonly status: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + readonly statusText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + readonly headers: Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + readonly ok: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + readonly redirected: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + readonly method: string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + readonly url: string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + readonly headers: Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + readonly integrity: string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + readonly keepalive: boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +declare interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +declare interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +declare interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + readonly closed: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + readonly ready: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + readonly desiredSize: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + readonly readable: ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + readonly writable: WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + href: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + readonly origin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + protocol: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + username: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + password: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + host: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + hostname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + port: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + pathname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + search: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + readonly searchParams: URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + hash: string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readonly readyState: number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + readonly url: string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + readonly protocol: string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + readonly extensions: string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2021-11-03/index.ts b/node_modules/@cloudflare/workers-types/2021-11-03/index.ts new file mode 100755 index 0000000..f77f98b --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2021-11-03/index.ts @@ -0,0 +1,4787 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + readonly type: string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + readonly eventPhase: number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + readonly composed: boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + readonly bubbles: boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + readonly cancelable: boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + readonly defaultPrevented: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + readonly returnValue: boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + readonly currentTarget?: EventTarget; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + readonly srcElement?: EventTarget; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + readonly timeStamp: number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + readonly isTrusted: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + cancelBubble: boolean; + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + readonly aborted: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + readonly reason: any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [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/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + readonly lastModified: number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + readonly subtle: SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + readonly status: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + readonly statusText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + readonly headers: Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + readonly ok: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + readonly redirected: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + readonly method: string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + readonly url: string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + readonly headers: Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + readonly integrity: string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + readonly keepalive: boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +export interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +export interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +export interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +export interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + readonly closed: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + readonly ready: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + readonly desiredSize: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + readonly readable: ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + readonly writable: WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + href: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + readonly origin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + protocol: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + username: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + password: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + host: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + hostname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + port: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + pathname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + search: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + readonly searchParams: URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + hash: string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readonly readyState: number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + readonly url: string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + readonly protocol: string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + readonly extensions: string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-01-31/index.d.ts b/node_modules/@cloudflare/workers-types/2022-01-31/index.d.ts new file mode 100755 index 0000000..6ff5d62 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-01-31/index.d.ts @@ -0,0 +1,4874 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +declare interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +declare interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +declare interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-01-31/index.ts b/node_modules/@cloudflare/workers-types/2022-01-31/index.ts new file mode 100755 index 0000000..85fd7ec --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-01-31/index.ts @@ -0,0 +1,4813 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +export interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +export interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +export interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +export interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-03-21/index.d.ts b/node_modules/@cloudflare/workers-types/2022-03-21/index.d.ts new file mode 100755 index 0000000..82aec25 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-03-21/index.d.ts @@ -0,0 +1,4900 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +declare interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +declare interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +declare interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-03-21/index.ts b/node_modules/@cloudflare/workers-types/2022-03-21/index.ts new file mode 100755 index 0000000..9d0875a --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-03-21/index.ts @@ -0,0 +1,4839 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +export declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +export interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +export interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +export interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +export interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-08-04/index.d.ts b/node_modules/@cloudflare/workers-types/2022-08-04/index.d.ts new file mode 100755 index 0000000..ea0499a --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-08-04/index.d.ts @@ -0,0 +1,4901 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +declare interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +declare interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +declare interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-08-04/index.ts b/node_modules/@cloudflare/workers-types/2022-08-04/index.ts new file mode 100755 index 0000000..559dabf --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-08-04/index.ts @@ -0,0 +1,4840 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +export declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +export interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +export interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +export interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +export interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-10-31/index.d.ts b/node_modules/@cloudflare/workers-types/2022-10-31/index.d.ts new file mode 100755 index 0000000..25101b7 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-10-31/index.d.ts @@ -0,0 +1,4900 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +declare interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +declare interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +declare interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + static parse(url: string, base?: string): URL | null; +} +declare class URLSearchParams { + constructor( + init?: Iterable> | Record | string, + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-10-31/index.ts b/node_modules/@cloudflare/workers-types/2022-10-31/index.ts new file mode 100755 index 0000000..2d7ef75 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-10-31/index.ts @@ -0,0 +1,4839 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +export declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +export interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +export interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +export interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +export interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + static parse(url: string, base?: string): URL | null; +} +export declare class URLSearchParams { + constructor( + init?: Iterable> | Record | string, + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-11-30/index.d.ts b/node_modules/@cloudflare/workers-types/2022-11-30/index.d.ts new file mode 100755 index 0000000..81e5213 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-11-30/index.d.ts @@ -0,0 +1,4896 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +declare abstract class ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +declare abstract class ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +declare abstract class ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +declare abstract class WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + static parse(url: string, base?: string): URL | null; +} +declare class URLSearchParams { + constructor( + init?: Iterable> | Record | string, + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-11-30/index.ts b/node_modules/@cloudflare/workers-types/2022-11-30/index.ts new file mode 100755 index 0000000..f87abc2 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-11-30/index.ts @@ -0,0 +1,4835 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +export declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +export declare abstract class ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +export declare abstract class ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +export declare abstract class ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +export declare abstract class WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + static parse(url: string, base?: string): URL | null; +} +export declare class URLSearchParams { + constructor( + init?: Iterable> | Record | string, + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2023-03-01/index.d.ts b/node_modules/@cloudflare/workers-types/2023-03-01/index.d.ts new file mode 100755 index 0000000..9ee7615 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2023-03-01/index.d.ts @@ -0,0 +1,4897 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +declare abstract class ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +declare abstract class ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +declare abstract class ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +declare abstract class WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + static parse(url: string, base?: string): URL | null; +} +declare class URLSearchParams { + constructor( + init?: Iterable> | Record | string, + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2023-03-01/index.ts b/node_modules/@cloudflare/workers-types/2023-03-01/index.ts new file mode 100755 index 0000000..6511d1a --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2023-03-01/index.ts @@ -0,0 +1,4836 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +export declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +export declare abstract class ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +export declare abstract class ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +export declare abstract class ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +export declare abstract class WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + static parse(url: string, base?: string): URL | null; +} +export declare class URLSearchParams { + constructor( + init?: Iterable> | Record | string, + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2023-07-01/index.d.ts b/node_modules/@cloudflare/workers-types/2023-07-01/index.d.ts new file mode 100755 index 0000000..8421172 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2023-07-01/index.d.ts @@ -0,0 +1,4897 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +declare abstract class ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +declare abstract class ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +declare abstract class ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +declare abstract class WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + static parse(url: string, base?: string): URL | null; +} +declare class URLSearchParams { + constructor( + init?: Iterable> | Record | string, + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2023-07-01/index.ts b/node_modules/@cloudflare/workers-types/2023-07-01/index.ts new file mode 100755 index 0000000..392623c --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2023-07-01/index.ts @@ -0,0 +1,4836 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +export declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +export declare abstract class ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +export declare abstract class ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +export declare abstract class ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +export declare abstract class WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + static parse(url: string, base?: string): URL | null; +} +export declare class URLSearchParams { + constructor( + init?: Iterable> | Record | string, + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/README.md b/node_modules/@cloudflare/workers-types/README.md new file mode 100644 index 0000000..5c34479 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/README.md @@ -0,0 +1,128 @@ +# Cloudflare Workers Types + +## Install + +```bash +npm install -D @cloudflare/workers-types +-- Or +yarn add -D @cloudflare/workers-types +``` + +## Usage + +The following is a minimal `tsconfig.json` for use alongside this package: + +**`tsconfig.json`** + +```json +{ + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "lib": ["esnext"], + "types": ["@cloudflare/workers-types"] + } +} +``` + +### Compatibility dates + +![Entrypoints for compatibility dates](./entrypoints.svg) + +The Cloudflare Workers runtime manages backwards compatibility through the use of [Compatibility Dates](https://developers.cloudflare.com/workers/platform/compatibility-dates/). Using different compatibility dates affects the runtime types available to your Worker, and so it's important you specify the correct entrypoint to the `workers-types` package to match your compatibility date (which is usually set in your `wrangler.toml` configuration file). `workers-types` currently exposes the following entrypoints to choose from: + +- `@cloudflare/workers-types` + + The default entrypoint exposes the runtime types for a compatibility date before `2021-11-03`. + +- `@cloudflare/workers-types/2021-11-03` + + This entrypoint exposes the runtime types for a compatibility date between `2021-11-03` and `2022-01-31`. + +- `@cloudflare/workers-types/2022-01-31` + + This entrypoint exposes the runtime types for a compatibility date between `2022-01-31` and `2022-03-21`. + +- `@cloudflare/workers-types/2022-03-21` + + This entrypoint exposes the runtime types for a compatibility date between `2022-03-21` and `2022-08-04`. + +- `@cloudflare/workers-types/2022-08-04` + + This entrypoint exposes the runtime types for a compatibility date between `2022-08-04` and `2022-10-31`. + +- `@cloudflare/workers-types/2022-10-31` + + This entrypoint exposes the runtime types for a compatibility date between `2022-10-31` and `2022-11-30`. + +- `@cloudflare/workers-types/2022-11-30` + + This entrypoint exposes the runtime types for a compatibility date between `2022-11-30` and `2023-03-01`. + +- `@cloudflare/workers-types/2023-03-01` + + This entrypoint exposes the runtime types for a compatibility date between `2023-03-01` and `2023-07-01`. + +- `@cloudflare/workers-types/2023-07-01` + + This entrypoint exposes the runtime types for a compatibility date after `2023-07-01`. + +- `@cloudflare/workers-types/experimental` + + This entrypoint exposes the runtime types for the latest compatibility date. The types exposed by this entrypoint will change over time to always reflect the latest version of the Workers runtime. + +To use one of these entrypoints, you need to specify them in your `tsconfig.json`. For example, this is a sample `tsconfig.json` for using the `2022-08-04` entrypoint. + +```json +{ + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "lib": ["esnext"], + "types": ["@cloudflare/workers-types/2022-08-04"] + } +} +``` + +### Importable Types + +It's not always possible (or desirable) to modify the `tsconfig.json` settings for a project to include all the Cloudflare Workers types. For use cases like that, this package provides importable versions of its types, which are usable with no additional `tsconfig.json` setup. For example: + +```ts +import type { Request as WorkerRequest, ExecutionContext } from "@cloudflare/workers-types/experimental" + +export default { + fetch(request: WorkerRequest, env: unknown, ctx: ExecutionContext) { + return new Response("OK") + } +} +``` + + +### Using bindings + +It's recommended that you create a type file for any bindings your Worker uses. Create a file named +`worker-configuration.d.ts` in your src directory. + +If you're using Module Workers, it should look like this: +```typescript +// worker-configuration.d.ts +interface Env { + MY_ENV_VAR: string; + MY_SECRET: string; + myKVNamespace: KVNamespace; +} +``` +For Service Workers, it should augment the global scope: +```typescript +// worker-configuration.d.ts +declare global { + const MY_ENV_VAR: string; + const MY_SECRET: string; + const myKVNamespace: KVNamespace; +} +export {} +``` + +Wrangler can also generate this for you automatically from your `wrangler.toml` configuration file, using the `wrangler types` command. + diff --git a/node_modules/@cloudflare/workers-types/entrypoints.svg b/node_modules/@cloudflare/workers-types/entrypoints.svg new file mode 100644 index 0000000..057a152 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/entrypoints.svg @@ -0,0 +1,53 @@ + + + + + + @cloudflare/workers-types + + + + @cloudflare/workers-types/2021-11-03 + + + + @cloudflare/workers-types/2022-01-31 + + + + @cloudflare/workers-types/2022-03-21 + + + + @cloudflare/workers-types/2022-08-04 + + + + @cloudflare/workers-types/2022-10-31 + + + + @cloudflare/workers-types/2022-11-30 + + + + @cloudflare/workers-types/experimental + + + + + + + + + + + types Entrypoint + compatibility_date + 2021-11-03 + 2022-01-31 + 2022-03-21 + 2022-08-04 + 2022-10-31 + 2022-11-30 + diff --git a/node_modules/@cloudflare/workers-types/experimental/index.d.ts b/node_modules/@cloudflare/workers-types/experimental/index.d.ts new file mode 100755 index 0000000..04668fd --- /dev/null +++ b/node_modules/@cloudflare/workers-types/experimental/index.d.ts @@ -0,0 +1,4972 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; + abort(reason?: any): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + getExisting( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; + abort(reason?: string): void; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + sql: SqlStorage; + transactionSync(closure: () => T): T; + getCurrentBookmark(): Promise; + getBookmarkForTime(timestamp: number | Date): Promise; + onNextSessionRestoreBookmark(bookmark: string): Promise; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; + queue( + queueName: string, + messages: ServiceBindingQueueMessage[], + ): Promise; + scheduled(options?: FetcherScheduledOptions): Promise; +}; +declare interface FetcherScheduledOptions { + scheduledTime?: Date; + cron?: string; +} +declare interface FetcherScheduledResult { + outcome: string; + noRetry: boolean; +} +declare interface FetcherQueueResult { + outcome: string; + ackAll: boolean; + retryBatch: QueueRetryBatch; + explicitAcks: string[]; + retryMessages: QueueRetryMessage[]; +} +declare type ServiceBindingQueueMessage = { + id: string; + timestamp: Date; + attempts: number; +} & ( + | { + body: Body; + } + | { + serializedBody: ArrayBuffer | ArrayBufferView; + } +); +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryBatch { + retry: boolean; + delaySeconds?: number; +} +declare interface QueueRetryMessage { + msgId: string; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class JsRpcProperty { + then(handler: Function, errorHandler?: Function): any; + catch(errorHandler: Function): any; + finally(onFinally: Function): any; +} +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +declare abstract class ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +declare abstract class ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +declare abstract class ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +declare abstract class WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + static parse(url: string, base?: string): URL | null; +} +declare class URLSearchParams { + constructor( + init?: Iterable> | Record | string, + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface SqlStorage { + exec(query: string, ...bindings: any[]): SqlStorageCursor; + prepare(query: string): SqlStorageStatement; + ingest(query: string): SqlStorageIngestResult; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +declare abstract class SqlStorageStatement {} +declare abstract class SqlStorageCursor { + raw(): IterableIterator<((ArrayBuffer | string | number) | null)[]>; + get columnNames(): string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator< + Record + >; +} +declare interface SqlStorageIngestResult { + remainder: string; + rowsRead: number; + rowsWritten: number; + statementCount: number; +} +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/experimental/index.ts b/node_modules/@cloudflare/workers-types/experimental/index.ts new file mode 100755 index 0000000..9c8bebf --- /dev/null +++ b/node_modules/@cloudflare/workers-types/experimental/index.ts @@ -0,0 +1,4911 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; + abort(reason?: any): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +export declare abstract class Navigator { + sendBeacon( + url: string, + body?: + | ReadableStream + | string + | (ArrayBuffer | ArrayBufferView) + | Blob + | URLSearchParams + | FormData, + ): boolean; + readonly userAgent: string; + readonly gpu: gpuGPU; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + getExisting( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; + abort(reason?: string): void; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + sql: SqlStorage; + transactionSync(closure: () => T): T; + getCurrentBookmark(): Promise; + getBookmarkForTime(timestamp: number | Date): Promise; + onNextSessionRestoreBookmark(bookmark: string): Promise; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + get status(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + get statusText(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + get headers(): Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + get ok(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + get redirected(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + get method(): string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + get url(): string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + get headers(): Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + get redirect(): string; + get fetcher(): Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + get signal(): AbortSignal; + get cf(): Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + get integrity(): string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + get keepalive(): boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; + queue( + queueName: string, + messages: ServiceBindingQueueMessage[], + ): Promise; + scheduled(options?: FetcherScheduledOptions): Promise; +}; +export interface FetcherScheduledOptions { + scheduledTime?: Date; + cron?: string; +} +export interface FetcherScheduledResult { + outcome: string; + noRetry: boolean; +} +export interface FetcherQueueResult { + outcome: string; + ackAll: boolean; + retryBatch: QueueRetryBatch; + explicitAcks: string[]; + retryMessages: QueueRetryMessage[]; +} +export type ServiceBindingQueueMessage = { + id: string; + timestamp: Date; + attempts: number; +} & ( + | { + body: Body; + } + | { + serializedBody: ArrayBuffer | ArrayBufferView; + } +); +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryBatch { + retry: boolean; + delaySeconds?: number; +} +export interface QueueRetryMessage { + msgId: string; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class JsRpcProperty { + then(handler: Function, errorHandler?: Function): any; + catch(errorHandler: Function): any; + finally(onFinally: Function): any; +} +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +export declare abstract class ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +export declare abstract class ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +export declare abstract class ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +export declare abstract class WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + static parse(url: string, base?: string): URL | null; +} +export declare class URLSearchParams { + constructor( + init?: Iterable> | Record | string, + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + get readyState(): number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + get url(): string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + get protocol(): string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface SqlStorage { + exec(query: string, ...bindings: any[]): SqlStorageCursor; + prepare(query: string): SqlStorageStatement; + ingest(query: string): SqlStorageIngestResult; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +export declare abstract class SqlStorageStatement {} +export declare abstract class SqlStorageCursor { + raw(): IterableIterator<((ArrayBuffer | string | number) | null)[]>; + get columnNames(): string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator< + Record + >; +} +export interface SqlStorageIngestResult { + remainder: string; + rowsRead: number; + rowsWritten: number; + statementCount: number; +} +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export interface gpuGPU { + requestAdapter( + param1?: gpuGPURequestAdapterOptions, + ): Promise; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPURequestAdapterOptions { + powerPreference: string; + forceFallbackAdapter?: boolean; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/index.d.ts b/node_modules/@cloudflare/workers-types/index.d.ts new file mode 100755 index 0000000..dda4816 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/index.d.ts @@ -0,0 +1,4848 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + readonly type: string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + readonly eventPhase: number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + readonly composed: boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + readonly bubbles: boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + readonly cancelable: boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + readonly defaultPrevented: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + readonly returnValue: boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + readonly currentTarget?: EventTarget; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + readonly srcElement?: EventTarget; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + readonly timeStamp: number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + readonly isTrusted: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + cancelBubble: boolean; + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + readonly aborted: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + readonly reason: any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [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/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + readonly lastModified: number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + readonly subtle: SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + readonly status: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + readonly statusText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + readonly headers: Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + readonly ok: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + readonly redirected: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + readonly method: string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + readonly url: string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + readonly headers: Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + readonly integrity: string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + readonly keepalive: boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +declare interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +declare interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +declare interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + readonly closed: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + readonly ready: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + readonly desiredSize: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + readonly readable: ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + readonly writable: WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + href: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + readonly origin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + protocol: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + username: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + password: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + host: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + hostname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + port: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + pathname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + search: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + readonly searchParams: URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + hash: string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readonly readyState: number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + readonly url: string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + readonly protocol: string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + readonly extensions: string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/index.ts b/node_modules/@cloudflare/workers-types/index.ts new file mode 100755 index 0000000..155f62a --- /dev/null +++ b/node_modules/@cloudflare/workers-types/index.ts @@ -0,0 +1,4787 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + readonly type: string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + readonly eventPhase: number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + readonly composed: boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + readonly bubbles: boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + readonly cancelable: boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + readonly defaultPrevented: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + readonly returnValue: boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + readonly currentTarget?: EventTarget; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + readonly srcElement?: EventTarget; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + readonly timeStamp: number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + readonly isTrusted: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + cancelBubble: boolean; + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + readonly aborted: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + readonly reason: any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [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/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + readonly lastModified: number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + readonly subtle: SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + readonly status: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + readonly statusText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + readonly headers: Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + readonly ok: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + readonly redirected: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + readonly method: string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + readonly url: string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + readonly headers: Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + readonly integrity: string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + readonly keepalive: boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +export interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +export interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +export interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +export interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + readonly closed: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + readonly ready: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + readonly desiredSize: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + readonly readable: ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + readonly writable: WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + href: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + readonly origin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + protocol: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + username: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + password: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + host: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + hostname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + port: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + pathname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + search: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + readonly searchParams: URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + hash: string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readonly readyState: number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + readonly url: string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + readonly protocol: string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + readonly extensions: string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/oldest/index.d.ts b/node_modules/@cloudflare/workers-types/oldest/index.d.ts new file mode 100755 index 0000000..dda4816 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/oldest/index.d.ts @@ -0,0 +1,4848 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +declare type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +declare interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +declare interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +declare type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +declare interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +declare interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + readonly type: string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + readonly eventPhase: number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + readonly composed: boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + readonly bubbles: boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + readonly cancelable: boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + readonly defaultPrevented: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + readonly returnValue: boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + readonly currentTarget?: EventTarget; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + readonly srcElement?: EventTarget; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + readonly timeStamp: number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + readonly isTrusted: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + cancelBubble: boolean; + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener = ( + event: EventType, +) => void; +declare interface EventListenerObject { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + readonly aborted: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + readonly reason: any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +declare interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [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/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + readonly lastModified: number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + readonly subtle: SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +declare interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable> + | Record; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + readonly status: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + readonly statusText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + readonly headers: Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + readonly ok: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + readonly redirected: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + readonly method: string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + readonly url: string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + readonly headers: Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + readonly integrity: string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + readonly keepalive: boolean; +} +declare interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +declare type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +declare interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueSendBatchOptions { + delaySeconds?: number; +} +declare interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +declare interface QueueRetryOptions { + delaySeconds?: number; +} +declare interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +declare interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +declare interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +declare interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +declare interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +declare interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +declare interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +declare interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +declare interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +declare interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +declare interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + readonly closed: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + readonly ready: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + readonly desiredSize: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + readonly readable: ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + readonly writable: WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +declare 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; +} +declare interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +declare interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +declare interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +declare interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +declare interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +declare interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + href: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + readonly origin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + protocol: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + username: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + password: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + host: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + hostname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + port: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + pathname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + search: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + readonly searchParams: URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + hash: string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readonly readyState: number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + readonly url: string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + readonly protocol: string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + readonly extensions: string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +declare interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +declare interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +declare interface gpuGPUQueueDescriptor { + label?: string; +} +declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +declare interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +declare interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +declare interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +declare interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +declare interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +declare interface gpuGPUSamplerBindingLayout { + type?: string; +} +declare interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +declare interface gpuGPUBindGroupLayout {} +declare interface gpuGPUBindGroup {} +declare interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +declare interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +declare interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +declare interface gpuGPUSampler {} +declare interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +declare interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +declare interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +declare interface gpuGPUPipelineLayout {} +declare interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +declare interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +declare interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +declare interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +declare interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +declare interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +declare interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +declare interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +declare interface gpuGPUQuerySet {} +declare interface gpuGPUQuerySetDescriptor { + label?: string; +} +declare interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUCommandBufferDescriptor { + label?: string; +} +declare interface gpuGPUCommandBuffer {} +declare interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +declare interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +declare interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +declare interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +declare abstract class gpuGPUError { + get message(): string; +} +declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +declare abstract class gpuGPUInternalError extends gpuGPUError {} +declare abstract class gpuGPUValidationError extends gpuGPUError {} +declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +declare interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +declare interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +declare interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +declare interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +declare interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +declare interface gpuGPUTextureView {} +declare interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +declare interface gpuGPURenderPipeline {} +declare interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +declare interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +declare interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +declare interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +declare interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +declare interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +declare interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +declare interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +declare interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +declare interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +declare interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +declare interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +declare interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +declare interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +declare interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +declare interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +declare interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +declare interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +declare interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +declare interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +declare interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +declare type AiImageClassificationInput = { + image: number[]; +}; +declare type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +declare type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +declare type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +declare type AiObjectDetectionInput = { + image: number[]; +}; +declare type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +declare type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +declare type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +declare type AiSpeechRecognitionInput = { + audio: number[]; +}; +declare type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +declare type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +declare type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +declare type AiTextClassificationInput = { + text: string; +}; +declare type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +declare type AiTextEmbeddingsInput = { + text: string | string[]; +}; +declare type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +declare type RoleScopedChatInput = { + role: string; + content: string; +}; +declare type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +declare type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +declare type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +declare type AiTextToImageOutput = Uint8Array; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +declare type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +declare type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +declare type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +declare interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +declare interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +declare type D1Result = D1Response & { + results: T[]; +}; +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +declare interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params

= Record; +declare type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +declare type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +declare type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +declare module "cloudflare:workers" { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +declare type VectorizeVectorMetadataValue = + | string + | number + | boolean + | string[]; +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +declare type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +declare type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +declare type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/oldest/index.ts b/node_modules/@cloudflare/workers-types/oldest/index.ts new file mode 100755 index 0000000..155f62a --- /dev/null +++ b/node_modules/@cloudflare/workers-types/oldest/index.ts @@ -0,0 +1,4787 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +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 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch( + input: RequestInfo, + init?: RequestInit, + ): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; + GPUAdapter: typeof gpuGPUAdapter; + GPUOutOfMemoryError: typeof gpuGPUOutOfMemoryError; + GPUValidationError: typeof gpuGPUValidationError; + GPUInternalError: typeof gpuGPUInternalError; + GPUDeviceLostInfo: typeof gpuGPUDeviceLostInfo; + GPUBufferUsage: typeof gpuGPUBufferUsage; + GPUShaderStage: typeof gpuGPUShaderStage; + GPUMapMode: typeof gpuGPUMapMode; + GPUTextureUsage: typeof gpuGPUTextureUsage; + GPUColorWrite: typeof gpuGPUColorWrite; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */ +export declare function btoa(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */ +export declare function atob(data: string): string; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */ +export declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */ +export declare function clearTimeout(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */ +export declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */ +export declare function clearInterval(timeoutId: number | null): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ +export declare function queueMicrotask(task: Function): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */ +export declare function reportError(error: any): void; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +export declare function fetch( + input: RequestInfo, + init?: RequestInit, +): Promise; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown, +> = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +export type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +/** + * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) + */ +export interface Performance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ + readonly timeOrigin: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ + now(): number; +} +export interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(): void | Promise; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +export type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + "alarm" | "webSocketMessage" | "webSocketClose" | "webSocketError" +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub; + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; +} +export interface DurableObjectTransaction { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +export interface DurableObjectStorage { + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise; + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise>; + list( + options?: DurableObjectListOptions, + ): Promise>; + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise; + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + transactionSync(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + readonly type: string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + readonly eventPhase: number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + readonly composed: boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + readonly bubbles: boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + readonly cancelable: boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + readonly defaultPrevented: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + readonly returnValue: boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + readonly currentTarget?: EventTarget; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + readonly srcElement?: EventTarget; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + readonly timeStamp: number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + readonly isTrusted: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + cancelBubble: boolean; + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener = ( + event: EventType, +) => void; +export interface EventListenerObject { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event, +> = EventListener | EventListenerObject; +export declare class EventTarget< + EventMap extends Record = Record, +> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + readonly aborted: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + readonly reason: any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +export declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +export interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ); + /** [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/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + readonly lastModified: number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: CacheQueryOptions, + ): Promise; + put(request: RequestInfo, response: Response): Promise; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + readonly subtle: SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + exportKey(format: string, key: CryptoKey): Promise; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean; +} +export declare abstract class CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | (ArrayBuffer | ArrayBufferView); + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +export declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView, + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +export interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + /** Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the list. */ + keys(): IterableIterator; + /** Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable> + | Record; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + formData(): Promise; + blob(): Promise; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirect_static) */ + static redirect(url: string, status?: number): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static) */ + static json(any: any, maybeInit?: ResponseInit | Response): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + readonly status: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + readonly statusText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + readonly headers: Headers; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + readonly ok: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + readonly redirected: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties, +> = Request | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties, +> extends Body { + constructor(input: RequestInfo, init?: RequestInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + readonly method: string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + readonly url: string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + readonly headers: Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + readonly integrity: string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + readonly keepalive: boolean; +} +export interface RequestInit { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export type Service< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher; +export type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +export interface KVNamespace { + get( + key: Key, + options?: Partial>, + ): Promise; + get(key: Key, type: "text"): Promise; + get( + key: Key, + type: "json", + ): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"text">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"json">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream">, + ): Promise; + list( + options?: KVNamespaceListOptions, + ): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: "text", + ): Promise>; + getWithMetadata( + key: Key, + type: "json", + ): Promise>; + getWithMetadata( + key: Key, + type: "arrayBuffer", + ): Promise>; + getWithMetadata( + key: Key, + type: "stream", + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"text">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"json">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer">, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<"stream">, + ): Promise>; + delete(key: Key): Promise; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise; +} +export interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueSendBatchOptions { + delaySeconds?: number; +} +export interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +export interface QueueRetryOptions { + delaySeconds?: number; +} +export interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +export interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +export declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; + storageClass?: string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +export interface UnderlyingSource { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +export interface Transformer { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise; + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +export interface StreamPipeOptions { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +export interface ReadableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; +}; +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise; + cancel(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast( + minElements: number, + view: T, + ): Promise>; +} +export interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +export interface ReadableStreamGetReaderOptions { + /** + * Creates a 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 read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +export interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +export interface ReadableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +export interface ReadableByteStreamController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * 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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +export interface WritableStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +export interface TransformStreamDefaultController { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +export interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +export declare class WritableStream { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + readonly locked: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + readonly closed: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + readonly ready: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + readonly desiredSize: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +export declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + readonly readable: ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + readonly writable: WritableStream; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); + get encoding(): string; +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +export 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; +} +export interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +export interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +export interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +export interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +export interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +export interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + href: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + readonly origin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + protocol: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + username: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + password: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + host: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + hostname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + port: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + pathname: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + search: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + readonly searchParams: URLSearchParams; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + hash: string; + toString(): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record + | [key: string, value: string][], + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + /** Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /** Returns a list of keys in the search params. */ + keys(): IterableIterator; + /** Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + patternOptions?: URLPatternURLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string, + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export interface URLPatternURLPatternOptions { + ignoreCase?: boolean; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget { + constructor(url: string, protocols?: string[] | string); + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly CLOSING: number; + static readonly READY_STATE_CLOSED: number; + static readonly CLOSED: number; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readonly readyState: number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + readonly url: string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + readonly protocol: string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + readonly extensions: string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +export declare abstract class gpuGPUAdapter { + requestDevice(param1?: gpuGPUDeviceDescriptor): Promise; + requestAdapterInfo(unmaskHints?: string[]): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDevice extends EventTarget { + createBuffer(param1: gpuGPUBufferDescriptor): gpuGPUBuffer; + createBindGroupLayout( + descriptor: gpuGPUBindGroupLayoutDescriptor, + ): gpuGPUBindGroupLayout; + createBindGroup(descriptor: gpuGPUBindGroupDescriptor): gpuGPUBindGroup; + createSampler(descriptor: gpuGPUSamplerDescriptor): gpuGPUSampler; + createShaderModule( + descriptor: gpuGPUShaderModuleDescriptor, + ): gpuGPUShaderModule; + createPipelineLayout( + descriptor: gpuGPUPipelineLayoutDescriptor, + ): gpuGPUPipelineLayout; + createComputePipeline( + descriptor: gpuGPUComputePipelineDescriptor, + ): gpuGPUComputePipeline; + createRenderPipeline( + descriptor: gpuGPURenderPipelineDescriptor, + ): gpuGPURenderPipeline; + createCommandEncoder( + descriptor?: gpuGPUCommandEncoderDescriptor, + ): gpuGPUCommandEncoder; + createTexture(param1: gpuGPUTextureDescriptor): gpuGPUTexture; + destroy(): void; + createQuerySet(descriptor: gpuGPUQuerySetDescriptor): gpuGPUQuerySet; + pushErrorScope(filter: string): void; + popErrorScope(): Promise; + get queue(): gpuGPUQueue; + get lost(): Promise; + get features(): gpuGPUSupportedFeatures; + get limits(): gpuGPUSupportedLimits; +} +export interface gpuGPUDeviceDescriptor { + label?: string; + requiredFeatures?: string[]; + requiredLimits?: Record; + defaultQueue?: gpuGPUQueueDescriptor; +} +export interface gpuGPUBufferDescriptor { + label: string; + size: number | bigint; + usage: number; + mappedAtCreation: boolean; +} +export interface gpuGPUQueueDescriptor { + label?: string; +} +export declare abstract class gpuGPUBufferUsage { + static readonly MAP_READ: number; + static readonly MAP_WRITE: number; + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly INDEX: number; + static readonly VERTEX: number; + static readonly UNIFORM: number; + static readonly STORAGE: number; + static readonly INDIRECT: number; + static readonly QUERY_RESOLVE: number; +} +export interface gpuGPUBuffer { + getMappedRange(size?: number | bigint, param2?: number | bigint): ArrayBuffer; + unmap(): void; + destroy(): void; + mapAsync( + offset: number, + size?: number | bigint, + param3?: number | bigint, + ): Promise; + get size(): number | bigint; + get usage(): number; + get mapState(): string; +} +export declare abstract class gpuGPUShaderStage { + static readonly VERTEX: number; + static readonly FRAGMENT: number; + static readonly COMPUTE: number; +} +export interface gpuGPUBindGroupLayoutDescriptor { + label?: string; + entries: gpuGPUBindGroupLayoutEntry[]; +} +export interface gpuGPUBindGroupLayoutEntry { + binding: number; + visibility: number; + buffer?: gpuGPUBufferBindingLayout; + sampler?: gpuGPUSamplerBindingLayout; + texture?: gpuGPUTextureBindingLayout; + storageTexture?: gpuGPUStorageTextureBindingLayout; +} +export interface gpuGPUStorageTextureBindingLayout { + access?: string; + format: string; + viewDimension?: string; +} +export interface gpuGPUTextureBindingLayout { + sampleType?: string; + viewDimension?: string; + multisampled?: boolean; +} +export interface gpuGPUSamplerBindingLayout { + type?: string; +} +export interface gpuGPUBufferBindingLayout { + type?: string; + hasDynamicOffset?: boolean; + minBindingSize?: number | bigint; +} +export interface gpuGPUBindGroupLayout {} +export interface gpuGPUBindGroup {} +export interface gpuGPUBindGroupDescriptor { + label?: string; + layout: gpuGPUBindGroupLayout; + entries: gpuGPUBindGroupEntry[]; +} +export interface gpuGPUBindGroupEntry { + binding: number; + resource: gpuGPUBufferBinding | gpuGPUSampler; +} +export interface gpuGPUBufferBinding { + buffer: gpuGPUBuffer; + offset?: number | bigint; + size?: number | bigint; +} +export interface gpuGPUSampler {} +export interface gpuGPUSamplerDescriptor { + label?: string; + addressModeU?: string; + addressModeV?: string; + addressModeW?: string; + magFilter?: string; + minFilter?: string; + mipmapFilter?: string; + lodMinClamp?: number; + lodMaxClamp?: number; + compare: string; + maxAnisotropy?: number; +} +export interface gpuGPUShaderModule { + getCompilationInfo(): Promise; +} +export interface gpuGPUShaderModuleDescriptor { + label?: string; + code: string; +} +export interface gpuGPUPipelineLayout {} +export interface gpuGPUPipelineLayoutDescriptor { + label?: string; + bindGroupLayouts: gpuGPUBindGroupLayout[]; +} +export interface gpuGPUComputePipeline { + getBindGroupLayout(index: number): gpuGPUBindGroupLayout; +} +export interface gpuGPUComputePipelineDescriptor { + label?: string; + compute: gpuGPUProgrammableStage; + layout: string | gpuGPUPipelineLayout; +} +export interface gpuGPUProgrammableStage { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; +} +export interface gpuGPUCommandEncoder { + get label(): string; + beginComputePass( + descriptor?: gpuGPUComputePassDescriptor, + ): gpuGPUComputePassEncoder; + beginRenderPass( + descriptor: gpuGPURenderPassDescriptor, + ): gpuGPURenderPassEncoder; + copyBufferToBuffer( + source: gpuGPUBuffer, + sourceOffset: number | bigint, + destination: gpuGPUBuffer, + destinationOffset: number | bigint, + size: number | bigint, + ): void; + finish(param0?: gpuGPUCommandBufferDescriptor): gpuGPUCommandBuffer; + copyTextureToBuffer( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyBuffer, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyBufferToTexture( + source: gpuGPUImageCopyBuffer, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + copyTextureToTexture( + source: gpuGPUImageCopyTexture, + destination: gpuGPUImageCopyTexture, + copySize: Iterable | gpuGPUExtent3DDict, + ): void; + clearBuffer( + buffer: gpuGPUBuffer, + offset?: number | bigint, + size?: number | bigint, + ): void; +} +export interface gpuGPUCommandEncoderDescriptor { + label?: string; +} +export interface gpuGPUComputePassEncoder { + setPipeline(pipeline: gpuGPUComputePipeline): void; + setBindGroup( + index: number, + bindGroup: gpuGPUBindGroup | null, + dynamicOffsets?: Iterable, + ): void; + dispatchWorkgroups( + workgroupCountX: number, + workgroupCountY?: number, + workgroupCountZ?: number, + ): void; + end(): void; +} +export interface gpuGPUComputePassDescriptor { + label?: string; + timestampWrites?: gpuGPUComputePassTimestampWrites; +} +export interface gpuGPUQuerySet {} +export interface gpuGPUQuerySetDescriptor { + label?: string; +} +export interface gpuGPUComputePassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUCommandBufferDescriptor { + label?: string; +} +export interface gpuGPUCommandBuffer {} +export interface gpuGPUQueue { + submit(commandBuffers: gpuGPUCommandBuffer[]): void; + writeBuffer( + buffer: gpuGPUBuffer, + bufferOffset: number | bigint, + data: ArrayBuffer | ArrayBufferView, + dataOffset?: number | bigint, + size?: number | bigint, + ): void; +} +export declare abstract class gpuGPUMapMode { + static readonly READ: number; + static readonly WRITE: number; +} +export interface gpuGPUAdapterInfo { + get vendor(): string; + get architecture(): string; + get device(): string; + get description(): string; +} +export interface gpuGPUSupportedFeatures { + has(name: string): boolean; + keys(): string[]; +} +export interface gpuGPUSupportedLimits { + get maxTextureDimension1D(): number; + get maxTextureDimension2D(): number; + get maxTextureDimension3D(): number; + get maxTextureArrayLayers(): number; + get maxBindGroups(): number; + get maxBindingsPerBindGroup(): number; + get maxDynamicUniformBuffersPerPipelineLayout(): number; + get maxDynamicStorageBuffersPerPipelineLayout(): number; + get maxSampledTexturesPerShaderStage(): number; + get maxSamplersPerShaderStage(): number; + get maxStorageBuffersPerShaderStage(): number; + get maxStorageTexturesPerShaderStage(): number; + get maxUniformBuffersPerShaderStage(): number; + get maxUniformBufferBindingSize(): number | bigint; + get maxStorageBufferBindingSize(): number | bigint; + get minUniformBufferOffsetAlignment(): number; + get minStorageBufferOffsetAlignment(): number; + get maxVertexBuffers(): number; + get maxBufferSize(): number | bigint; + get maxVertexAttributes(): number; + get maxVertexBufferArrayStride(): number; + get maxInterStageShaderComponents(): number; + get maxInterStageShaderVariables(): number; + get maxColorAttachments(): number; + get maxColorAttachmentBytesPerSample(): number; + get maxComputeWorkgroupStorageSize(): number; + get maxComputeInvocationsPerWorkgroup(): number; + get maxComputeWorkgroupSizeX(): number; + get maxComputeWorkgroupSizeY(): number; + get maxComputeWorkgroupSizeZ(): number; + get maxComputeWorkgroupsPerDimension(): number; +} +export declare abstract class gpuGPUError { + get message(): string; +} +export declare abstract class gpuGPUOutOfMemoryError extends gpuGPUError {} +export declare abstract class gpuGPUInternalError extends gpuGPUError {} +export declare abstract class gpuGPUValidationError extends gpuGPUError {} +export declare abstract class gpuGPUDeviceLostInfo { + get message(): string; + get reason(): string; +} +export interface gpuGPUCompilationMessage { + get message(): string; + get type(): string; + get lineNum(): number; + get linePos(): number; + get offset(): number; + get length(): number; +} +export interface gpuGPUCompilationInfo { + get messages(): gpuGPUCompilationMessage[]; +} +export declare abstract class gpuGPUTextureUsage { + static readonly COPY_SRC: number; + static readonly COPY_DST: number; + static readonly TEXTURE_BINDING: number; + static readonly STORAGE_BINDING: number; + static readonly RENDER_ATTACHMENT: number; +} +export interface gpuGPUTextureDescriptor { + label: string; + size: number[] | gpuGPUExtent3DDict; + mipLevelCount?: number; + sampleCount?: number; + dimension?: string; + format: string; + usage: number; + viewFormats?: string[]; +} +export interface gpuGPUExtent3DDict { + width: number; + height?: number; + depthOrArrayLayers?: number; +} +export interface gpuGPUTexture { + createView(descriptor?: gpuGPUTextureViewDescriptor): gpuGPUTextureView; + destroy(): void; + get width(): number; + get height(): number; + get depthOrArrayLayers(): number; + get mipLevelCount(): number; + get dimension(): string; + get format(): string; + get usage(): number; +} +export interface gpuGPUTextureView {} +export interface gpuGPUTextureViewDescriptor { + label: string; + format: string; + dimension: string; + aspect?: string; + baseMipLevel?: number; + mipLevelCount: number; + baseArrayLayer?: number; + arrayLayerCount: number; +} +export declare abstract class gpuGPUColorWrite { + static readonly RED: number; + static readonly GREEN: number; + static readonly BLUE: number; + static readonly ALPHA: number; + static readonly ALL: number; +} +export interface gpuGPURenderPipeline {} +export interface gpuGPURenderPipelineDescriptor { + label?: string; + layout: string | gpuGPUPipelineLayout; + vertex: gpuGPUVertexState; + primitive?: gpuGPUPrimitiveState; + depthStencil?: gpuGPUDepthStencilState; + multisample?: gpuGPUMultisampleState; + fragment?: gpuGPUFragmentState; +} +export interface gpuGPUVertexState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + buffers?: gpuGPUVertexBufferLayout[]; +} +export interface gpuGPUVertexBufferLayout { + arrayStride: number | bigint; + stepMode?: string; + attributes: gpuGPUVertexAttribute[]; +} +export interface gpuGPUVertexAttribute { + format: string; + offset: number | bigint; + shaderLocation: number; +} +export interface gpuGPUPrimitiveState { + topology?: string; + stripIndexFormat?: string; + frontFace?: string; + cullMode?: string; + unclippedDepth?: boolean; +} +export interface gpuGPUStencilFaceState { + compare?: string; + failOp?: string; + depthFailOp?: string; + passOp?: string; +} +export interface gpuGPUDepthStencilState { + format: string; + depthWriteEnabled: boolean; + depthCompare: string; + stencilFront?: gpuGPUStencilFaceState; + stencilBack?: gpuGPUStencilFaceState; + stencilReadMask?: number; + stencilWriteMask?: number; + depthBias?: number; + depthBiasSlopeScale?: number; + depthBiasClamp?: number; +} +export interface gpuGPUMultisampleState { + count?: number; + mask?: number; + alphaToCoverageEnabled?: boolean; +} +export interface gpuGPUFragmentState { + module: gpuGPUShaderModule; + entryPoint: string; + constants?: Record; + targets: gpuGPUColorTargetState[]; +} +export interface gpuGPUColorTargetState { + format: string; + blend: gpuGPUBlendState; + writeMask?: number; +} +export interface gpuGPUBlendState { + color: gpuGPUBlendComponent; + alpha: gpuGPUBlendComponent; +} +export interface gpuGPUBlendComponent { + operation?: string; + srcFactor?: string; + dstFactor?: string; +} +export interface gpuGPURenderPassEncoder { + setPipeline(pipeline: gpuGPURenderPipeline): void; + draw( + vertexCount: number, + instanceCount?: number, + firstVertex?: number, + firstInstance?: number, + ): void; + end(): void; +} +export interface gpuGPURenderPassDescriptor { + label?: string; + colorAttachments: gpuGPURenderPassColorAttachment[]; + depthStencilAttachment?: gpuGPURenderPassDepthStencilAttachment; + occlusionQuerySet?: gpuGPUQuerySet; + timestampWrites?: gpuGPURenderPassTimestampWrites; + maxDrawCount?: number | bigint; +} +export interface gpuGPURenderPassColorAttachment { + view: gpuGPUTextureView; + depthSlice?: number; + resolveTarget?: gpuGPUTextureView; + clearValue?: number[] | gpuGPUColorDict; + loadOp: string; + storeOp: string; +} +export interface gpuGPUColorDict { + r: number; + g: number; + b: number; + a: number; +} +export interface gpuGPURenderPassDepthStencilAttachment { + view: gpuGPUTextureView; + depthClearValue?: number; + depthLoadOp?: string; + depthStoreOp?: string; + depthReadOnly?: boolean; + stencilClearValue?: number; + stencilLoadOp?: string; + stencilStoreOp?: string; + stencilReadOnly?: boolean; +} +export interface gpuGPURenderPassTimestampWrites { + querySet: gpuGPUQuerySet; + beginningOfPassWriteIndex?: number; + endOfPassWriteIndex?: number; +} +export interface gpuGPUImageCopyTexture { + texture: gpuGPUTexture; + mipLevel?: number; + origin?: number[] | gpuGPUOrigin3DDict; + aspect?: string; +} +export interface gpuGPUImageCopyBuffer { + buffer: gpuGPUBuffer; + offset?: number | bigint; + bytesPerRow?: number; + rowsPerImage?: number; +} +export interface gpuGPUOrigin3DDict { + x?: number; + y?: number; + z?: number; +} +export type AiImageClassificationInput = { + image: number[]; +}; +export type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +export type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +export type AiImageToTextOutput = { + description: string; +}; +export declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +export type AiObjectDetectionInput = { + image: number[]; +}; +export type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +export type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +export type AiSentenceSimilarityOutput = number[]; +export declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +export type AiSpeechRecognitionInput = { + audio: number[]; +}; +export type AiSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +export declare abstract class BaseAiSpeechRecognition { + inputs: AiSpeechRecognitionInput; + postProcessedOutputs: AiSpeechRecognitionOutput; +} +export type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +export type AiSummarizationOutput = { + summary: string; +}; +export declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +export type AiTextClassificationInput = { + text: string; +}; +export type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +export declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +export type AiTextEmbeddingsInput = { + text: string | string[]; +}; +export type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +export declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +export type RoleScopedChatInput = { + role: string; + content: string; +}; +export type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + messages?: RoleScopedChatInput[]; +}; +export type AiTextGenerationOutput = + | { + response?: string; + } + | ReadableStream; +export declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +export type AiTextToImageInput = { + prompt: string; + image?: number[]; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; +}; +export type AiTextToImageOutput = Uint8Array; +export declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +export type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +export type AiTranslationOutput = { + translated_text?: string; +}; +export declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +export type AiOptions = { + prefix?: string; + extraHeaders?: object; +}; +export declare abstract class Ai { + run( + model: + | "@cf/huggingface/distilbert-sst-2-int8" + | "@cf/jpmorganchase/roberta-spam" + | "@cf/inml/inml-roberta-dga", + inputs: BaseAiTextClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/stabilityai/stable-diffusion-xl-base-1.0" + | "@cf/runwayml/stable-diffusion-v1-5-inpainting" + | "@cf/runwayml/stable-diffusion-v1-5-img2img" + | "@cf/lykon/dreamshaper-8-lcm" + | "@cf/bytedance/stable-diffusion-xl-lightning", + inputs: BaseAiTextToImage["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@hf/sentence-transformers/all-minilm-l6-v2", + inputs: BaseAiSentenceSimilarity["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/baai/bge-small-en-v1.5" + | "@cf/baai/bge-base-en-v1.5" + | "@cf/baai/bge-large-en-v1.5", + inputs: BaseAiTextEmbeddings["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/openai/whisper" + | "@cf/openai/whisper-tiny-en" + | "@cf/openai/whisper-sherpa", + inputs: BaseAiSpeechRecognition["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/microsoft/resnet-50", + inputs: BaseAiImageClassification["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/detr-resnet-50", + inputs: BaseAiObjectDetection["inputs"], + options?: AiOptions, + ): Promise; + run( + model: + | "@cf/meta/llama-3-8b-instruct" + | "@cf/meta/llama-2-7b-chat-int8" + | "@cf/mistral/mistral-7b-instruct-v0.1" + | "@cf/mistral/mistral-7b-instruct-v0.1-vllm" + | "@cf/mistral/mistral-7b-instruct-v0.2-lora" + | "@cf/meta/llama-2-7b-chat-fp16" + | "@hf/thebloke/llama-2-13b-chat-awq" + | "@hf/thebloke/zephyr-7b-beta-awq" + | "@hf/thebloke/mistral-7b-instruct-v0.1-awq" + | "@hf/thebloke/codellama-7b-instruct-awq" + | "@hf/thebloke/openchat_3.5-awq" + | "@hf/thebloke/openhermes-2.5-mistral-7b-awq" + | "@hf/thebloke/neural-chat-7b-v3-1-awq" + | "@hf/thebloke/llamaguard-7b-awq" + | "@hf/thebloke/deepseek-coder-6.7b-base-awq" + | "@hf/thebloke/deepseek-coder-6.7b-instruct-awq" + | "@hf/nousresearch/hermes-2-pro-mistral-7b" + | "@hf/mistral/mistral-7b-instruct-v0.2" + | "@cf/mistral/mixtral-8x7b-instruct-v0.1-awq" + | "@hf/google/gemma-7b-it" + | "@hf/nexusflow/starling-lm-7b-beta" + | "@cf/deepseek-ai/deepseek-math-7b-instruct" + | "@cf/defog/sqlcoder-7b-2" + | "@cf/openchat/openchat-3.5-0106" + | "@cf/tiiuae/falcon-7b-instruct" + | "@cf/thebloke/discolm-german-7b-v1-awq" + | "@cf/qwen/qwen1.5-0.5b-chat" + | "@cf/qwen/qwen1.5-1.8b-chat" + | "@cf/qwen/qwen1.5-7b-chat-awq" + | "@cf/qwen/qwen1.5-14b-chat-awq" + | "@cf/tinyllama/tinyllama-1.1b-chat-v1.0" + | "@cf/microsoft/phi-2" + | "@cf/google/gemma-2b-it-lora" + | "@cf/google/gemma-7b-it-lora" + | "@cf/meta-llama/llama-2-7b-chat-hf-lora", + inputs: BaseAiTextGeneration["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/meta/m2m100-1.2b", + inputs: BaseAiTranslation["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/facebook/bart-large-cnn", + inputs: BaseAiSummarization["inputs"], + options?: AiOptions, + ): Promise; + run( + model: "@cf/unum/uform-gen2-qwen-500m" | "@cf/llava-hf/llava-1.5-7b-hf", + inputs: BaseAiImageToText["inputs"], + options?: AiOptions, + ): Promise; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata, +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +export type Iso3166Alpha2Code = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties; +export interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; +} +export interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +export type D1Result = D1Response & { + results: T[]; +}; +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run(): Promise; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +export interface Disposable {} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params

= Record; +export type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +export type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +export type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +export declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: "__RPC_STUB_BRAND"; + export const __RPC_TARGET_BRAND: "__RPC_TARGET_BRAND"; + export const __WORKER_ENTRYPOINT_BRAND: "__WORKER_ENTRYPOINT_BRAND"; + export const __DURABLE_OBJECT_BRAND: "__DURABLE_OBJECT_BRAND"; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + type Serializable = + // Structured cloneables + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + // Structured cloneable composites + | Map + | Set + | ReadonlyArray + | { + [key: string | number]: Serializable; + } + // Special types + | ReadableStream + | WritableStream + | Request + | Response + | Headers + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // Recursively rewrite all `Stubable` types with `Stub`s + type Stubify = T extends Stubable + ? Stub + : T extends Map + ? Map, Stubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Stubify; + } + : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + type Unstubify = + T extends StubBase + ? V + : T extends Map + ? Map, Unstubify> + : T extends Set + ? Set> + : T extends Array + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends { + [key: string | number]: unknown; + } + ? { + [K in keyof T]: Unstubify; + } + : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + type Result = R extends Stubable + ? Promise> & Provider + : R extends Serializable + ? Promise & MaybeDisposable> & MaybeProvider + : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty; + }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +export type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +export type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +export type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of the other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export type VectorizeMatch = Pick, "values"> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions, + ): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +export type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; +}; +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/package.json b/node_modules/@cloudflare/workers-types/package.json new file mode 100644 index 0000000..5fd4fe3 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/package.json @@ -0,0 +1,11 @@ +{ + "name": "@cloudflare/workers-types", + "description": "TypeScript typings for Cloudflare Workers", + "repository": { + "type": "git", + "url": "https://github.com/cloudflare/workerd" + }, + "author": "Cloudflare Workers DevProd Team (https://workers.cloudflare.com)", + "license": "MIT OR Apache-2.0", + "version": "4.20240512.0" +} diff --git a/node_modules/@cspotcode/source-map-support/LICENSE.md b/node_modules/@cspotcode/source-map-support/LICENSE.md new file mode 100644 index 0000000..6247ca9 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Evan Wallace + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@cspotcode/source-map-support/README.md b/node_modules/@cspotcode/source-map-support/README.md new file mode 100644 index 0000000..f739070 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/README.md @@ -0,0 +1,289 @@ +# Source Map Support + +[![NPM version](https://img.shields.io/npm/v/@cspotcode/source-map-support.svg?style=flat)](https://npmjs.org/package/@cspotcode/source-map-support) +[![NPM downloads](https://img.shields.io/npm/dm/@cspotcode/source-map-support.svg?style=flat)](https://npmjs.org/package/@cspotcode/source-map-support) +[![Build status](https://img.shields.io/github/workflow/status/cspotcode/node-source-map-support/Continuous%20Integration)](https://github.com/cspotcode/node-source-map-support/actions?query=workflow%3A%22Continuous+Integration%22) + +This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process. + +## Installation and Usage + +#### Node support + +``` +$ npm install @cspotcode/source-map-support +``` + +Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler): + +``` +//# sourceMappingURL=path/to/source.map +``` + +If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be +respected (e.g. if a file mentions the comment in code, or went through multiple transpilers). +The path should either be absolute or relative to the compiled file. + +From here you have two options. + +##### CLI Usage + +```bash +node -r @cspotcode/source-map-support/register compiled.js +# Or to enable hookRequire +node -r @cspotcode/source-map-support/register-hook-require compiled.js +``` + +##### Programmatic Usage + +Put the following line at the top of the compiled file. + +```js +require('@cspotcode/source-map-support').install(); +``` + +It is also possible to install the source map support directly by +requiring the `register` module which can be handy with ES6: + +```js +import '@cspotcode/source-map-support/register' + +// Instead of: +import sourceMapSupport from '@cspotcode/source-map-support' +sourceMapSupport.install() +``` +Note: if you're using babel-register, it includes source-map-support already. + +It is also very useful with Mocha: + +``` +$ mocha --require @cspotcode/source-map-support/register tests/ +``` + +#### Browser support + +This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code. + +This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify. + +```html + + +``` + +This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency: + +```html + +``` + +## Options + +This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer: + +```js +require('@cspotcode/source-map-support').install({ + handleUncaughtExceptions: false +}); +``` + +This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access. + +```js +require('@cspotcode/source-map-support').install({ + retrieveSourceMap: function(source) { + if (source === 'compiled.js') { + return { + url: 'original.js', + map: fs.readFileSync('compiled.js.map', 'utf8') + }; + } + return null; + } +}); +``` + +The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment. +In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'. + +```js +require('@cspotcode/source-map-support').install({ + environment: 'node' +}); +``` + +To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps. + + +```js +require('@cspotcode/source-map-support').install({ + hookRequire: true +}); +``` + +This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage. + +## Demos + +#### Basic Demo + +original.js: + +```js +throw new Error('test'); // This is the original code +``` + +compiled.js: + +```js +require('@cspotcode/source-map-support').install(); + +throw new Error('test'); // This is the compiled code +// The next line defines the sourceMapping. +//# sourceMappingURL=compiled.js.map +``` + +compiled.js.map: + +```json +{ + "version": 3, + "file": "compiled.js", + "sources": ["original.js"], + "names": [], + "mappings": ";;AAAA,MAAM,IAAI" +} +``` + +Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js): + +``` +$ node compiled.js + +original.js:1 +throw new Error('test'); // This is the original code + ^ +Error: test + at Object. (original.js:1:7) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### TypeScript Demo + +demo.ts: + +```typescript +declare function require(name: string); +require('@cspotcode/source-map-support').install(); +class Foo { + constructor() { this.bar(); } + bar() { throw new Error('this is a demo'); } +} +new Foo(); +``` + +Compile and run the file using the TypeScript compiler from the terminal: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('@cspotcode/source-map-support').install()` in the code base: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node -r source-map-support/register demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### CoffeeScript Demo + +demo.coffee: + +```coffee +require('@cspotcode/source-map-support').install() +foo = -> + bar = -> throw new Error 'this is a demo' + bar() +foo() +``` + +Compile and run the file using the CoffeeScript compiler from the terminal: + +```sh +$ npm install @cspotcode/source-map-support coffeescript +$ node_modules/.bin/coffee --map --compile demo.coffee +$ node demo.js + +demo.coffee:3 + bar = -> throw new Error 'this is a demo' + ^ +Error: this is a demo + at bar (demo.coffee:3:22) + at foo (demo.coffee:4:3) + at Object. (demo.coffee:5:1) + at Object. (demo.coffee:1:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) +``` + +## Tests + +This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests: + +* Build the tests using `build.js` +* Launch the HTTP server (`npm run serve-tests`) and visit + * http://127.0.0.1:1336/amd-test + * http://127.0.0.1:1336/browser-test + * http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details). +* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/ + +## License + +This code is available under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/node_modules/@cspotcode/source-map-support/browser-source-map-support.js b/node_modules/@cspotcode/source-map-support/browser-source-map-support.js new file mode 100644 index 0000000..782da50 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/browser-source-map-support.js @@ -0,0 +1,114 @@ +/* + * Support for source maps in V8 stack traces + * https://github.com/evanw/node-source-map-support + */ +/* + The buffer module from node.js, for the browser. + + @author Feross Aboukhadijeh + license MIT +*/ +(this.define||function(R,U){this.sourceMapSupport=U()})("browser-source-map-support",function(R){(function e(C,J,A){function p(f,c){if(!J[f]){if(!C[f]){var l="function"==typeof require&&require;if(!c&&l)return l(f,!0);if(t)return t(f,!0);throw Error("Cannot find module '"+f+"'");}l=J[f]={exports:{}};C[f][0].call(l.exports,function(q){var r=C[f][1][q];return p(r?r:q)},l,l.exports,e,C,J,A)}return J[f].exports}for(var t="function"==typeof require&&require,m=0;mm)return-1;if(58>m)return m-48+52;if(91>m)return m-65;if(123>m)return m-97+26}var t="undefined"!==typeof Uint8Array?Uint8Array:Array;e.toByteArray=function(m){function f(d){q[k++]=d}if(0>16);f((u&65280)>>8);f(u&255)}2===l?(u=p(m.charAt(c))<<2|p(m.charAt(c+1))>>4,f(u&255)):1===l&&(u=p(m.charAt(c))<<10|p(m.charAt(c+1))<<4|p(m.charAt(c+2))>>2,f(u>>8&255),f(u&255));return q};e.fromByteArray=function(m){var f=m.length%3,c="",l;var q=0;for(l=m.length-f;q> +18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);c+=r}switch(f){case 1:r=m[m.length-1];c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<4&63);c+="==";break;case 2:r=(m[m.length-2]<<8)+ +m[m.length-1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),c+="="}return c}})("undefined"===typeof A?this.base64js={}:A)},{}],3:[function(C,J,A){},{}],4:[function(C,J,A){(function(e){var p=Object.prototype.toString,t="function"===typeof e.alloc&&"function"===typeof e.allocUnsafe&&"function"=== +typeof e.from;J.exports=function(m,f,c){if("number"===typeof m)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===p.call(m).slice(8,-1)){f>>>=0;var l=m.byteLength-f;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===c)c=l;else if(c>>>=0,c>l)throw new RangeError("'length' is out of bounds");return t?e.from(m.slice(f,f+c)):new e(new Uint8Array(m.slice(f,f+c)))}if("string"===typeof m){c=f;if("string"!==typeof c||""===c)c="utf8";if(!e.isEncoding(c))throw new TypeError('"encoding" must be a valid string encoding'); +return t?e.from(m,c):new e(m,c)}return t?e.from(m):new e(m)}}).call(this,C("buffer").Buffer)},{buffer:5}],5:[function(C,J,A){function e(a,b,h){if(!(this instanceof e))return new e(a,b,h);var w=typeof a;if("number"===w)var y=0>>0:0;else if("string"===w){if("base64"===b)for(a=(a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")).replace(L,"");0!==a.length%4;)a+="=";y=e.byteLength(a,b)}else if("object"===w&&null!==a)"Buffer"===a.type&&z(a.data)&&(a=a.data),y=0<+a.length?Math.floor(+a.length):0;else throw new TypeError("must start with number, buffer, array or string"); +if(this.length>G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");if(e.TYPED_ARRAY_SUPPORT)var I=e._augment(new Uint8Array(y));else I=this,I.length=y,I._isBuffer=!0;if(e.TYPED_ARRAY_SUPPORT&&"number"===typeof a.byteLength)I._set(a);else{var K=a;if(z(K)||e.isBuffer(K)||K&&"object"===typeof K&&"number"===typeof K.length)if(e.isBuffer(a))for(b=0;ba)throw new RangeError("offset is not uint");if(a+b>h)throw new RangeError("Trying to access beyond buffer length");}function m(a,b,h,w,y,I){if(!e.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>y||ba.length)throw new TypeError("index out of range"); +}function f(a,b,h,w){0>b&&(b=65535+b+1);for(var y=0,I=Math.min(a.length-h,2);y>>8*(w?y:1-y)}function c(a,b,h,w){0>b&&(b=4294967295+b+1);for(var y=0,I=Math.min(a.length-h,4);y>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||ba.length)throw new TypeError("index out of range");}function q(a,b,h,w,y){y||l(a,b,h,4,3.4028234663852886E38,-3.4028234663852886E38);v.write(a,b,h,w,23,4);return h+4}function r(a, +b,h,w,y){y||l(a,b,h,8,1.7976931348623157E308,-1.7976931348623157E308);v.write(a,b,h,w,52,8);return h+8}function k(a){for(var b=[],h=0;h=w)b.push(w);else{var y=h;55296<=w&&57343>=w&&h++;w=encodeURIComponent(a.slice(y,h+1)).substr(1).split("%");for(y=0;y=b.length||y>=a.length);y++)b[y+ +h]=a[y];return y}function g(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}var n=C("base64-js"),v=C("ieee754"),z=C("is-array");A.Buffer=e;A.SlowBuffer=e;A.INSPECT_MAX_BYTES=50;e.poolSize=8192;var G=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(h){return!1}}();e.isBuffer=function(a){return!(null== +a||!a._isBuffer)};e.compare=function(a,b){if(!e.isBuffer(a)||!e.isBuffer(b))throw new TypeError("Arguments must be Buffers");for(var h=a.length,w=b.length,y=0,I=Math.min(h,w);y>>1;break;case "utf8":case "utf-8":h=k(a).length;break;case "base64":h=n.toByteArray(a).length; +break;default:h=a.length}return h};e.prototype.length=void 0;e.prototype.parent=void 0;e.prototype.toString=function(a,b,h){var w=!1;b>>>=0;h=void 0===h||Infinity===h?this.length:h>>>0;a||(a="utf8");0>b&&(b=0);h>this.length&&(h=this.length);if(h<=b)return"";for(;;)switch(a){case "hex":a=b;b=h;h=this.length;if(!a||0>a)a=0;if(!b||0>b||b>h)b=h;w="";for(h=a;hw?"0"+w.toString(16):w.toString(16),w=a+w;return w;case "utf8":case "utf-8":w=a="";for(h=Math.min(this.length,h);b= +this[b]?(a+=g(w)+String.fromCharCode(this[b]),w=""):w+="%"+this[b].toString(16);return a+g(w);case "ascii":return p(this,b,h);case "binary":return p(this,b,h);case "base64":return b=0===b&&h===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(b,h)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,h);h="";for(a=0;ab&&(a+=" ... "));return""};e.prototype.compare=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return e.compare(this,a)};e.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead."); +return this.readUInt8(a)};e.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};e.prototype.write=function(a,b,h,w){if(isFinite(b))isFinite(h)||(w=h,h=void 0);else{var y=w;w=b;b=h;h=y}b=Number(b)||0;y=this.length-b;h?(h=Number(h),h>y&&(h=y)):h=y;w=String(w||"utf8").toLowerCase();switch(w){case "hex":b=Number(b)||0;w=this.length-b;h?(h=Number(h),h>w&&(h=w)):h=w;w=a.length;if(0!==w%2)throw Error("Invalid hex string");h>w/ +2&&(h=w/2);for(w=0;w>8;K%=256;y.push(K);y.push(w)}a=d(y,this,b,h,2);break;default:throw new TypeError("Unknown encoding: "+ +w);}return a};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};e.prototype.slice=function(a,b){var h=this.length;a=~~a;b=void 0===b?h:~~b;0>a?(a+=h,0>a&&(a=0)):a>h&&(a=h);0>b?(b+=h,0>b&&(b=0)):b>h&&(b=h);b>>=0;h||m(this,a,b,1,255,0);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[b]=a;return b+1};e.prototype.writeUInt16LE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeUInt16BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeUInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=a):c(this,a,b,!0);return b+4};e.prototype.writeUInt32BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,127,-128);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[b]=a;return b+1};e.prototype.writeInt16LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeInt16BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):c(this,a,b,!0);return b+4};e.prototype.writeInt32BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);0>a&&(a=4294967295+a+1);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+ +2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeFloatLE=function(a,b,h){return q(this,a,b,!0,h)};e.prototype.writeFloatBE=function(a,b,h){return q(this,a,b,!1,h)};e.prototype.writeDoubleLE=function(a,b,h){return r(this,a,b,!0,h)};e.prototype.writeDoubleBE=function(a,b,h){return r(this,a,b,!1,h)};e.prototype.copy=function(a,b,h,w){h||(h=0);w||0===w||(w=this.length);b||(b=0);if(w!==h&&0!==a.length&&0!==this.length){if(wb||b>=a.length)throw new TypeError("targetStart out of bounds"); +if(0>h||h>=this.length)throw new TypeError("sourceStart out of bounds");if(0>w||w>this.length)throw new TypeError("sourceEnd out of bounds");w>this.length&&(w=this.length);a.length-bw||!e.TYPED_ARRAY_SUPPORT)for(var y=0;yb||b>=this.length)throw new TypeError("start out of bounds"); +if(0>h||h>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;b>1,r=-7;f=t?f-1:0;var k=t?-1:1,u=e[p+f];f+=k;t=u&(1<<-r)-1;u>>=-r;for(r+=c;0>=-r;for(r+=m;0>1,u=23===f?Math.pow(2,-24)-Math.pow(2,-77):0;c=m?0:c-1;var d=m?1:-1,g=0>p||0===p&&0>1/p?1:0;p=Math.abs(p);isNaN(p)||Infinity===p?(p=isNaN(p)?1:0,m=r):(m=Math.floor(Math.log(p)/Math.LN2),1>p*(l=Math.pow(2,-m))&&(m--,l*=2),p=1<=m+k?p+u/l:p+u*Math.pow(2,1-k),2<=p*l&&(m++,l/=2),m+k>=r?(p=0,m=r):1<=m+k?(p=(p*l-1)*Math.pow(2,f),m+=k):(p=p*Math.pow(2,k-1)*Math.pow(2,f),m=0));for(;8<=f;e[t+c]=p&255,c+= +d,p/=256,f-=8);m=m<z?[]:n.slice(v,z-v+1)}c=A.resolve(c).substr(1);l=A.resolve(l).substr(1); +for(var r=q(c.split("/")),k=q(l.split("/")),u=Math.min(r.length,k.length),d=u,g=0;gl&&(l=c.length+l);return c.substr(l,q)}}).call(this,C("g5I+bs"))},{"g5I+bs":9}],9:[function(C,J,A){function e(){}C=J.exports={};C.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(t){return window.setImmediate(t)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var p=[];window.addEventListener("message",function(t){var m=t.source;m!==window&&null!== +m||"process-tick"!==t.data||(t.stopPropagation(),0p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0=f)throw Error("Expected more digits in base 64 VLQ value.");var q=e.decode(p.charCodeAt(t++));if(-1===q)throw Error("Invalid base64 digit: "+p.charAt(t-1));var r=!!(q&32);q&=31;c+=q<>1;m.value=1===(c&1)?-p:p;m.rest=t}},{"./base64":12}],12:[function(C, +J,A){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");A.encode=function(p){if(0<=p&&p=p?p-65:97<=p&&122>=p?p-97+26:48<=p&&57>=p?p-48+52:43==p?62:47==p?63:-1}},{}],13:[function(C,J,A){function e(p,t,m,f,c,l){var q=Math.floor((t-p)/2)+p,r=c(m,f[q],!0);return 0===r?q:0p?-1:p}A.GREATEST_LOWER_BOUND=1;A.LEAST_UPPER_BOUND=2;A.search=function(p,t,m,f){if(0===t.length)return-1;p=e(-1,t.length,p,t,m,f||A.GREATEST_LOWER_BOUND);if(0>p)return-1;for(;0<=p-1&&0===m(t[p],t[p-1],!0);)--p;return p}},{}],14:[function(C,J,A){function e(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var p=C("./util");e.prototype.unsortedForEach=function(t,m){this._array.forEach(t,m)};e.prototype.add=function(t){var m=this._last,f=m.generatedLine, +c=t.generatedLine,l=m.generatedColumn,q=t.generatedColumn;c>f||c==f&&q>=l||0>=p.compareByGeneratedPositionsInflated(m,t)?this._last=t:this._sorted=!1;this._array.push(t)};e.prototype.toArray=function(){this._sorted||(this._array.sort(p.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};A.MappingList=e},{"./util":19}],15:[function(C,J,A){function e(t,m,f){var c=t[m];t[m]=t[f];t[f]=c}function p(t,m,f,c){if(f=m(t[r],q)&&(l+=1,e(t,l,r));e(t,l+1,r);l+=1;p(t,m,f,l-1);p(t,m,l+1,c)}}A.quickSort=function(t,m){p(t,m,0,t.length-1)}},{}],16:[function(C,J,A){function e(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));return null!=d.sections?new m(d,u):new p(d,u)}function p(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version"),n=f.getArg(d,"sources"),v=f.getArg(d,"names",[]),z=f.getArg(d,"sourceRoot",null),G=f.getArg(d,"sourcesContent",null),D=f.getArg(d, +"mappings");d=f.getArg(d,"file",null);if(g!=this._version)throw Error("Unsupported version: "+g);z&&(z=f.normalize(z));n=n.map(String).map(f.normalize).map(function(L){return z&&f.isAbsolute(z)&&f.isAbsolute(L)?f.relative(z,L):L});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(n,!0);this.sourceRoot=z;this.sourcesContent=G;this._mappings=D;this._sourceMapURL=u;this.file=d}function t(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source= +null}function m(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version");d=f.getArg(d,"sections");if(g!=this._version)throw Error("Unsupported version: "+g);this._sources=new l;this._names=new l;var n={line:-1,column:0};this._sections=d.map(function(v){if(v.url)throw Error("Support for url field in sections not implemented.");var z=f.getArg(v,"offset"),G=f.getArg(z,"line"),D=f.getArg(z,"column");if(G=k[d])throw new TypeError("Line must be greater than or equal to 1, got "+ +k[d]);if(0>k[g])throw new TypeError("Column must be greater than or equal to 0, got "+k[g]);return c.search(k,u,n,v)};p.prototype.computeColumnSpans=function(){for(var k=0;k=this._sources.size()&&!this.sourcesContent.some(function(k){return null==k}):!1};p.prototype.sourceContentFor=function(k,u){if(!this.sourcesContent)return null;var d=k;null!=this.sourceRoot&&(d=f.relative(this.sourceRoot,d));if(this._sources.has(d))return this.sourcesContent[this._sources.indexOf(d)]; +var g=this.sources,n;for(n=0;n +g||95!==d.charCodeAt(g-1)||95!==d.charCodeAt(g-2)||111!==d.charCodeAt(g-3)||116!==d.charCodeAt(g-4)||111!==d.charCodeAt(g-5)||114!==d.charCodeAt(g-6)||112!==d.charCodeAt(g-7)||95!==d.charCodeAt(g-8)||95!==d.charCodeAt(g-9))return!1;for(g-=10;0<=g;g--)if(36!==d.charCodeAt(g))return!1;return!0}function r(d,g){return d===g?0:null===d?1:null===g?-1:d>g?1:-1}A.getArg=function(d,g,n){if(g in d)return d[g];if(3===arguments.length)return n;throw Error('"'+g+'" is a required argument.');};var k=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/, +u=/^data:.+,.+$/;A.urlParse=e;A.urlGenerate=p;A.normalize=t;A.join=m;A.isAbsolute=function(d){return"/"===d.charAt(0)||k.test(d)};A.relative=function(d,g){""===d&&(d=".");d=d.replace(/\/$/,"");for(var n=0;0!==g.indexOf(d+"/");){var v=d.lastIndexOf("/");if(0>v)return g;d=d.slice(0,v);if(d.match(/^([^\/]+:\/)?\/*$/))return g;++n}return Array(n+1).join("../")+g.substr(d.length+1)};C=!("__proto__"in Object.create(null));A.toSetString=C?f:c;A.fromSetString=C?f:l;A.compareByOriginalPositions=function(d, +g,n){var v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;if(0!==v||n)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v)return v;v=d.generatedLine-g.generatedLine;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsDeflated=function(d,g,n){var v=d.generatedLine-g.generatedLine;if(0!==v)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v||n)return v;v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine- +g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsInflated=function(d,g){var n=d.generatedLine-g.generatedLine;if(0!==n)return n;n=d.generatedColumn-g.generatedColumn;if(0!==n)return n;n=r(d.source,g.source);if(0!==n)return n;n=d.originalLine-g.originalLine;if(0!==n)return n;n=d.originalColumn-g.originalColumn;return 0!==n?n:r(d.name,g.name)};A.parseSourceMapInput=function(d){return JSON.parse(d.replace(/^\)]}'[^\n]*\n/, +""))};A.computeSourceURL=function(d,g,n){g=g||"";d&&("/"!==d[d.length-1]&&"/"!==g[0]&&(d+="/"),g=d+g);if(n){d=e(n);if(!d)throw Error("sourceMapURL could not be parsed");d.path&&(n=d.path.lastIndexOf("/"),0<=n&&(d.path=d.path.substring(0,n+1)));g=m(p(d),g)}return t(g)}},{}],20:[function(C,J,A){A.SourceMapGenerator=C("./lib/source-map-generator").SourceMapGenerator;A.SourceMapConsumer=C("./lib/source-map-consumer").SourceMapConsumer;A.SourceNode=C("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16, +"./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(C,J,A){(function(e){function p(){return"browser"===a?!0:"node"===a?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function t(x){return function(B){for(var F=0;F";B=this.getLineNumber();null!=B&&(x+=":"+B,(B= +this.getColumnNumber())&&(x+=":"+B))}B="";var F=this.getFunctionName(),E=!0,H=this.isConstructor();if(this.isToplevel()||H)H?B+="new "+(F||""):F?B+=F:(B+=x,E=!1);else{H=this.getTypeName();"[object Object]"===H&&(H="null");var M=this.getMethodName();F?(H&&0!=F.indexOf(H)&&(B+=H+"."),B+=F,M&&F.indexOf("."+M)!=F.length-M.length-1&&(B+=" [as "+M+"]")):B+=H+"."+(M||"")}E&&(B+=" ("+x+")");return B}function q(x){var B={};Object.getOwnPropertyNames(Object.getPrototypeOf(x)).forEach(function(F){B[F]= +/^(?:is|get)/.test(F)?function(){return x[F].call(x)}:x[F]});B.toString=l;return B}function r(x,B){void 0===B&&(B={nextPosition:null,curPosition:null});if(x.isNative())return B.curPosition=null,x;var F=x.getFileName()||x.getScriptNameOrSourceURL();if(F){var E=x.getLineNumber(),H=x.getColumnNumber()-1,M=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/,S=M.test;var V="object"===typeof e&&null!==e?e.version:"";M=S.call(M,V)?0:62;1===E&&H>M&&!p()&&!x.isEval()&&(H-=M);var O= +f({source:F,line:E,column:H});B.curPosition=O;x=q(x);var T=x.getFunctionName;x.getFunctionName=function(){return null==B.nextPosition?T():B.nextPosition.name||T()};x.getFileName=function(){return O.source};x.getLineNumber=function(){return O.line};x.getColumnNumber=function(){return O.column+1};x.getScriptNameOrSourceURL=function(){return O.source};return x}var Q=x.isEval()&&x.getEvalOrigin();Q&&(Q=c(Q),x=q(x),x.getEvalOrigin=function(){return Q});return x}function k(x,B){L&&(b={},h={});for(var F= +(x.name||"Error")+": "+(x.message||""),E={nextPosition:null,curPosition:null},H=[],M=B.length-1;0<=M;M--)H.push("\n at "+r(B[M],E)),E.nextPosition=E.curPosition;E.curPosition=E.nextPosition=null;return F+H.reverse().join("")}function u(x){var B=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(x.stack);if(B){x=B[1];var F=+B[2];B=+B[3];var E=b[x];if(!E&&v&&v.existsSync(x))try{E=v.readFileSync(x,"utf8")}catch(H){E=""}if(E&&(E=E.split(/(?:\r\n|\r|\n)/)[F-1]))return x+":"+F+"\n"+E+"\n"+Array(B).join(" ")+ +"^"}return null}function d(){var x=e.emit;e.emit=function(B){if("uncaughtException"===B){var F=arguments[1]&&arguments[1].stack,E=0=12" + }, + "volta": { + "node": "16.11.0", + "npm": "7.24.2" + } +} diff --git a/node_modules/@cspotcode/source-map-support/register-hook-require.d.ts b/node_modules/@cspotcode/source-map-support/register-hook-require.d.ts new file mode 100755 index 0000000..a787e69 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/register-hook-require.d.ts @@ -0,0 +1,7 @@ +// tslint:disable:no-useless-files + +// For following usage: +// import '@cspotcode/source-map-support/register-hook-require' +// Instead of: +// import sourceMapSupport from '@cspotcode/source-map-support' +// sourceMapSupport.install({hookRequire: true}) diff --git a/node_modules/@cspotcode/source-map-support/register-hook-require.js b/node_modules/@cspotcode/source-map-support/register-hook-require.js new file mode 100644 index 0000000..6bc12ab --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/register-hook-require.js @@ -0,0 +1,3 @@ +require('./').install({ + hookRequire: true +}); diff --git a/node_modules/@cspotcode/source-map-support/register.d.ts b/node_modules/@cspotcode/source-map-support/register.d.ts new file mode 100755 index 0000000..063cd7c --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/register.d.ts @@ -0,0 +1,7 @@ +// tslint:disable:no-useless-files + +// For following usage: +// import '@cspotcode/source-map-support/register' +// Instead of: +// import sourceMapSupport from '@cspotcode/source-map-support' +// sourceMapSupport.install() diff --git a/node_modules/@cspotcode/source-map-support/register.js b/node_modules/@cspotcode/source-map-support/register.js new file mode 100644 index 0000000..4f68e67 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/register.js @@ -0,0 +1 @@ +require('./').install(); diff --git a/node_modules/@cspotcode/source-map-support/source-map-support.d.ts b/node_modules/@cspotcode/source-map-support/source-map-support.d.ts new file mode 100755 index 0000000..d8cb9d8 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/source-map-support.d.ts @@ -0,0 +1,76 @@ +// Type definitions for source-map-support 0.5 +// Project: https://github.com/evanw/node-source-map-support +// Definitions by: Bart van der Schoor +// Jason Cheatham +// Alcedo Nathaniel De Guzman Jr +// Griffin Yourick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface RawSourceMap { + version: 3; + sources: string[]; + names: string[]; + sourceRoot?: string; + sourcesContent?: string[]; + mappings: string; + file: string; +} + +/** + * Output of retrieveSourceMap(). + * From source-map-support: + * The map field may be either a string or the parsed JSON object (i.e., + * it must be a valid argument to the SourceMapConsumer constructor). + */ +export interface UrlAndMap { + url: string; + map: string | RawSourceMap; +} + +/** + * Options to install(). + */ +export interface Options { + handleUncaughtExceptions?: boolean | undefined; + hookRequire?: boolean | undefined; + emptyCacheBetweenOperations?: boolean | undefined; + environment?: 'auto' | 'browser' | 'node' | undefined; + overrideRetrieveFile?: boolean | undefined; + overrideRetrieveSourceMap?: boolean | undefined; + retrieveFile?(path: string): string; + retrieveSourceMap?(source: string): UrlAndMap | null; + /** + * Set false to disable redirection of require / import `source-map-support` to `@cspotcode/source-map-support` + */ + redirectConflictingLibrary?: boolean; + /** + * Callback will be called every time we redirect due to `redirectConflictingLibrary` + * This allows consumers to log helpful warnings if they choose. + * @param parent NodeJS.Module which made the require() or require.resolve() call + * @param options options object internally passed to node's `_resolveFilename` hook + */ + onConflictingLibraryRedirect?: (request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void; +} + +export interface Position { + source: string; + line: number; + column: number; +} + +export function wrapCallSite(frame: any /* StackFrame */): any /* StackFrame */; +export function getErrorSource(error: Error): string | null; +export function mapSourcePosition(position: Position): Position; +export function retrieveSourceMap(source: string): UrlAndMap | null; +export function resetRetrieveHandlers(): void; + +/** + * Install SourceMap support. + * @param options Can be used to e.g. disable uncaughtException handler. + */ +export function install(options?: Options): void; + +/** + * Uninstall SourceMap support. + */ +export function uninstall(): void; diff --git a/node_modules/@cspotcode/source-map-support/source-map-support.js b/node_modules/@cspotcode/source-map-support/source-map-support.js new file mode 100644 index 0000000..ad830b6 --- /dev/null +++ b/node_modules/@cspotcode/source-map-support/source-map-support.js @@ -0,0 +1,938 @@ +const { TraceMap, originalPositionFor, AnyMap } = require('@jridgewell/trace-mapping'); +var path = require('path'); +const { fileURLToPath, pathToFileURL } = require('url'); +var util = require('util'); + +var fs; +try { + fs = require('fs'); + if (!fs.existsSync || !fs.readFileSync) { + // fs doesn't have all methods we need + fs = null; + } +} catch (err) { + /* nop */ +} + +/** + * Requires a module which is protected against bundler minification. + * + * @param {NodeModule} mod + * @param {string} request + */ +function dynamicRequire(mod, request) { + return mod.require(request); +} + +/** + * @typedef {{ + * enabled: boolean; + * originalValue: any; + * installedValue: any; + * }} HookState + * Used for installing and uninstalling hooks + */ + +// Increment this if the format of sharedData changes in a breaking way. +var sharedDataVersion = 1; + +/** + * @template T + * @param {T} defaults + * @returns {T} + */ +function initializeSharedData(defaults) { + var sharedDataKey = 'source-map-support/sharedData'; + if (typeof Symbol !== 'undefined') { + sharedDataKey = Symbol.for(sharedDataKey); + } + var sharedData = this[sharedDataKey]; + if (!sharedData) { + sharedData = { version: sharedDataVersion }; + if (Object.defineProperty) { + Object.defineProperty(this, sharedDataKey, { value: sharedData }); + } else { + this[sharedDataKey] = sharedData; + } + } + if (sharedDataVersion !== sharedData.version) { + throw new Error("Multiple incompatible instances of source-map-support were loaded"); + } + for (var key in defaults) { + if (!(key in sharedData)) { + sharedData[key] = defaults[key]; + } + } + return sharedData; +} + +// If multiple instances of source-map-support are loaded into the same +// context, they shouldn't overwrite each other. By storing handlers, caches, +// and other state on a shared object, different instances of +// source-map-support can work together in a limited way. This does require +// that future versions of source-map-support continue to support the fields on +// this object. If this internal contract ever needs to be broken, increment +// sharedDataVersion. (This version number is not the same as any of the +// package's version numbers, which should reflect the *external* API of +// source-map-support.) +var sharedData = initializeSharedData({ + + // Only install once if called multiple times + // Remember how the environment looked before installation so we can restore if able + /** @type {HookState} */ + errorPrepareStackTraceHook: undefined, + /** @type {HookState} */ + processEmitHook: undefined, + /** @type {HookState} */ + moduleResolveFilenameHook: undefined, + + /** @type {Array<(request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void>} */ + onConflictingLibraryRedirectArr: [], + + // If true, the caches are reset before a stack trace formatting operation + emptyCacheBetweenOperations: false, + + // Maps a file path to a string containing the file contents + fileContentsCache: Object.create(null), + + // Maps a file path to a source map for that file + /** @type {Record C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + const key = getCacheKey(path); + if(hasFileContentsCacheFromKey(key)) { + return getFileContentsCacheFromKey(key); + } + + var contents = ''; + try { + if (!fs) { + // Use SJAX if we are in the browser + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, /** async */ false); + xhr.send(null); + if (xhr.readyState === 4 && xhr.status === 200) { + contents = xhr.responseText; + } + } else if (fs.existsSync(path)) { + // Otherwise, use the filesystem + contents = fs.readFileSync(path, 'utf8'); + } + } catch (er) { + /* ignore any errors */ + } + + return setFileContentsCache(path, contents); +}); + +// Support URLs relative to a directory, but be careful about a protocol prefix +// in case we are in the browser (i.e. directories may start with "http://" or "file:///") +function supportRelativeURL(file, url) { + if(!file) return url; + // given that this happens within error formatting codepath, probably best to + // fallback instead of throwing if anything goes wrong + try { + // if should output a URL + if(isAbsoluteUrl(file) || isSchemeRelativeUrl(file)) { + if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) { + return new URL(url, file).toString(); + } + if(path.isAbsolute(url)) { + return new URL(pathToFileURL(url), file).toString(); + } + // url is relative path or URL + return new URL(url.replace(/\\/g, '/'), file).toString(); + } + // if should output a path (unless URL is something like https://) + if(path.isAbsolute(file)) { + if(isFileUrl(url)) { + return fileURLToPath(url); + } + if(isSchemeRelativeUrl(url)) { + return fileURLToPath(new URL(url, 'file://')); + } + if(isAbsoluteUrl(url)) { + // url is a non-file URL + // Go with the URL + return url; + } + if(path.isAbsolute(url)) { + // Normalize at all? decodeURI or normalize slashes? + return path.normalize(url); + } + // url is relative path or URL + return path.join(file, '..', decodeURI(url)); + } + // If we get here, file is relative. + // Shouldn't happen since node identifies modules with absolute paths or URLs. + // But we can take a stab at returning something meaningful anyway. + if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) { + return url; + } + return path.join(file, '..', url); + } catch(e) { + return url; + } +} + +// Return pathOrUrl in the same style as matchStyleOf: either a file URL or a native path +function matchStyleOfPathOrUrl(matchStyleOf, pathOrUrl) { + try { + if(isAbsoluteUrl(matchStyleOf) || isSchemeRelativeUrl(matchStyleOf)) { + if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) return pathOrUrl; + if(path.isAbsolute(pathOrUrl)) return pathToFileURL(pathOrUrl).toString(); + } else if(path.isAbsolute(matchStyleOf)) { + if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) { + return fileURLToPath(new URL(pathOrUrl, 'file://')); + } + } + return pathOrUrl; + } catch(e) { + return pathOrUrl; + } +} + +function retrieveSourceMapURL(source) { + var fileData; + + if (isInBrowser()) { + try { + var xhr = new XMLHttpRequest(); + xhr.open('GET', source, false); + xhr.send(null); + fileData = xhr.readyState === 4 ? xhr.responseText : null; + + // Support providing a sourceMappingURL via the SourceMap header + var sourceMapHeader = xhr.getResponseHeader("SourceMap") || + xhr.getResponseHeader("X-SourceMap"); + if (sourceMapHeader) { + return sourceMapHeader; + } + } catch (e) { + } + } + + // Get the URL of the source map + fileData = retrieveFile(tryFileURLToPath(source)); + var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; +}; + +// Can be overridden by the retrieveSourceMap option to install. Takes a +// generated source filename; returns a {map, optional url} object, or null if +// there is no source map. The map field may be either a string or the parsed +// JSON object (ie, it must be a valid argument to the SourceMapConsumer +// constructor). +/** @type {(source: string) => import('./source-map-support').UrlAndMap | null} */ +var retrieveSourceMap = handlerExec(sharedData.retrieveMapHandlers, sharedData.internalRetrieveMapHandlers); +sharedData.internalRetrieveMapHandlers.push(function(source) { + var sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) return null; + + // Read the contents of the source map + var sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + // Support source map URL as a data url + var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); + sourceMapData = Buffer.from(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(tryFileURLToPath(sourceMappingURL)); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = getSourceMapCache(position.source); + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = setSourceMapCache(position.source, { + url: urlAndMap.url, + map: new AnyMap(urlAndMap.map, urlAndMap.url) + }); + + // Overwrite trace-mapping's resolutions, because they do not handle + // Windows paths the way we want. + // TODO Remove now that windows path support was added to resolve-uri and thus trace-mapping? + sourceMap.map.resolvedSources = sourceMap.map.sources.map(s => supportRelativeURL(sourceMap.url, s)); + + // Load all sources stored inline with the source map into the file cache + // to pretend like they are already loaded. They may not exist on disk. + if (sourceMap.map.sourcesContent) { + sourceMap.map.resolvedSources.forEach(function(resolvedSource, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + setFileContentsCache(resolvedSource, contents); + } + }); + } + } else { + sourceMap = setSourceMapCache(position.source, { + url: null, + map: null + }); + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map) { + var originalPosition = originalPositionFor(sourceMap.map, position); + + // Only return the original position if a matching line was found. If no + // matching line is found then we return position instead, which will cause + // the stack trace to print the path and line for the compiled file. It is + // better to give a precise location in the compiled file than a vague + // location in the original file. + if (originalPosition.source !== null) { + // originalPosition.source has *already* been resolved against sourceMap.url + // so is *already* as absolute as possible. + // However, we want to ensure we output in same format as input: URL or native path + originalPosition.source = matchStyleOfPathOrUrl( + position.source, originalPosition.source); + return originalPosition; + } + } + + return position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition({ + source: match[2], + line: +match[3], + column: match[4] - 1 + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + (position.column + 1) + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +// This is copied almost verbatim from the V8 source code at +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +// Update 2022-04-29: +// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/builtins/builtins-callsite.cc#L175-L179 +// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L795-L804 +// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L717-L750 +// The implementation of wrapCallSite() used to just forward to the actual source +// code of CallSite.prototype.toString but unfortunately a new release of V8 +// did something to the prototype chain and broke the shim. The only fix I +// could find was copy/paste. +function CallSiteToString() { + var fileName; + var fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; // Expecting source position to follow. + } + + if (fileName) { + fileLocation += fileName; + } else { + // Source code does not originate from a file and is not native, but we + // can still get the source position inside the source string, e.g. in + // an eval string. + fileLocation += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + var isAsync = this.isAsync ? this.isAsync() : false; + if(isAsync) { + line += 'async '; + var isPromiseAll = this.isPromiseAll ? this.isPromiseAll() : false; + var isPromiseAny = this.isPromiseAny ? this.isPromiseAny() : false; + if(isPromiseAny || isPromiseAll) { + line += isPromiseAll ? 'Promise.all (index ' : 'Promise.any (index '; + var promiseIndex = this.getPromiseIndex(); + line += promiseIndex + ')'; + } + } + var functionName = this.getFunctionName(); + var addSuffix = true; + var isConstructor = this.isConstructor(); + var isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + var typeName = this.getTypeName(); + // Fixes shim to be backward compatable with Node v0 to v4 + if (typeName === "[object Object]") { + typeName = "null"; + } + var methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) != 0) { + line += typeName + "."; + } + line += functionName; + if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { + line += " [as " + methodName + "]"; + } + } else { + line += typeName + "." + (methodName || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) { + line += " (" + fileLocation + ")"; + } + return line; +} + +function cloneCallSite(frame) { + var object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { + object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; + }); + object.toString = CallSiteToString; + return object; +} + +function wrapCallSite(frame, state) { + // provides interface backward compatibility + if (state === undefined) { + state = { nextPosition: null, curPosition: null } + } + if(frame.isNative()) { + state.curPosition = null; + return frame; + } + + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//# sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + // v8 does not expose its internal isWasm, etc methods, so we do this instead. + if(source.startsWith('wasm://')) { + state.curPosition = null; + return frame; + } + + var line = frame.getLineNumber(); + var column = frame.getColumnNumber() - 1; + + // Fix position in Node where some (internal) code is prepended. + // See https://github.com/evanw/node-source-map-support/issues/36 + // Header removed in node at ^10.16 || >=11.11.0 + // v11 is not an LTS candidate, we can just test the one version with it. + // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11 + var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; + var headerLength = noHeader.test(process.version) ? 0 : 62; + if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { + column -= headerLength; + } + + var position = mapSourcePosition({ + source: source, + line: line, + column: column + }); + state.curPosition = position; + frame = cloneCallSite(frame); + var originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { + if (state.nextPosition == null) { + return originalFunctionName(); + } + return state.nextPosition.name || originalFunctionName(); + }; + frame.getFileName = function() { return position.source; }; + frame.getLineNumber = function() { return position.line; }; + frame.getColumnNumber = function() { return position.column + 1; }; + frame.getScriptNameOrSourceURL = function() { return position.source; }; + return frame; + } + + // Code called using eval() needs special handling + var origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { return origin; }; + return frame; + } + + // If we get here then we were unable to change the source position + return frame; +} + +var kIsNodeError = undefined; +try { + // Get a deliberate ERR_INVALID_ARG_TYPE + // TODO is there a better way to reliably get an instance of NodeError? + path.resolve(123); +} catch(e) { + const symbols = Object.getOwnPropertySymbols(e); + const symbol = symbols.find(function (s) {return s.toString().indexOf('kIsNodeError') >= 0}); + if(symbol) kIsNodeError = symbol; +} + +const ErrorPrototypeToString = (err) =>Error.prototype.toString.call(err); + +/** @param {HookState} hookState */ +function createPrepareStackTrace(hookState) { + return prepareStackTrace; + + // This function is part of the V8 stack trace API, for more info see: + // https://v8.dev/docs/stack-trace-api + function prepareStackTrace(error, stack) { + if(!hookState.enabled) return hookState.originalValue.apply(this, arguments); + + if (sharedData.emptyCacheBetweenOperations) { + clearCaches(); + } + + // node gives its own errors special treatment. Mimic that behavior + // https://github.com/nodejs/node/blob/3cbaabc4622df1b4009b9d026a1a970bdbae6e89/lib/internal/errors.js#L118-L128 + // https://github.com/nodejs/node/pull/39182 + var errorString; + if (kIsNodeError) { + if(kIsNodeError in error) { + errorString = `${error.name} [${error.code}]: ${error.message}`; + } else { + errorString = ErrorPrototypeToString(error); + } + } else { + var name = error.name || 'Error'; + var message = error.message || ''; + errorString = message ? name + ": " + message : name; + } + + var state = { nextPosition: null, curPosition: null }; + var processedStack = []; + for (var i = stack.length - 1; i >= 0; i--) { + processedStack.push('\n at ' + wrapCallSite(stack[i], state)); + state.nextPosition = state.curPosition; + } + state.curPosition = state.nextPosition = null; + return errorString + processedStack.reverse().join(''); + } +} + +// Generate position and snippet of original source with pointer +function getErrorSource(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var source = match[1]; + var line = +match[2]; + var column = +match[3]; + + // Support the inline sourceContents inside the source map + var contents = getFileContentsCache(source); + + const sourceAsPath = tryFileURLToPath(source); + + // Support files on disk + if (!contents && fs && fs.existsSync(sourceAsPath)) { + try { + contents = fs.readFileSync(sourceAsPath, 'utf8'); + } catch (er) { + contents = ''; + } + } + + // Format the line from the original source code like node does + if (contents) { + var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; + if (code) { + return source + ':' + line + '\n' + code + '\n' + + new Array(column).join(' ') + '^'; + } + } + } + return null; +} + +function printFatalErrorUponExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + if (process.stderr._handle && process.stderr._handle.setBlocking) { + process.stderr._handle.setBlocking(true); + } + + if (source) { + console.error(source); + } + + // Matches node's behavior for colorized output + console.error( + util.inspect(error, { + customInspect: false, + colors: process.stderr.isTTY + }) + ); +} + +function shimEmitUncaughtException () { + const originalValue = process.emit; + var hook = sharedData.processEmitHook = { + enabled: true, + originalValue, + installedValue: undefined + }; + var isTerminatingDueToFatalException = false; + var fatalException; + + process.emit = sharedData.processEmitHook.installedValue = function (type) { + const hadListeners = originalValue.apply(this, arguments); + if(hook.enabled) { + if (type === 'uncaughtException' && !hadListeners) { + isTerminatingDueToFatalException = true; + fatalException = arguments[1]; + process.exit(1); + } + if (type === 'exit' && isTerminatingDueToFatalException) { + printFatalErrorUponExit(fatalException); + } + } + return hadListeners; + }; +} + +var originalRetrieveFileHandlers = sharedData.retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = sharedData.retrieveMapHandlers.slice(0); + +exports.wrapCallSite = wrapCallSite; +exports.getErrorSource = getErrorSource; +exports.mapSourcePosition = mapSourcePosition; +exports.retrieveSourceMap = retrieveSourceMap; + +exports.install = function(options) { + options = options || {}; + + if (options.environment) { + environment = options.environment; + if (["node", "browser", "auto"].indexOf(environment) === -1) { + throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") + } + } + + // Use dynamicRequire to avoid including in browser bundles + var Module = dynamicRequire(module, 'module'); + + // Redirect subsequent imports of "source-map-support" + // to this package + const {redirectConflictingLibrary = true, onConflictingLibraryRedirect} = options; + if(redirectConflictingLibrary) { + if (!sharedData.moduleResolveFilenameHook) { + const originalValue = Module._resolveFilename; + const moduleResolveFilenameHook = sharedData.moduleResolveFilenameHook = { + enabled: true, + originalValue, + installedValue: undefined, + } + Module._resolveFilename = sharedData.moduleResolveFilenameHook.installedValue = function (request, parent, isMain, options) { + if (moduleResolveFilenameHook.enabled) { + // Match all source-map-support entrypoints: source-map-support, source-map-support/register + let requestRedirect; + if (request === 'source-map-support') { + requestRedirect = './'; + } else if (request === 'source-map-support/register') { + requestRedirect = './register'; + } + + if (requestRedirect !== undefined) { + const newRequest = require.resolve(requestRedirect); + for (const cb of sharedData.onConflictingLibraryRedirectArr) { + cb(request, parent, isMain, options, newRequest); + } + request = newRequest; + } + } + + return originalValue.call(this, request, parent, isMain, options); + } + } + if (onConflictingLibraryRedirect) { + sharedData.onConflictingLibraryRedirectArr.push(onConflictingLibraryRedirect); + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + sharedData.retrieveFileHandlers.length = 0; + } + + sharedData.retrieveFileHandlers.unshift(options.retrieveFile); + } + + // Allow source maps to be found by methods other than reading the files + // directly from disk. + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) { + sharedData.retrieveMapHandlers.length = 0; + } + + sharedData.retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + setFileContentsCache(filename, content); + setSourceMapCache(filename, undefined); + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!sharedData.emptyCacheBetweenOperations) { + sharedData.emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + + // Install the error reformatter + if (!sharedData.errorPrepareStackTraceHook) { + const originalValue = Error.prepareStackTrace; + sharedData.errorPrepareStackTraceHook = { + enabled: true, + originalValue, + installedValue: undefined + }; + Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.installedValue = createPrepareStackTrace(sharedData.errorPrepareStackTraceHook); + } + + if (!sharedData.processEmitHook) { + var installHandler = 'handleUncaughtExceptions' in options ? + options.handleUncaughtExceptions : true; + + // Do not override 'uncaughtException' with our own handler in Node.js + // Worker threads. Workers pass the error to the main thread as an event, + // rather than printing something to stderr and exiting. + try { + // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify. + var worker_threads = dynamicRequire(module, 'worker_threads'); + if (worker_threads.isMainThread === false) { + installHandler = false; + } + } catch(e) {} + + // Provide the option to not install the uncaught exception handler. This is + // to support other uncaught exception handlers (in test frameworks, for + // example). If this handler is not installed and there are no other uncaught + // exception handlers, uncaught exceptions will be caught by node's built-in + // exception handler and the process will still be terminated. However, the + // generated JavaScript code will be shown above the stack trace instead of + // the original source code. + if (installHandler && hasGlobalProcessEventEmitter()) { + shimEmitUncaughtException(); + } + } +}; + +exports.uninstall = function() { + if(sharedData.processEmitHook) { + // Disable behavior + sharedData.processEmitHook.enabled = false; + // If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us. + if(process.emit === sharedData.processEmitHook.installedValue) { + process.emit = sharedData.processEmitHook.originalValue; + } + sharedData.processEmitHook = undefined; + } + if(sharedData.errorPrepareStackTraceHook) { + // Disable behavior + sharedData.errorPrepareStackTraceHook.enabled = false; + // If possible or necessary, remove our hook function. + // In vanilla environments, prepareStackTrace is `undefined`. + // We cannot delegate to `undefined` the way we can to a function w/`.apply()`; our only option is to remove the function. + // If we are the *first* hook installed, and another was installed on top of us, we have no choice but to remove both. + if(Error.prepareStackTrace === sharedData.errorPrepareStackTraceHook.installedValue || typeof sharedData.errorPrepareStackTraceHook.originalValue !== 'function') { + Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.originalValue; + } + sharedData.errorPrepareStackTraceHook = undefined; + } + if (sharedData.moduleResolveFilenameHook) { + // Disable behavior + sharedData.moduleResolveFilenameHook.enabled = false; + // If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us. + var Module = dynamicRequire(module, 'module'); + if(Module._resolveFilename === sharedData.moduleResolveFilenameHook.installedValue) { + Module._resolveFilename = sharedData.moduleResolveFilenameHook.originalValue; + } + sharedData.moduleResolveFilenameHook = undefined; + } + sharedData.onConflictingLibraryRedirectArr.length = 0; +} + +exports.resetRetrieveHandlers = function() { + sharedData.retrieveFileHandlers.length = 0; + sharedData.retrieveMapHandlers.length = 0; +} diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/Buffer.js b/node_modules/@esbuild-plugins/node-globals-polyfill/Buffer.js new file mode 100644 index 0000000..a857959 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/Buffer.js @@ -0,0 +1,2168 @@ +// taken from https://github.com/calvinmetcalf/buffer-es6 + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array +var inited = false +function init() { + inited = true + var code = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i + } + + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 +} + +function base64toByteArray(b64) { + if (!inited) { + init() + } + var i, j, l, tmp, placeHolders, arr + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr((len * 3) / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xff + arr[L++] = (tmp >> 8) & 0xff + arr[L++] = tmp & 0xff + } + + if (placeHolders === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xff + } else if (placeHolders === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xff + arr[L++] = tmp & 0xff + } + + return arr +} + +function tripletToBase64(num) { + return ( + lookup[(num >> 18) & 0x3f] + + lookup[(num >> 12) & 0x3f] + + lookup[(num >> 6) & 0x3f] + + lookup[num & 0x3f] + ) +} + +function encodeChunk(uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2] + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function base64fromByteArray(uint8) { + if (!inited) { + init() + } + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push( + encodeChunk( + uint8, + i, + i + maxChunkLength > len2 ? len2 : i + maxChunkLength, + ), + ) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3f] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3f] + output += lookup[(tmp << 2) & 0x3f] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +var INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = + global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : true + +function kMaxLength() { + return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff +} + +function createBuffer(that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +export function Buffer(arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string', + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function(arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from(that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function(value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +Buffer.kMaxLength = kMaxLength() + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if ( + typeof Symbol !== 'undefined' && + Symbol.species && + Buffer[Symbol.species] === Buffer + ) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + // Object.defineProperty(Buffer, Symbol.species, { + // value: null, + // configurable: true + // }) + } +} + +function assertSize(size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc(that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function(size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe(that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function(size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function(size) { + return allocUnsafe(null, size) +} + +function fromString(that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike(that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer(that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError("'offset' is out of bounds") + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError("'length' is out of bounds") + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject(that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ( + (typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || + 'length' in obj + ) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError( + 'First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.', + ) +} + +function checked(length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError( + 'Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + + kMaxLength().toString(16) + + ' bytes', + ) + } + return length | 0 +} + +export function SlowBuffer(length) { + if (+length != length) { + // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} +Buffer.isBuffer = isBuffer +function internalIsBuffer(b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare(a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength(string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if ( + typeof ArrayBuffer !== 'undefined' && + typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer) + ) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString(encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) + throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap(b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16() { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32() { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64() { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString() { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals(b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + + +Buffer.prototype.compare = function compare( + target, + start, + end, + thisStart, + thisEnd, +) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if ( + start < 0 || + end > target.length || + thisStart < 0 || + thisEnd > this.length + ) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1 + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xff // Search for a byte value [0-255] + if ( + Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function' + ) { + if (dir) { + return Uint8Array.prototype.indexOf.call( + buffer, + val, + byteOffset, + ) + } else { + return Uint8Array.prototype.lastIndexOf.call( + buffer, + val, + byteOffset, + ) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if ( + encoding === 'ucs2' || + encoding === 'ucs-2' || + encoding === 'utf16le' || + encoding === 'utf-16le' + ) { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read(buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if ( + read(arr, i) === + read(val, foundIndex === -1 ? 0 : i - foundIndex) + ) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) + return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) + byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write(buf, string, offset, length) { + return blitBuffer( + utf8ToBytes(string, buf.length - offset), + buf, + offset, + length, + ) +} + +function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write(buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write(buf, string, offset, length) { + return blitBuffer( + utf16leToBytes(string, buf.length - offset), + buf, + offset, + length, + ) +} + +Buffer.prototype.write = function write(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported', + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ( + (string.length > 0 && (length < 0 || offset < 0)) || + offset > this.length + ) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) + throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON() { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0), + } +} + +function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64fromByteArray(buf) + } else { + return base64fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = + firstByte > 0xef + ? 4 + : firstByte > 0xdf + ? 3 + : firstByte > 0xbf + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xc0) === 0x80) { + tempCodePoint = + ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f) + if (tempCodePoint > 0x7f) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ( + (secondByte & 0xc0) === 0x80 && + (thirdByte & 0xc0) === 0x80 + ) { + tempCodePoint = + ((firstByte & 0xf) << 0xc) | + ((secondByte & 0x3f) << 0x6) | + (thirdByte & 0x3f) + if ( + tempCodePoint > 0x7ff && + (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff) + ) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ( + (secondByte & 0xc0) === 0x80 && + (thirdByte & 0xc0) === 0x80 && + (fourthByte & 0xc0) === 0x80 + ) { + tempCodePoint = + ((firstByte & 0xf) << 0x12) | + ((secondByte & 0x3f) << 0xc) | + ((thirdByte & 0x3f) << 0x6) | + (fourthByte & 0x3f) + if ( + tempCodePoint > 0xffff && + tempCodePoint < 0x110000 + ) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xfffd + bytesPerSequence = 1 + } else if (codePoint > 0xffff) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(((codePoint >>> 10) & 0x3ff) | 0xd800) + codePoint = 0xdc00 | (codePoint & 0x3ff) + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray(codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH)), + ) + } + return res +} + +function asciiSlice(buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7f) + } + return ret +} + +function latin1Slice(buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice(buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice(start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) + throw new RangeError('offset is not uint') + if (offset + ext > length) + throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE( + offset, + byteLength, + noAssert, +) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE( + offset, + byteLength, + noAssert, +) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ( + (this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + + this[offset + 3] * 0x1000000 + ) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ( + this[offset] * 0x1000000 + + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) + ) +} + +Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return this[offset] + return (0xff - this[offset] + 1) * -1 +} + +Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return val & 0x8000 ? val | 0xffff0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return val & 0x8000 ? val | 0xffff0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ( + this[offset] | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + ) +} + +Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ( + (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3] + ) +} + +Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754read(this, offset, false, 52, 8) +} + +function checkInt(buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) + throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) + throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE( + value, + offset, + byteLength, + noAssert, +) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xff + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE( + value, + offset, + byteLength, + noAssert, +) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xff + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = value & 0xff + return offset + 1 +} + +function objectWriteUInt16(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = + (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + ((littleEndian ? i : 1 - i) * 8) + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE( + value, + offset, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff + this[offset + 1] = value >>> 8 + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE( + value, + offset, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8 + this[offset + 1] = value & 0xff + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> ((littleEndian ? i : 3 - i) * 8)) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE( + value, + offset, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = value >>> 24 + this[offset + 2] = value >>> 16 + this[offset + 1] = value >>> 8 + this[offset] = value & 0xff + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE( + value, + offset, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24 + this[offset + 1] = value >>> 16 + this[offset + 2] = value >>> 8 + this[offset + 3] = value & 0xff + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE( + value, + offset, + byteLength, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xff + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE( + value, + offset, + byteLength, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xff + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = value & 0xff + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff + this[offset + 1] = value >>> 8 + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8 + this[offset + 1] = value & 0xff + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff + this[offset + 1] = value >>> 8 + this[offset + 2] = value >>> 16 + this[offset + 3] = value >>> 24 + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24 + this[offset + 1] = value >>> 16 + this[offset + 2] = value >>> 8 + this[offset + 3] = value & 0xff + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754( + buf, + value, + offset, + 4, + 3.4028234663852886e38, + -3.4028234663852886e38, + ) + } + ieee754write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754( + buf, + value, + offset, + 8, + 1.7976931348623157e308, + -1.7976931348623157e308, + ) + } + ieee754write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE( + value, + offset, + noAssert, +) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE( + value, + offset, + noAssert, +) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) + throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart, + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean(str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim(str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex(n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes(string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xd7ff && codePoint < 0xe000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xdbff) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xdc00) { + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = + (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push((codePoint >> 0x6) | 0xc0, (codePoint & 0x3f) | 0x80) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + (codePoint >> 0xc) | 0xe0, + ((codePoint >> 0x6) & 0x3f) | 0x80, + (codePoint & 0x3f) | 0x80, + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + (codePoint >> 0x12) | 0xf0, + ((codePoint >> 0xc) & 0x3f) | 0x80, + ((codePoint >> 0x6) & 0x3f) | 0x80, + (codePoint & 0x3f) | 0x80, + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes(str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xff) + } + return byteArray +} + +function utf16leToBytes(str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes(str) { + return base64toByteArray(base64clean(str)) +} + +function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break + dst[i + offset] = src[i] + } + return i +} + +function isnan(val) { + return val !== val // eslint-disable-line no-self-compare +} + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer(obj) { + return ( + obj != null && + (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + ) +} + +function isFastBuffer(obj) { + return ( + !!obj.constructor && + typeof obj.constructor.isBuffer === 'function' && + obj.constructor.isBuffer(obj) + ) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer(obj) { + return ( + typeof obj.readFloatLE === 'function' && + typeof obj.slice === 'function' && + isFastBuffer(obj.slice(0, 0)) + ) +} + +function ieee754read(buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? nBytes - 1 : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << -nBits) - 1) + s >>= -nBits + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << -nBits) - 1) + e >>= -nBits + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function ieee754write(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0 + var i = isLE ? 0 : nBytes - 1 + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for ( + ; + mLen >= 8; + buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8 + ) {} + + e = (e << mLen) | m + eLen += mLen + for ( + ; + eLen > 0; + buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8 + ) {} + + buffer[offset + i - d] |= s * 128 +} diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/_buffer.js b/node_modules/@esbuild-plugins/node-globals-polyfill/_buffer.js new file mode 100644 index 0000000..66103f8 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/_buffer.js @@ -0,0 +1 @@ +export { Buffer } from '_node-buffer-polyfill_.js' diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/_process.js b/node_modules/@esbuild-plugins/node-globals-polyfill/_process.js new file mode 100644 index 0000000..e9d08e8 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/_process.js @@ -0,0 +1 @@ +export { process } from '_node-process-polyfill_.js' diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts new file mode 100644 index 0000000..2f1104e --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts @@ -0,0 +1,7 @@ +import * as esbuild from 'esbuild'; +export declare function NodeGlobalsPolyfillPlugin({ buffer, process, }?: { + buffer?: boolean | undefined; + process?: boolean | undefined; +}): esbuild.Plugin; +export default NodeGlobalsPolyfillPlugin; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts.map b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts.map new file mode 100644 index 0000000..2d38864 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAElC,wBAAgB,yBAAyB,CAAC,EACtC,MAAc,EAEd,OAAc,GACjB;;;CAAK,GAAG,OAAO,CAAC,MAAM,CAyEtB;AAED,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js new file mode 100644 index 0000000..1bd8fb8 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js @@ -0,0 +1,80 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NodeGlobalsPolyfillPlugin = void 0; +const path_1 = __importDefault(require("path")); +function NodeGlobalsPolyfillPlugin({ buffer = false, +// define = {}, +process = true, } = {}) { + return { + name: 'node-globals-polyfill', + setup({ initialOptions, onResolve, onLoad }) { + onResolve({ filter: /_node-buffer-polyfill_\.js/ }, (arg) => { + return { + path: path_1.default.resolve(__dirname, '../Buffer.js'), + }; + }); + onResolve({ filter: /_node-process-polyfill_\.js/ }, (arg) => { + return { + path: path_1.default.resolve(__dirname, '../process.js'), + }; + }); + // TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 + // onLoad({ filter: /_virtual-process-polyfill_\.js/ }, (arg) => { + // const data = fs + // .readFileSync(path.resolve(__dirname, '../process.js')) + // .toString() + // const keys = Object.keys(define) + // return { + // loader: 'js', + // contents: data.replace( + // `const defines = {}`, + // 'const defines = {\n' + + // keys + // .filter((x) => x.startsWith('process.')) + // .sort((a, b) => a.length - b.length) + // .map( + // (k) => + // ` ${JSON.stringify(k).replace( + // 'process.', + // '', + // )}: ${define[k]},`, + // ) + // .join('\n') + + // '\n}', + // ), + // } + // }) + onResolve({ filter: /_virtual-process-polyfill_\.js/ }, () => { + return { + path: path_1.default.resolve(__dirname, '../process.js'), + }; + }); + onResolve({ filter: /_virtual-buffer-polyfill_\.js/ }, () => { + return { + path: path_1.default.resolve(__dirname, '../_buffer.js'), + }; + }); + const polyfills = []; + if (process) { + polyfills.push(path_1.default.resolve(__dirname, '../_virtual-process-polyfill_.js')); + } + if (buffer) { + polyfills.push(path_1.default.resolve(__dirname, '../_virtual-buffer-polyfill_.js')); + } + if (initialOptions.inject) { + initialOptions.inject.push(...polyfills); + // handle duplicate plugin + initialOptions.inject = [...new Set(initialOptions.inject)]; + } + else { + initialOptions.inject = [...polyfills]; + } + }, + }; +} +exports.NodeGlobalsPolyfillPlugin = NodeGlobalsPolyfillPlugin; +exports.default = NodeGlobalsPolyfillPlugin; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js.map b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js.map new file mode 100644 index 0000000..8f8a451 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AAIvB,SAAgB,yBAAyB,CAAC,EACtC,MAAM,GAAG,KAAK;AACd,eAAe;AACf,OAAO,GAAG,IAAI,GACjB,GAAG,EAAE;IACF,OAAO;QACH,IAAI,EAAE,uBAAuB;QAC7B,KAAK,CAAC,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,EAAE;YACvC,SAAS,CAAC,EAAE,MAAM,EAAE,4BAA4B,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE;gBACxD,OAAO;oBACH,IAAI,EAAE,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,cAAc,CAAC;iBAChD,CAAA;YACL,CAAC,CAAC,CAAA;YACF,SAAS,CAAC,EAAE,MAAM,EAAE,6BAA6B,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE;gBACzD,OAAO;oBACH,IAAI,EAAE,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,eAAe,CAAC;iBACjD,CAAA;YACL,CAAC,CAAC,CAAA;YAEF,mGAAmG;YACnG,kEAAkE;YAClE,sBAAsB;YACtB,kEAAkE;YAClE,sBAAsB;YAEtB,uCAAuC;YACvC,eAAe;YACf,wBAAwB;YACxB,kCAAkC;YAClC,oCAAoC;YACpC,sCAAsC;YACtC,uBAAuB;YACvB,+DAA+D;YAC/D,2DAA2D;YAC3D,4BAA4B;YAC5B,iCAAiC;YACjC,8DAA8D;YAC9D,8CAA8C;YAC9C,sCAAsC;YACtC,kDAAkD;YAClD,wBAAwB;YACxB,oCAAoC;YACpC,yBAAyB;YACzB,aAAa;YACb,QAAQ;YACR,KAAK;YACL,SAAS,CAAC,EAAE,MAAM,EAAE,gCAAgC,EAAE,EAAE,GAAG,EAAE;gBACzD,OAAO;oBACH,IAAI,EAAE,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,eAAe,CAAC;iBACjD,CAAA;YACL,CAAC,CAAC,CAAA;YACF,SAAS,CAAC,EAAE,MAAM,EAAE,+BAA+B,EAAE,EAAE,GAAG,EAAE;gBACxD,OAAO;oBACH,IAAI,EAAE,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,eAAe,CAAC;iBACjD,CAAA;YACL,CAAC,CAAC,CAAA;YAEF,MAAM,SAAS,GAAa,EAAE,CAAA;YAC9B,IAAI,OAAO,EAAE;gBACT,SAAS,CAAC,IAAI,CACV,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,kCAAkC,CAAC,CAC9D,CAAA;aACJ;YACD,IAAI,MAAM,EAAE;gBACR,SAAS,CAAC,IAAI,CACV,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,iCAAiC,CAAC,CAC7D,CAAA;aACJ;YACD,IAAI,cAAc,CAAC,MAAM,EAAE;gBACvB,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,CAAA;gBACxC,0BAA0B;gBAC1B,cAAc,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAA;aAC9D;iBAAM;gBACH,cAAc,CAAC,MAAM,GAAG,CAAC,GAAG,SAAS,CAAC,CAAA;aACzC;QACL,CAAC;KACJ,CAAA;AACL,CAAC;AA7ED,8DA6EC;AAED,kBAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts new file mode 100644 index 0000000..121d59b --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.test.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts.map b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts.map new file mode 100644 index 0000000..b5774e1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js new file mode 100644 index 0000000..3f9f406 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js @@ -0,0 +1,139 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const esbuild_1 = require("esbuild"); +const test_support_1 = require("test-support"); +const _1 = require("."); +require('debug').enable(require('../package.json').name); +test('process works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `process.version`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('process is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `console.log('hei')`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }); + const output = res.outputFiles[0].text; + expect(output).not.toContain('process'); + unlink(); +})); +// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 +test('process env vars are replaced with ones from define', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `if (process.env.VAR !== 'hello') { throw new Error('process.env.VAR not right: ' + process.env.VAR) }`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + define: { + 'process.env.VAR': '"hello"', + }, + plugins: [_1.NodeGlobalsPolyfillPlugin({})], + }); + const output = res.outputFiles[0].text; + eval(output); + unlink(); +})); +test('Buffer works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `console.log(Buffer.from('xxx').toString())`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('Buffer is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `console.log('hei')`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }); + const output = res.outputFiles[0].text; + expect(output).not.toContain('Buffer'); + unlink(); +})); +test('Buffer works using plugin', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': ` + let buf = new Buffer(256); + let len = buf.write("Simply Easy Learning"); + console.log("Octets written : "+ len);`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.NodeGlobalsPolyfillPlugin({ buffer: true })], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('process works using plugin', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `console.log(process.cwd())`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.NodeGlobalsPolyfillPlugin({ process: true })], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +//# sourceMappingURL=index.test.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js.map b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js.map new file mode 100644 index 0000000..cef0110 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,qCAA+B;AAC/B,+CAAyC;AACzC,wBAA6C;AAE7C,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,CAAA;AAExD,IAAI,CAAC,eAAe,EAAE,GAAS,EAAE;IAC7B,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,yBAAU,CAAC;QACjB,UAAU,EAAE,iBAAiB;KAChC,CAAC,CAAA;IACF,MAAM,GAAG,GAAG,MAAM,eAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAAK,C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AU,CAAC;QACjB,UAAU,EAAE,4BAA4B;KAC3C,CAAC,CAAA;IACF,MAAM,GAAG,GAAG,MAAM,eAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,CAAC,4BAAyB,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;KAC1D,CAAC,CAAA;IACF,MAAM,MAAM,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACtC,sBAAsB;IACtB,IAAI,CAAC,MAAM,CAAC,CAAA;IACZ,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts new file mode 100644 index 0000000..2f1104e --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts @@ -0,0 +1,7 @@ +import * as esbuild from 'esbuild'; +export declare function NodeGlobalsPolyfillPlugin({ buffer, process, }?: { + buffer?: boolean | undefined; + process?: boolean | undefined; +}): esbuild.Plugin; +export default NodeGlobalsPolyfillPlugin; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts.map b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts.map new file mode 100644 index 0000000..2d38864 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAElC,wBAAgB,yBAAyB,CAAC,EACtC,MAAc,EAEd,OAAc,GACjB;;;CAAK,GAAG,OAAO,CAAC,MAAM,CAyEtB;AAED,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js new file mode 100644 index 0000000..aa0bceb --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js @@ -0,0 +1,73 @@ +import path from 'path'; +export function NodeGlobalsPolyfillPlugin({ buffer = false, +// define = {}, +process = true, } = {}) { + return { + name: 'node-globals-polyfill', + setup({ initialOptions, onResolve, onLoad }) { + onResolve({ filter: /_node-buffer-polyfill_\.js/ }, (arg) => { + return { + path: path.resolve(__dirname, '../Buffer.js'), + }; + }); + onResolve({ filter: /_node-process-polyfill_\.js/ }, (arg) => { + return { + path: path.resolve(__dirname, '../process.js'), + }; + }); + // TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 + // onLoad({ filter: /_virtual-process-polyfill_\.js/ }, (arg) => { + // const data = fs + // .readFileSync(path.resolve(__dirname, '../process.js')) + // .toString() + // const keys = Object.keys(define) + // return { + // loader: 'js', + // contents: data.replace( + // `const defines = {}`, + // 'const defines = {\n' + + // keys + // .filter((x) => x.startsWith('process.')) + // .sort((a, b) => a.length - b.length) + // .map( + // (k) => + // ` ${JSON.stringify(k).replace( + // 'process.', + // '', + // )}: ${define[k]},`, + // ) + // .join('\n') + + // '\n}', + // ), + // } + // }) + onResolve({ filter: /_virtual-process-polyfill_\.js/ }, () => { + return { + path: path.resolve(__dirname, '../process.js'), + }; + }); + onResolve({ filter: /_virtual-buffer-polyfill_\.js/ }, () => { + return { + path: path.resolve(__dirname, '../_buffer.js'), + }; + }); + const polyfills = []; + if (process) { + polyfills.push(path.resolve(__dirname, '../_virtual-process-polyfill_.js')); + } + if (buffer) { + polyfills.push(path.resolve(__dirname, '../_virtual-buffer-polyfill_.js')); + } + if (initialOptions.inject) { + initialOptions.inject.push(...polyfills); + // handle duplicate plugin + initialOptions.inject = [...new Set(initialOptions.inject)]; + } + else { + initialOptions.inject = [...polyfills]; + } + }, + }; +} +export default NodeGlobalsPolyfillPlugin; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js.map b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js.map new file mode 100644 index 0000000..0ebb938 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAA;AAIvB,MAAM,UAAU,yBAAyB,CAAC,EACtC,MAAM,GAAG,KAAK;AACd,eAAe;AACf,OAAO,GAAG,IAAI,GACjB,GAAG,EAAE;IACF,OAAO;QACH,IAAI,EAAE,uBAAuB;QAC7B,KAAK,CAAC,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,EAAE;YACvC,SAAS,CAAC,EAAE,MAAM,EAAE,4BAA4B,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE;gBACxD,OAAO;oBACH,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,cAAc,CAAC;iBAChD,CAAA;YACL,CAAC,CAAC,CAAA;YACF,SAAS,CAAC,EAAE,MAAM,EAAE,6BAA6B,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE;gBACzD,OAAO;oBACH,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,eAAe,CAAC;iBACjD,CAAA;YACL,CAAC,CAAC,CAAA;YAEF,mGAAmG;YACnG,kEAAkE;YAClE,sBAAsB;YACtB,kEAAkE;YAClE,sBAAsB;YAEtB,uCAAuC;YACvC,eAAe;YACf,wBAAwB;YACxB,kCAAkC;YAClC,oCAAoC;YACpC,sCAAsC;YACtC,uBAAuB;YACvB,+DAA+D;YAC/D,2DAA2D;YAC3D,4BAA4B;Y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ild-plugins/node-globals-polyfill/esm/index.test.d.ts new file mode 100644 index 0000000..121d59b --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.test.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.d.ts.map b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.d.ts.map new file mode 100644 index 0000000..b5774e1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js new file mode 100644 index 0000000..c3177d5 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js @@ -0,0 +1,137 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { build } from 'esbuild'; +import { writeFiles } from 'test-support'; +import { NodeGlobalsPolyfillPlugin } from '.'; +require('debug').enable(require('../package.json').name); +test('process works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `process.version`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('process is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `console.log('hei')`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }); + const output = res.outputFiles[0].text; + expect(output).not.toContain('process'); + unlink(); +})); +// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 +test('process env vars are replaced with ones from define', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `if (process.env.VAR !== 'hello') { throw new Error('process.env.VAR not right: ' + process.env.VAR) }`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + define: { + 'process.env.VAR': '"hello"', + }, + plugins: [NodeGlobalsPolyfillPlugin({})], + }); + const output = res.outputFiles[0].text; + eval(output); + unlink(); +})); +test('Buffer works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `console.log(Buffer.from('xxx').toString())`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('Buffer is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `console.log('hei')`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }); + const output = res.outputFiles[0].text; + expect(output).not.toContain('Buffer'); + unlink(); +})); +test('Buffer works using plugin', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': ` + let buf = new Buffer(256); + let len = buf.write("Simply Easy Learning"); + console.log("Octets written : "+ len);`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeGlobalsPolyfillPlugin({ buffer: true })], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('process works using plugin', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `console.log(process.cwd())`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeGlobalsPolyfillPlugin({ process: true })], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +//# sourceMappingURL=index.test.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js.map b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js.map new file mode 100644 index 0000000..9e46b21 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAC/B,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,yBAAyB,EAAE,MAAM,GAAG,CAAA;AAE7C,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,CAAA;AAExD,IAAI,CAAC,eAAe,EAAE,GAAS,EAAE;IAC7B,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,UAAU,CAAC;QACjB,UAAU,EAAE,iBAAiB;KAChC,CAAC,CAAA;IACF,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC;QACpB,WAAW,EAAE,C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M,UAAU,CAAC;QACjB,UAAU,EAAE,4BAA4B;KAC3C,CAAC,CAAA;IACF,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,CAAC,yBAAyB,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;KAC1D,CAAC,CAAA;IACF,MAAM,MAAM,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACtC,sBAAsB;IACtB,IAAI,CAAC,MAAM,CAAC,CAAA;IACZ,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/package.json b/node_modules/@esbuild-plugins/node-globals-polyfill/package.json new file mode 100644 index 0000000..f62b1fc --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/package.json @@ -0,0 +1,34 @@ +{ + "name": "@esbuild-plugins/node-globals-polyfill", + "version": "0.2.3", + "description": "", + "preferUnplugged": true, + "sideEffects": false, + "main": "dist/index.js", + "module": "esm/index.js", + "types": "dist/index.d.ts", + "repository": "https://github.com/remorses/esbuild-plugins.git", + "scripts": { + "build": "tsc && tsc -m es6 --outDir esm", + "watch": "tsc -w" + }, + "files": [ + "dist", + "src", + "esm", + "Buffer.js", + "process.js", + "_buffer.js", + "_process.js" + ], + "keywords": [], + "author": "Tommaso De Rossi, morse ", + "license": "ISC", + "devDependencies": { + "test-support": "*" + }, + "dependencies": {}, + "peerDependencies": { + "esbuild": "*" + } +} diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/process.js b/node_modules/@esbuild-plugins/node-globals-polyfill/process.js new file mode 100644 index 0000000..cb43c28 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/process.js @@ -0,0 +1,245 @@ +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined') +} +function defaultClearTimeout() { + throw new Error('clearTimeout has not been defined') +} +var cachedSetTimeout = defaultSetTimout +var cachedClearTimeout = defaultClearTimeout +if (typeof global.setTimeout === 'function') { + cachedSetTimeout = setTimeout +} +if (typeof global.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0) + } + // if setTimeout wasn't available but was latter defined + if ( + (cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && + setTimeout + ) { + cachedSetTimeout = setTimeout + return setTimeout(fun, 0) + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0) + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0) + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0) + } + } +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker) + } + // if clearTimeout wasn't available but was latter defined + if ( + (cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && + clearTimeout + ) { + cachedClearTimeout = clearTimeout + return clearTimeout(marker) + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker) + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker) + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker) + } + } +} +var queue = [] +var draining = false +var currentQueue +var queueIndex = -1 + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return + } + draining = false + if (currentQueue.length) { + queue = currentQueue.concat(queue) + } else { + queueIndex = -1 + } + if (queue.length) { + drainQueue() + } +} + +function drainQueue() { + if (draining) { + return + } + var timeout = runTimeout(cleanUpNextTick) + draining = true + + var len = queue.length + while (len) { + currentQueue = queue + queue = [] + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run() + } + } + queueIndex = -1 + len = queue.length + } + currentQueue = null + draining = false + runClearTimeout(timeout) +} +function nextTick(fun) { + var args = new Array(arguments.length - 1) + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i] + } + } + queue.push(new Item(fun, args)) + if (queue.length === 1 && !draining) { + runTimeout(drainQueue) + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun + this.array = array +} +Item.prototype.run = function() { + this.fun.apply(null, this.array) +} +var title = 'browser' +var platform = 'browser' +var browser = true +var env = {} +var argv = [] +var version = '' // empty string to avoid regexp issues +var versions = {} +var release = {} +var config = {} + +function noop() {} + +var on = noop +var addListener = noop +var once = noop +var off = noop +var removeListener = noop +var removeAllListeners = noop +var emit = noop + +function binding(name) { + throw new Error('process.binding is not supported') +} + +function cwd() { + return '/' +} +function chdir(dir) { + throw new Error('process.chdir is not supported') +} +function umask() { + return 0 +} + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global.performance || {} +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function() { + return new Date().getTime() + } + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp) { + var clocktime = performanceNow.call(performance) * 1e-3 + var seconds = Math.floor(clocktime) + var nanoseconds = Math.floor((clocktime % 1) * 1e9) + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0] + nanoseconds = nanoseconds - previousTimestamp[1] + if (nanoseconds < 0) { + seconds-- + nanoseconds += 1e9 + } + } + return [seconds, nanoseconds] +} + +var startTime = new Date() +function uptime() { + var currentTime = new Date() + var dif = currentTime - startTime + return dif / 1000 +} + +export var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime, +} + +// replace process.env.VAR with define + +const defines = {} +Object.keys(defines).forEach((key) => { + const segs = key.split('.') + let target = process + for (let i = 0; i < segs.length; i++) { + const seg = segs[i] + if (i === segs.length - 1) { + target[seg] = defines[key] + } else { + target = target[seg] || (target[seg] = {}) + } + } +}) diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.test.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.test.ts new file mode 100644 index 0000000..62e530e --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.test.ts @@ -0,0 +1,155 @@ +import { build } from 'esbuild' +import { writeFiles } from 'test-support' +import { NodeGlobalsPolyfillPlugin } from '.' + +require('debug').enable(require('../package.json').name) + +test('process works', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `process.version`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }) + const output = res.outputFiles[0].text + // console.log(output) + eval(output) + unlink() +}) + +test('process is tree shaken', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `console.log('hei')`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }) + const output = res.outputFiles[0].text + expect(output).not.toContain('process') + unlink() +}) + +// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 +test('process env vars are replaced with ones from define', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `if (process.env.VAR !== 'hello') { throw new Error('process.env.VAR not right: ' + process.env.VAR) }`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + define: { + 'process.env.VAR': '"hello"', + }, + plugins: [NodeGlobalsPolyfillPlugin({})], + }) + const output = res.outputFiles[0].text + eval(output) + unlink() +}) + +test('Buffer works', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `console.log(Buffer.from('xxx').toString())`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }) + const output = res.outputFiles[0].text + // console.log(output) + eval(output) + unlink() +}) + +test('Buffer is tree shaken', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `console.log('hei')`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }) + const output = res.outputFiles[0].text + expect(output).not.toContain('Buffer') + unlink() +}) + +test('Buffer works using plugin', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': ` + let buf = new Buffer(256); + let len = buf.write("Simply Easy Learning"); + console.log("Octets written : "+ len);`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeGlobalsPolyfillPlugin({ buffer: true })], + }) + const output = res.outputFiles[0].text + // console.log(output) + eval(output) + unlink() +}) +test('process works using plugin', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `console.log(process.cwd())`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeGlobalsPolyfillPlugin({ process: true })], + }) + const output = res.outputFiles[0].text + // console.log(output) + eval(output) + unlink() +}) diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.ts new file mode 100644 index 0000000..4b06c37 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.ts @@ -0,0 +1,84 @@ +import path from 'path' +import fs from 'fs' +import * as esbuild from 'esbuild' + +export function NodeGlobalsPolyfillPlugin({ + buffer = false, + // define = {}, + process = true, +} = {}): esbuild.Plugin { + return { + name: 'node-globals-polyfill', + setup({ initialOptions, onResolve, onLoad }) { + onResolve({ filter: /_node-buffer-polyfill_\.js/ }, (arg) => { + return { + path: path.resolve(__dirname, '../Buffer.js'), + } + }) + onResolve({ filter: /_node-process-polyfill_\.js/ }, (arg) => { + return { + path: path.resolve(__dirname, '../process.js'), + } + }) + + // TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 + // onLoad({ filter: /_virtual-process-polyfill_\.js/ }, (arg) => { + // const data = fs + // .readFileSync(path.resolve(__dirname, '../process.js')) + // .toString() + + // const keys = Object.keys(define) + // return { + // loader: 'js', + // contents: data.replace( + // `const defines = {}`, + // 'const defines = {\n' + + // keys + // .filter((x) => x.startsWith('process.')) + // .sort((a, b) => a.length - b.length) + // .map( + // (k) => + // ` ${JSON.stringify(k).replace( + // 'process.', + // '', + // )}: ${define[k]},`, + // ) + // .join('\n') + + // '\n}', + // ), + // } + // }) + onResolve({ filter: /_virtual-process-polyfill_\.js/ }, () => { + return { + path: path.resolve(__dirname, '../process.js'), + } + }) + onResolve({ filter: /_virtual-buffer-polyfill_\.js/ }, () => { + return { + path: path.resolve(__dirname, '../_buffer.js'), + } + }) + + const polyfills: string[] = [] + if (process) { + polyfills.push( + path.resolve(__dirname, '../_virtual-process-polyfill_.js'), + ) + } + if (buffer) { + polyfills.push( + path.resolve(__dirname, '../_virtual-buffer-polyfill_.js'), + ) + } + if (initialOptions.inject) { + initialOptions.inject.push(...polyfills) + // handle duplicate plugin + initialOptions.inject = [...new Set(initialOptions.inject)] + } else { + initialOptions.inject = [...polyfills] + } + }, + } +} + +export default NodeGlobalsPolyfillPlugin diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts new file mode 100644 index 0000000..65d4193 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts @@ -0,0 +1,8 @@ +import { Plugin } from 'esbuild'; +export interface NodePolyfillsOptions { + name?: string; + namespace?: string; +} +export declare function NodeModulesPolyfillPlugin(options?: NodePolyfillsOptions): Plugin; +export default NodeModulesPolyfillPlugin; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts.map new file mode 100644 index 0000000..c1151f9 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,MAAM,EAAE,MAAM,SAAS,CAAA;AAkB/C,MAAM,WAAW,oBAAoB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,wBAAgB,yBAAyB,CACrC,OAAO,GAAE,oBAAyB,GACnC,MAAM,CAwFR;AAmBD,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js new file mode 100644 index 0000000..51f4d1a --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js @@ -0,0 +1,127 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NodeModulesPolyfillPlugin = void 0; +const escape_string_regexp_1 = __importDefault(require("escape-string-regexp")); +const fs_1 = __importDefault(require("fs")); +const path_1 = __importDefault(require("path")); +const polyfills_1 = require("./polyfills"); +// import { NodeResolvePlugin } from '@esbuild-plugins/node-resolve' +const NAME = 'node-modules-polyfills'; +const NAMESPACE = NAME; +function removeEndingSlash(importee) { + if (importee && importee.slice(-1) === '/') { + importee = importee.slice(0, -1); + } + return importee; +} +function NodeModulesPolyfillPlugin(options = {}) { + const { namespace = NAMESPACE, name = NAME } = options; + if (namespace.endsWith('commonjs')) { + throw new Error(`namespace ${namespace} must not end with commonjs`); + } + // this namespace is needed to make ES modules expose their default export to require: require('assert') will give you import('assert').default + const commonjsNamespace = namespace + '-commonjs'; + const polyfilledBuiltins = polyfills_1.builtinsPolyfills(); + const polyfilledBuiltinsNames = [...polyfilledBuiltins.keys()]; + return { + name, + setup: function setup({ onLoad, onResolve, initialOptions }) { + var _a; + // polyfills contain global keyword, it must be defined + if ((initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define) && !((_a = initialOptions.define) === null || _a === void 0 ? void 0 : _a.global)) { + initialOptions.define['global'] = 'globalThis'; + } + else if (!(initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define)) { + initialOptions.define = { global: 'globalThis' }; + } + // TODO these polyfill module cannot import anything, is that ok? + function loader(args) { + return __awaiter(this, void 0, void 0, function* () { + try { + const argsPath = args.path.replace(/^node:/, ''); + const isCommonjs = args.namespace.endsWith('commonjs'); + const resolved = polyfilledBuiltins.get(removeEndingSlash(argsPath)); + const contents = yield (yield fs_1.default.promises.readFile(resolved)).toString(); + let resolveDir = path_1.default.dirname(resolved); + if (isCommonjs) { + return { + loader: 'js', + contents: commonJsTemplate({ + importPath: argsPath, + }), + resolveDir, + }; + } + return { + loader: 'js', + contents, + resolveDir, + }; + } + catch (e) { + console.error('node-modules-polyfill', e); + return { + contents: `export {}`, + loader: 'js', + }; + } + }); + } + onLoad({ filter: /.*/, namespace }, loader); + onLoad({ filter: /.*/, namespace: commonjsNamespace }, loader); + const filter = new RegExp([ + ...polyfilledBuiltinsNames, + ...polyfilledBuiltinsNames.map((n) => `node:${n}`), + ] + .map(escape_string_regexp_1.default) + .join('|')); + function resolver(args) { + return __awaiter(this, void 0, void 0, function* () { + const argsPath = args.path.replace(/^node:/, ''); + const ignoreRequire = args.namespace === commonjsNamespace; + if (!polyfilledBuiltins.has(argsPath)) { + return; + } + const isCommonjs = !ignoreRequire && args.kind === 'require-call'; + return { + namespace: isCommonjs ? commonjsNamespace : namespace, + path: argsPath, + }; + }); + } + onResolve({ filter }, resolver); + // onResolve({ filter: /.*/, namespace }, resolver) + }, + }; +} +exports.NodeModulesPolyfillPlugin = NodeModulesPolyfillPlugin; +function commonJsTemplate({ importPath }) { + return ` +const polyfill = require('${importPath}') + +if (polyfill && polyfill.default) { + module.exports = polyfill.default + for (let k in polyfill) { + module.exports[k] = polyfill[k] + } +} else if (polyfill) { + module.exports = polyfill +} + + +`; +} +exports.default = NodeModulesPolyfillPlugin; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js.map new file mode 100644 index 0000000..c4bf9e4 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;A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M,CACrB;gBACI,GAAG,uBAAuB;gBAC1B,GAAG,uBAAuB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC;aACrD;iBACI,GAAG,CAAC,8BAAkB,CAAC;iBACvB,IAAI,CAAC,GAAG,CAAC,CACjB,CAAA;YACD,SAAe,QAAQ,CAAC,IAAmB;;oBACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAA;oBAChD,MAAM,aAAa,GAAG,IAAI,CAAC,SAAS,KAAK,iBAAiB,CAAA;oBAE1D,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;wBACnC,OAAM;qBACT;oBAED,MAAM,UAAU,GACZ,CAAC,aAAa,IAAI,IAAI,CAAC,IAAI,KAAK,cAAc,CAAA;oBAElD,OAAO;wBACH,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,SAAS;wBACrD,IAAI,EAAE,QAAQ;qBACjB,CAAA;gBACL,CAAC;aAAA;YACD,SAAS,CAAC,EAAE,MAAM,EAAE,EAAE,QAAQ,CAAC,CAAA;YAC/B,mDAAmD;QACvD,CAAC;KACJ,CAAA;AACL,CAAC;AA1FD,8DA0FC;AAED,SAAS,gBAAgB,CAAC,EAAE,UAAU,EAAE;IACpC,OAAO;4BACiB,UAAU;;;;;;;;;;;;CAYrC,CAAA;AACD,CAAC;AAED,kBAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts new file mode 100644 index 0000000..121d59b --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.test.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts.map new file mode 100644 index 0000000..b5774e1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js new file mode 100644 index 0000000..2923eec --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js @@ -0,0 +1,183 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const esbuild_1 = require("esbuild"); +const test_support_1 = require("test-support"); +const fs_1 = __importDefault(require("fs")); +const _1 = __importDefault(require(".")); +const node_globals_polyfill_1 = __importDefault(require("@esbuild-plugins/node-globals-polyfill")); +require('debug').enable(require('../package.json').name); +test('works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('works with SafeBuffer and other package consumers', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import {Buffer as SafeBuffer} from './safe-buffer'; console.log(SafeBuffer);`, + 'safe-buffer.ts': fs_1.default + .readFileSync(require.resolve('safe-buffer')) + .toString(), + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + // console.log( + // res.outputFiles[0].text + // .split('\n') + // .map((x, i) => i + ' ' + x) + // .join('\n'), + // ) + eval(res.outputFiles[0].text); + unlink(); +})); +test('events works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': ` + import EventEmitter from 'events'; + + class Test extends EventEmitter { + constructor() { }; + } + console.log(Test) + `, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text); + unlink(); +})); +test('require can use default export', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': ` + const assert = require('assert') + // console.log(assert) + assert('ok') + `, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text); + unlink(); +})); +test.skip('crypto', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import { randomBytes } from 'crypto'; console.log(randomBytes(20).toString('hex'))`, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test.skip('fs', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import { readFile } from 'fs'; console.log(readFile(''))`, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('does not include global keyword', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + const text = res.outputFiles[0].text; + eval(text); + expect(text).not.toContain(/\bglobal\b/); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('works with globals polyfills', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default(), node_globals_polyfill_1.default()], + }); + const text = res.outputFiles[0].text; + eval(text); + console.log(text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +//# sourceMappingURL=index.test.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js.map new file mode 100644 index 0000000..e8a76e6 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,qCAA+B;AAC/B,+CAAyC;AACzC,4CAAmB;AACnB,yCAA0C;AAC1C,mGAA+E;AAE/E,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,CAAA;AAExD,IAAI,CAAC,OAAO,EAAE,GAAS,EAAE;IACrB,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,yBAAU,CAAC;QACjB,UAAU,EAAE,4CAA4C;QACxD,UAAU,EAAE,uHAAuH;KACtI,CAAC,CAAA;IACF,qCAAqC;IACrC,MAAM,GAAG,GAAG,MAAM,eAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,CAAC,UAA0B,EAAE,CAAC;KAC1C,CAAC,CAAA;IACF,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;IAC7B,uCAAuC;IACvC,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA;AAEF,IAAI,CAAC,mDAAmD,EAAE,GAAS,EAAE;IACjE,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,y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EAAE,GAAS,EAAE;IAC5C,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,yBAAU,CAAC;QACjB,UAAU,EAAE,4CAA4C;QACxD,UAAU,EAAE,uHAAuH;KACtI,CAAC,CAAA;IACF,qCAAqC;IACrC,MAAM,GAAG,GAAG,MAAM,eAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,CAAC,UAA0B,EAAE,EAAE,+BAA0B,EAAE,CAAC;KACxE,CAAC,CAAA;IACF,MAAM,IAAI,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACpC,IAAI,CAAC,IAAI,CAAC,CAAA;IACV,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;IACjB,uCAAuC;IACvC,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts new file mode 100644 index 0000000..564adc1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts @@ -0,0 +1,2 @@ +export declare function builtinsPolyfills(): Map; +//# sourceMappingURL=polyfills.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts.map new file mode 100644 index 0000000..2f7b592 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":"AAQA,wBAAgB,iBAAiB,kBA8IhC"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js new file mode 100644 index 0000000..4f4f953 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js @@ -0,0 +1,61 @@ +"use strict"; +// Taken from https://github.com/ionic-team/rollup-plugin-node-polyfills/blob/master/src/modules.ts +Object.defineProperty(exports, "__esModule", { value: true }); +exports.builtinsPolyfills = void 0; +const EMPTY_PATH = require.resolve('rollup-plugin-node-polyfills/polyfills/empty.js'); +function builtinsPolyfills() { + const libs = new Map(); + libs.set('process', require.resolve('rollup-plugin-node-polyfills/polyfills/process-es6')); + libs.set('buffer', require.resolve('rollup-plugin-node-polyfills/polyfills/buffer-es6')); + libs.set('util', require.resolve('rollup-plugin-node-polyfills/polyfills/util')); + libs.set('sys', libs.get('util')); + libs.set('events', require.resolve('rollup-plugin-node-polyfills/polyfills/events')); + libs.set('stream', require.resolve('rollup-plugin-node-polyfills/polyfills/stream')); + libs.set('path', require.resolve('rollup-plugin-node-polyfills/polyfills/path')); + libs.set('querystring', require.resolve('rollup-plugin-node-polyfills/polyfills/qs')); + libs.set('punycode', require.resolve('rollup-plugin-node-polyfills/polyfills/punycode')); + libs.set('url', require.resolve('rollup-plugin-node-polyfills/polyfills/url')); + libs.set('string_decoder', require.resolve('rollup-plugin-node-polyfills/polyfills/string-decoder')); + libs.set('http', require.resolve('rollup-plugin-node-polyfills/polyfills/http')); + libs.set('https', require.resolve('rollup-plugin-node-polyfills/polyfills/http')); + libs.set('os', require.resolve('rollup-plugin-node-polyfills/polyfills/os')); + libs.set('assert', require.resolve('rollup-plugin-node-polyfills/polyfills/assert')); + libs.set('constants', require.resolve('rollup-plugin-node-polyfills/polyfills/constants')); + libs.set('_stream_duplex', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/duplex')); + libs.set('_stream_passthrough', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough')); + libs.set('_stream_readable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/readable')); + libs.set('_stream_writable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/writable')); + libs.set('_stream_transform', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/transform')); + libs.set('timers', require.resolve('rollup-plugin-node-polyfills/polyfills/timers')); + libs.set('console', require.resolve('rollup-plugin-node-polyfills/polyfills/console')); + libs.set('vm', require.resolve('rollup-plugin-node-polyfills/polyfills/vm')); + libs.set('zlib', require.resolve('rollup-plugin-node-polyfills/polyfills/zlib')); + libs.set('tty', require.resolve('rollup-plugin-node-polyfills/polyfills/tty')); + libs.set('domain', require.resolve('rollup-plugin-node-polyfills/polyfills/domain')); + // not shimmed + libs.set('dns', EMPTY_PATH); + libs.set('dgram', EMPTY_PATH); + libs.set('child_process', EMPTY_PATH); + libs.set('cluster', EMPTY_PATH); + libs.set('module', EMPTY_PATH); + libs.set('net', EMPTY_PATH); + libs.set('readline', EMPTY_PATH); + libs.set('repl', EMPTY_PATH); + libs.set('tls', EMPTY_PATH); + libs.set('fs', EMPTY_PATH); + libs.set('crypto', EMPTY_PATH); + // libs.set( + // 'fs', + // require.resolve('rollup-plugin-node-polyfills/polyfills/browserify-fs'), + // ) + // TODO enable crypto and fs https://github.com/ionic-team/rollup-plugin-node-polyfills/issues/20 + // libs.set( + // 'crypto', + // require.resolve( + // 'rollup-plugin-node-polyfills/polyfills/crypto-browserify', + // ), + // ) + return libs; +} +exports.builtinsPolyfills = builtinsPolyfills; +//# sourceMappingURL=polyfills.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js.map new file mode 100644 index 0000000..a7ef0e3 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js.map @@ -0,0 +1 @@ +{"version":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,OAAO,CAAC,6CAA6C,CAAC,CACjE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ,KAAK,EACL,OAAO,CAAC,OAAO,CAAC,4CAA4C,CAAC,CAChE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ,QAAQ,EACR,OAAO,CAAC,OAAO,CAAC,+CAA+C,CAAC,CACnE,CAAA;IAED,cAAc;IACd,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC,CAAA;IAC7B,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,CAAC,CAAA;IACrC,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,UAAU,CAAC,CAAA;IAC/B,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAC9B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,UAAU,CAAC,CAAA;IAChC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;IAC5B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,CAAA;IAC1B,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAE9B,YAAY;IACZ,YAAY;IACZ,+EAA+E;IAC/E,IAAI;IAEJ,iGAAiG;IACjG,YAAY;IACZ,gBAAgB;IAChB,uBAAuB;IACvB,sEAAsE;IACtE,SAAS;IACT,IAAI;IAEJ,OAAO,IAAI,CAAA;AACf,CAAC;AA9ID,8CA8IC"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts new file mode 100644 index 0000000..65d4193 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts @@ -0,0 +1,8 @@ +import { Plugin } from 'esbuild'; +export interface NodePolyfillsOptions { + name?: string; + namespace?: string; +} +export declare function NodeModulesPolyfillPlugin(options?: NodePolyfillsOptions): Plugin; +export default NodeModulesPolyfillPlugin; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts.map new file mode 100644 index 0000000..c1151f9 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,MAAM,EAAE,MAAM,SAAS,CAAA;AAkB/C,MAAM,WAAW,oBAAoB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,wBAAgB,yBAAyB,CACrC,OAAO,GAAE,oBAAyB,GACnC,MAAM,CAwFR;AAmBD,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js new file mode 100644 index 0000000..69526b5 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js @@ -0,0 +1,120 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import escapeStringRegexp from 'escape-string-regexp'; +import fs from 'fs'; +import path from 'path'; +import { builtinsPolyfills } from './polyfills'; +// import { NodeResolvePlugin } from '@esbuild-plugins/node-resolve' +const NAME = 'node-modules-polyfills'; +const NAMESPACE = NAME; +function removeEndingSlash(importee) { + if (importee && importee.slice(-1) === '/') { + importee = importee.slice(0, -1); + } + return importee; +} +export function NodeModulesPolyfillPlugin(options = {}) { + const { namespace = NAMESPACE, name = NAME } = options; + if (namespace.endsWith('commonjs')) { + throw new Error(`namespace ${namespace} must not end with commonjs`); + } + // this namespace is needed to make ES modules expose their default export to require: require('assert') will give you import('assert').default + const commonjsNamespace = namespace + '-commonjs'; + const polyfilledBuiltins = builtinsPolyfills(); + const polyfilledBuiltinsNames = [...polyfilledBuiltins.keys()]; + return { + name, + setup: function setup({ onLoad, onResolve, initialOptions }) { + var _a; + // polyfills contain global keyword, it must be defined + if ((initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define) && !((_a = initialOptions.define) === null || _a === void 0 ? void 0 : _a.global)) { + initialOptions.define['global'] = 'globalThis'; + } + else if (!(initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define)) { + initialOptions.define = { global: 'globalThis' }; + } + // TODO these polyfill module cannot import anything, is that ok? + function loader(args) { + return __awaiter(this, void 0, void 0, function* () { + try { + const argsPath = args.path.replace(/^node:/, ''); + const isCommonjs = args.namespace.endsWith('commonjs'); + const resolved = polyfilledBuiltins.get(removeEndingSlash(argsPath)); + const contents = yield (yield fs.promises.readFile(resolved)).toString(); + let resolveDir = path.dirname(resolved); + if (isCommonjs) { + return { + loader: 'js', + contents: commonJsTemplate({ + importPath: argsPath, + }), + resolveDir, + }; + } + return { + loader: 'js', + contents, + resolveDir, + }; + } + catch (e) { + console.error('node-modules-polyfill', e); + return { + contents: `export {}`, + loader: 'js', + }; + } + }); + } + onLoad({ filter: /.*/, namespace }, loader); + onLoad({ filter: /.*/, namespace: commonjsNamespace }, loader); + const filter = new RegExp([ + ...polyfilledBuiltinsNames, + ...polyfilledBuiltinsNames.map((n) => `node:${n}`), + ] + .map(escapeStringRegexp) + .join('|')); + function resolver(args) { + return __awaiter(this, void 0, void 0, function* () { + const argsPath = args.path.replace(/^node:/, ''); + const ignoreRequire = args.namespace === commonjsNamespace; + if (!polyfilledBuiltins.has(argsPath)) { + return; + } + const isCommonjs = !ignoreRequire && args.kind === 'require-call'; + return { + namespace: isCommonjs ? commonjsNamespace : namespace, + path: argsPath, + }; + }); + } + onResolve({ filter }, resolver); + // onResolve({ filter: /.*/, namespace }, resolver) + }, + }; +} +function commonJsTemplate({ importPath }) { + return ` +const polyfill = require('${importPath}') + +if (polyfill && polyfill.default) { + module.exports = polyfill.default + for (let k in polyfill) { + module.exports[k] = polyfill[k] + } +} else if (polyfill) { + module.exports = polyfill +} + + +`; +} +export default NodeModulesPolyfillPlugin; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js.map new file mode 100644 index 0000000..c8544ab --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,kBAAkB,MAAM,sBAAsB,CAAA;AACrD,OAAO,EAAE,MAAM,IAAI,CAAA;AACnB,OAAO,IAAI,MAAM,MAAM,CAAA;AAEvB,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAE/C,oEAAoE;AACpE,MAAM,IAAI,GAAG,wBAAwB,CAAA;AACrC,MAAM,SAAS,GAAG,IAAI,CAAA;AAEtB,SAAS,iBAAiB,CAAC,QAAQ;IAC/B,IAAI,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;QACxC,QAAQ,GAAG,QAAQ,CAAC,KAAK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QAAQ,EAAE,EAAE,CAAC,CAAA;oBAChD,MAAM,aAAa,GAAG,IAAI,CAAC,SAAS,KAAK,iBAAiB,CAAA;oBAE1D,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;wBACnC,OAAM;qBACT;oBAED,MAAM,UAAU,GACZ,CAAC,aAAa,IAAI,IAAI,CAAC,IAAI,KAAK,cAAc,CAAA;oBAElD,OAAO;wBACH,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,SAAS;wBACrD,IAAI,EAAE,QAAQ;qBACjB,CAAA;gBACL,CAAC;aAAA;YACD,SAAS,CAAC,EAAE,MAAM,EAAE,EAAE,QAAQ,CAAC,CAAA;YAC/B,mDAAmD;QACvD,CAAC;KACJ,CAAA;AACL,CAAC;AAED,SAAS,gBAAgB,CAAC,EAAE,UAAU,EAAE;IACpC,OAAO;4BACiB,UAAU;;;;;;;;;;;;CAYrC,CAAA;AACD,CAAC;AAED,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts new file mode 100644 index 0000000..121d59b --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.test.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts.map new file mode 100644 index 0000000..b5774e1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js new file mode 100644 index 0000000..b4ff899 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js @@ -0,0 +1,178 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { build } from 'esbuild'; +import { writeFiles } from 'test-support'; +import fs from 'fs'; +import NodeModulesPolyfillsPlugin from '.'; +import NodeGlobalsPolyfillsPlugin from '@esbuild-plugins/node-globals-polyfill'; +require('debug').enable(require('../package.json').name); +test('works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('works with SafeBuffer and other package consumers', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import {Buffer as SafeBuffer} from './safe-buffer'; console.log(SafeBuffer);`, + 'safe-buffer.ts': fs + .readFileSync(require.resolve('safe-buffer')) + .toString(), + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + // console.log( + // res.outputFiles[0].text + // .split('\n') + // .map((x, i) => i + ' ' + x) + // .join('\n'), + // ) + eval(res.outputFiles[0].text); + unlink(); +})); +test('events works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': ` + import EventEmitter from 'events'; + + class Test extends EventEmitter { + constructor() { }; + } + console.log(Test) + `, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text); + unlink(); +})); +test('require can use default export', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': ` + const assert = require('assert') + // console.log(assert) + assert('ok') + `, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text); + unlink(); +})); +test.skip('crypto', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import { randomBytes } from 'crypto'; console.log(randomBytes(20).toString('hex'))`, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test.skip('fs', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import { readFile } from 'fs'; console.log(readFile(''))`, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('does not include global keyword', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + const text = res.outputFiles[0].text; + eval(text); + expect(text).not.toContain(/\bglobal\b/); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('works with globals polyfills', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin(), NodeGlobalsPolyfillsPlugin()], + }); + const text = res.outputFiles[0].text; + eval(text); + console.log(text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +//# sourceMappingURL=index.test.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js.map new file mode 100644 index 0000000..9e80cfd --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAC/B,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,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AAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,CAAC,0BAA0B,EAAE,EAAE,0BAA0B,EAAE,CAAC;KACxE,CAAC,CAAA;IACF,MAAM,IAAI,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACpC,IAAI,CAAC,IAAI,CAAC,CAAA;IACV,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;IACjB,uCAAuC;IACvC,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts new file mode 100644 index 0000000..564adc1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts @@ -0,0 +1,2 @@ +export declare function builtinsPolyfills(): Map; +//# sourceMappingURL=polyfills.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts.map new file mode 100644 index 0000000..2f7b592 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":"AAQA,wBAAgB,iBAAiB,kBA8IhC"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js new file mode 100644 index 0000000..28b0ea7 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js @@ -0,0 +1,57 @@ +// Taken from https://github.com/ionic-team/rollup-plugin-node-polyfills/blob/master/src/modules.ts +const EMPTY_PATH = require.resolve('rollup-plugin-node-polyfills/polyfills/empty.js'); +export function builtinsPolyfills() { + const libs = new Map(); + libs.set('process', require.resolve('rollup-plugin-node-polyfills/polyfills/process-es6')); + libs.set('buffer', require.resolve('rollup-plugin-node-polyfills/polyfills/buffer-es6')); + libs.set('util', require.resolve('rollup-plugin-node-polyfills/polyfills/util')); + libs.set('sys', libs.get('util')); + libs.set('events', require.resolve('rollup-plugin-node-polyfills/polyfills/events')); + libs.set('stream', require.resolve('rollup-plugin-node-polyfills/polyfills/stream')); + libs.set('path', require.resolve('rollup-plugin-node-polyfills/polyfills/path')); + libs.set('querystring', require.resolve('rollup-plugin-node-polyfills/polyfills/qs')); + libs.set('punycode', require.resolve('rollup-plugin-node-polyfills/polyfills/punycode')); + libs.set('url', require.resolve('rollup-plugin-node-polyfills/polyfills/url')); + libs.set('string_decoder', require.resolve('rollup-plugin-node-polyfills/polyfills/string-decoder')); + libs.set('http', require.resolve('rollup-plugin-node-polyfills/polyfills/http')); + libs.set('https', require.resolve('rollup-plugin-node-polyfills/polyfills/http')); + libs.set('os', require.resolve('rollup-plugin-node-polyfills/polyfills/os')); + libs.set('assert', require.resolve('rollup-plugin-node-polyfills/polyfills/assert')); + libs.set('constants', require.resolve('rollup-plugin-node-polyfills/polyfills/constants')); + libs.set('_stream_duplex', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/duplex')); + libs.set('_stream_passthrough', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough')); + libs.set('_stream_readable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/readable')); + libs.set('_stream_writable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/writable')); + libs.set('_stream_transform', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/transform')); + libs.set('timers', require.resolve('rollup-plugin-node-polyfills/polyfills/timers')); + libs.set('console', require.resolve('rollup-plugin-node-polyfills/polyfills/console')); + libs.set('vm', require.resolve('rollup-plugin-node-polyfills/polyfills/vm')); + libs.set('zlib', require.resolve('rollup-plugin-node-polyfills/polyfills/zlib')); + libs.set('tty', require.resolve('rollup-plugin-node-polyfills/polyfills/tty')); + libs.set('domain', require.resolve('rollup-plugin-node-polyfills/polyfills/domain')); + // not shimmed + libs.set('dns', EMPTY_PATH); + libs.set('dgram', EMPTY_PATH); + libs.set('child_process', EMPTY_PATH); + libs.set('cluster', EMPTY_PATH); + libs.set('module', EMPTY_PATH); + libs.set('net', EMPTY_PATH); + libs.set('readline', EMPTY_PATH); + libs.set('repl', EMPTY_PATH); + libs.set('tls', EMPTY_PATH); + libs.set('fs', EMPTY_PATH); + libs.set('crypto', EMPTY_PATH); + // libs.set( + // 'fs', + // require.resolve('rollup-plugin-node-polyfills/polyfills/browserify-fs'), + // ) + // TODO enable crypto and fs https://github.com/ionic-team/rollup-plugin-node-polyfills/issues/20 + // libs.set( + // 'crypto', + // require.resolve( + // 'rollup-plugin-node-polyfills/polyfills/crypto-browserify', + // ), + // ) + return libs; +} +//# sourceMappingURL=polyfills.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js.map new file mode 100644 index 0000000..3c35ae4 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":"AAAA,mGAAmG;AAInG,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAC9B,iDAAiD,CACpD,CAAA;AAED,MAAM,UAAU,iBAAiB;IAC7B,MAAM,IAAI,GAAG,IAAI,GAAG,EAAE,CAAA;IAEtB,IAAI,CAAC,GAAG,CACJ,SAAS,EACT,OAAO,CAAC,OAAO,CAAC,oDAAoD,CAAC,CACxE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ,QAAQ,EACR,OAAO,CAAC,OAAO,CAAC,mDAAmD,CAAC,CACvE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AE,UAAU,CAAC,CAAA;IACrC,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,UAAU,CAAC,CAAA;IAC/B,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAC9B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,UAAU,CAAC,CAAA;IAChC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;IAC5B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,CAAA;IAC1B,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAE9B,YAAY;IACZ,YAAY;IACZ,+EAA+E;IAC/E,IAAI;IAEJ,iGAAiG;IACjG,YAAY;IACZ,gBAAgB;IAChB,uBAAuB;IACvB,sEAAsE;IACtE,SAAS;IACT,IAAI;IAEJ,OAAO,IAAI,CAAA;AACf,CAAC"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/package.json b/node_modules/@esbuild-plugins/node-modules-polyfill/package.json new file mode 100644 index 0000000..d9a6e41 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/package.json @@ -0,0 +1,33 @@ +{ + "name": "@esbuild-plugins/node-modules-polyfill", + "version": "0.2.2", + "description": "", + "main": "dist/index.js", + "module": "esm/index.js", + "types": "dist/index.d.ts", + "repository": "https://github.com/remorses/esbuild-plugins.git", + "scripts": { + "build": "tsc && tsc -m es6 --outDir esm", + "watch": "tsc -w" + }, + "files": [ + "dist", + "src", + "esm" + ], + "keywords": [], + "author": "Tommaso De Rossi, morse ", + "license": "ISC", + "devDependencies": { + "safe-buffer": "^5.2.1", + "test-support": "*", + "@esbuild-plugins/node-globals-polyfill": "*" + }, + "dependencies": { + "escape-string-regexp": "^4.0.0", + "rollup-plugin-node-polyfills": "^0.2.1" + }, + "peerDependencies": { + "esbuild": "*" + } +} diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.test.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.test.ts new file mode 100644 index 0000000..92792e6 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.test.ts @@ -0,0 +1,200 @@ +import { build } from 'esbuild' +import { writeFiles } from 'test-support' +import fs from 'fs' +import NodeModulesPolyfillsPlugin from '.' +import NodeGlobalsPolyfillsPlugin from '@esbuild-plugins/node-globals-polyfill' + +require('debug').enable(require('../package.json').name) + +test('works', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + eval(res.outputFiles[0].text) + // console.log(res.outputFiles[0].text) + unlink() +}) + +test('works with SafeBuffer and other package consumers', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import {Buffer as SafeBuffer} from './safe-buffer'; console.log(SafeBuffer);`, + 'safe-buffer.ts': fs + .readFileSync(require.resolve('safe-buffer')) + .toString(), + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + // console.log( + // res.outputFiles[0].text + // .split('\n') + // .map((x, i) => i + ' ' + x) + // .join('\n'), + // ) + eval(res.outputFiles[0].text) + unlink() +}) + +test('events works', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': ` + import EventEmitter from 'events'; + + class Test extends EventEmitter { + constructor() { }; + } + console.log(Test) + `, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text) + unlink() +}) + +test('require can use default export', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': ` + const assert = require('assert') + // console.log(assert) + assert('ok') + `, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text) + unlink() +}) + +test.skip('crypto', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import { randomBytes } from 'crypto'; console.log(randomBytes(20).toString('hex'))`, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + eval(res.outputFiles[0].text) + // console.log(res.outputFiles[0].text) + unlink() +}) +test.skip('fs', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import { readFile } from 'fs'; console.log(readFile(''))`, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + eval(res.outputFiles[0].text) + // console.log(res.outputFiles[0].text) + unlink() +}) + +test('does not include global keyword', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + const text = res.outputFiles[0].text + eval(text) + expect(text).not.toContain(/\bglobal\b/) + // console.log(res.outputFiles[0].text) + unlink() +}) + +test('works with globals polyfills', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin(), NodeGlobalsPolyfillsPlugin()], + }) + const text = res.outputFiles[0].text + eval(text) + console.log(text) + // console.log(res.outputFiles[0].text) + unlink() +}) diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.ts new file mode 100644 index 0000000..f7397e4 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.ts @@ -0,0 +1,133 @@ +import { OnResolveArgs, Plugin } from 'esbuild' +import escapeStringRegexp from 'escape-string-regexp' +import fs from 'fs' +import path from 'path' +import esbuild from 'esbuild' +import { builtinsPolyfills } from './polyfills' + +// import { NodeResolvePlugin } from '@esbuild-plugins/node-resolve' +const NAME = 'node-modules-polyfills' +const NAMESPACE = NAME + +function removeEndingSlash(importee) { + if (importee && importee.slice(-1) === '/') { + importee = importee.slice(0, -1) + } + return importee +} + +export interface NodePolyfillsOptions { + name?: string + namespace?: string +} + +export function NodeModulesPolyfillPlugin( + options: NodePolyfillsOptions = {}, +): Plugin { + const { namespace = NAMESPACE, name = NAME } = options + if (namespace.endsWith('commonjs')) { + throw new Error(`namespace ${namespace} must not end with commonjs`) + } + // this namespace is needed to make ES modules expose their default export to require: require('assert') will give you import('assert').default + const commonjsNamespace = namespace + '-commonjs' + const polyfilledBuiltins = builtinsPolyfills() + const polyfilledBuiltinsNames = [...polyfilledBuiltins.keys()] + + return { + name, + setup: function setup({ onLoad, onResolve, initialOptions }) { + // polyfills contain global keyword, it must be defined + if (initialOptions?.define && !initialOptions.define?.global) { + initialOptions.define['global'] = 'globalThis' + } else if (!initialOptions?.define) { + initialOptions.define = { global: 'globalThis' } + } + + // TODO these polyfill module cannot import anything, is that ok? + async function loader( + args: esbuild.OnLoadArgs, + ): Promise { + try { + const argsPath = args.path.replace(/^node:/, '') + const isCommonjs = args.namespace.endsWith('commonjs') + + const resolved = polyfilledBuiltins.get( + removeEndingSlash(argsPath), + ) + const contents = await ( + await fs.promises.readFile(resolved) + ).toString() + let resolveDir = path.dirname(resolved) + + if (isCommonjs) { + return { + loader: 'js', + contents: commonJsTemplate({ + importPath: argsPath, + }), + resolveDir, + } + } + return { + loader: 'js', + contents, + resolveDir, + } + } catch (e) { + console.error('node-modules-polyfill', e) + return { + contents: `export {}`, + loader: 'js', + } + } + } + onLoad({ filter: /.*/, namespace }, loader) + onLoad({ filter: /.*/, namespace: commonjsNamespace }, loader) + const filter = new RegExp( + [ + ...polyfilledBuiltinsNames, + ...polyfilledBuiltinsNames.map((n) => `node:${n}`), + ] + .map(escapeStringRegexp) + .join('|'), // TODO builtins could end with slash, keep in mind in regex + ) + async function resolver(args: OnResolveArgs) { + const argsPath = args.path.replace(/^node:/, '') + const ignoreRequire = args.namespace === commonjsNamespace + + if (!polyfilledBuiltins.has(argsPath)) { + return + } + + const isCommonjs = + !ignoreRequire && args.kind === 'require-call' + + return { + namespace: isCommonjs ? commonjsNamespace : namespace, + path: argsPath, + } + } + onResolve({ filter }, resolver) + // onResolve({ filter: /.*/, namespace }, resolver) + }, + } +} + +function commonJsTemplate({ importPath }) { + return ` +const polyfill = require('${importPath}') + +if (polyfill && polyfill.default) { + module.exports = polyfill.default + for (let k in polyfill) { + module.exports[k] = polyfill[k] + } +} else if (polyfill) { + module.exports = polyfill +} + + +` +} + +export default NodeModulesPolyfillPlugin diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/src/polyfills.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/src/polyfills.ts new file mode 100644 index 0000000..cea5f8d --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/src/polyfills.ts @@ -0,0 +1,151 @@ +// Taken from https://github.com/ionic-team/rollup-plugin-node-polyfills/blob/master/src/modules.ts + +import { NodePolyfillsOptions } from '.' + +const EMPTY_PATH = require.resolve( + 'rollup-plugin-node-polyfills/polyfills/empty.js', +) + +export function builtinsPolyfills() { + const libs = new Map() + + libs.set( + 'process', + require.resolve('rollup-plugin-node-polyfills/polyfills/process-es6'), + ) + libs.set( + 'buffer', + require.resolve('rollup-plugin-node-polyfills/polyfills/buffer-es6'), + ) + libs.set( + 'util', + require.resolve('rollup-plugin-node-polyfills/polyfills/util'), + ) + libs.set('sys', libs.get('util')) + libs.set( + 'events', + require.resolve('rollup-plugin-node-polyfills/polyfills/events'), + ) + libs.set( + 'stream', + require.resolve('rollup-plugin-node-polyfills/polyfills/stream'), + ) + libs.set( + 'path', + require.resolve('rollup-plugin-node-polyfills/polyfills/path'), + ) + libs.set( + 'querystring', + require.resolve('rollup-plugin-node-polyfills/polyfills/qs'), + ) + libs.set( + 'punycode', + require.resolve('rollup-plugin-node-polyfills/polyfills/punycode'), + ) + libs.set( + 'url', + require.resolve('rollup-plugin-node-polyfills/polyfills/url'), + ) + libs.set( + 'string_decoder', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/string-decoder', + ), + ) + libs.set( + 'http', + require.resolve('rollup-plugin-node-polyfills/polyfills/http'), + ) + libs.set( + 'https', + require.resolve('rollup-plugin-node-polyfills/polyfills/http'), + ) + libs.set('os', require.resolve('rollup-plugin-node-polyfills/polyfills/os')) + libs.set( + 'assert', + require.resolve('rollup-plugin-node-polyfills/polyfills/assert'), + ) + libs.set( + 'constants', + require.resolve('rollup-plugin-node-polyfills/polyfills/constants'), + ) + libs.set( + '_stream_duplex', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex', + ), + ) + libs.set( + '_stream_passthrough', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough', + ), + ) + libs.set( + '_stream_readable', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/readable-stream/readable', + ), + ) + libs.set( + '_stream_writable', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/readable-stream/writable', + ), + ) + libs.set( + '_stream_transform', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/readable-stream/transform', + ), + ) + libs.set( + 'timers', + require.resolve('rollup-plugin-node-polyfills/polyfills/timers'), + ) + libs.set( + 'console', + require.resolve('rollup-plugin-node-polyfills/polyfills/console'), + ) + libs.set('vm', require.resolve('rollup-plugin-node-polyfills/polyfills/vm')) + libs.set( + 'zlib', + require.resolve('rollup-plugin-node-polyfills/polyfills/zlib'), + ) + libs.set( + 'tty', + require.resolve('rollup-plugin-node-polyfills/polyfills/tty'), + ) + libs.set( + 'domain', + require.resolve('rollup-plugin-node-polyfills/polyfills/domain'), + ) + + // not shimmed + libs.set('dns', EMPTY_PATH) + libs.set('dgram', EMPTY_PATH) + libs.set('child_process', EMPTY_PATH) + libs.set('cluster', EMPTY_PATH) + libs.set('module', EMPTY_PATH) + libs.set('net', EMPTY_PATH) + libs.set('readline', EMPTY_PATH) + libs.set('repl', EMPTY_PATH) + libs.set('tls', EMPTY_PATH) + libs.set('fs', EMPTY_PATH) + libs.set('crypto', EMPTY_PATH) + + // libs.set( + // 'fs', + // require.resolve('rollup-plugin-node-polyfills/polyfills/browserify-fs'), + // ) + + // TODO enable crypto and fs https://github.com/ionic-team/rollup-plugin-node-polyfills/issues/20 + // libs.set( + // 'crypto', + // require.resolve( + // 'rollup-plugin-node-polyfills/polyfills/crypto-browserify', + // ), + // ) + + return libs +} diff --git a/node_modules/@esbuild/darwin-arm64/README.md b/node_modules/@esbuild/darwin-arm64/README.md new file mode 100644 index 0000000..c2c0398 --- /dev/null +++ b/node_modules/@esbuild/darwin-arm64/README.md @@ -0,0 +1,3 @@ +# esbuild + +This is the macOS ARM 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details. diff --git a/node_modules/@esbuild/darwin-arm64/bin/esbuild b/node_modules/@esbuild/darwin-arm64/bin/esbuild new file mode 100755 index 0000000..d8cc784 Binary files /dev/null and b/node_modules/@esbuild/darwin-arm64/bin/esbuild differ diff --git a/node_modules/@esbuild/darwin-arm64/package.json b/node_modules/@esbuild/darwin-arm64/package.json new file mode 100644 index 0000000..b5191a2 --- /dev/null +++ b/node_modules/@esbuild/darwin-arm64/package.json @@ -0,0 +1,17 @@ +{ + "name": "@esbuild/darwin-arm64", + "version": "0.17.19", + "description": "The macOS ARM 64-bit binary for esbuild, a JavaScript bundler.", + "repository": "https://github.com/evanw/esbuild", + "license": "MIT", + "preferUnplugged": true, + "engines": { + "node": ">=12" + }, + "os": [ + "darwin" + ], + "cpu": [ + "arm64" + ] +} diff --git a/node_modules/@fastify/busboy/LICENSE b/node_modules/@fastify/busboy/LICENSE new file mode 100644 index 0000000..290762e --- /dev/null +++ b/node_modules/@fastify/busboy/LICENSE @@ -0,0 +1,19 @@ +Copyright Brian White. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@fastify/busboy/README.md b/node_modules/@fastify/busboy/README.md new file mode 100644 index 0000000..ece3cc8 --- /dev/null +++ b/node_modules/@fastify/busboy/README.md @@ -0,0 +1,271 @@ +# busboy + +

+ +
+ +[![NPM version](https://img.shields.io/npm/v/@fastify/busboy.svg?style=flat)](https://www.npmjs.com/package/@fastify/busboy) +[![NPM downloads](https://img.shields.io/npm/dm/@fastify/busboy.svg?style=flat)](https://www.npmjs.com/package/@fastify/busboy) + +
+ +Description +=========== + +A Node.js module for parsing incoming HTML form data. + +This is an officially supported fork by [fastify](https://github.com/fastify/) organization of the amazing library [originally created](https://github.com/mscdex/busboy) by Brian White, +aimed at addressing long-standing issues with it. + +Benchmark (Mean time for 500 Kb payload, 2000 cycles, 1000 cycle warmup): + +| Library | Version | Mean time in nanoseconds (less is better) | +|-----------------------|---------|-------------------------------------------| +| busboy | 0.3.1 | `340114` | +| @fastify/busboy | 1.0.0 | `270984` | + +[Changelog](https://github.com/fastify/busboy/blob/master/CHANGELOG.md) since busboy 0.31. + +Requirements +============ + +* [Node.js](http://nodejs.org/) 10+ + + +Install +======= + + npm i @fastify/busboy + + +Examples +======== + +* Parsing (multipart) with default options: + +```javascript +const http = require('node:http'); +const { inspect } = require('node:util'); +const Busboy = require('busboy'); + +http.createServer((req, res) => { + if (req.method === 'POST') { + const busboy = new Busboy({ headers: req.headers }); + busboy.on('file', (fieldname, file, filename, encoding, mimetype) => { + console.log(`File [${fieldname}]: filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`); + file.on('data', data => { + console.log(`File [${fieldname}] got ${data.length} bytes`); + }); + file.on('end', () => { + console.log(`File [${fieldname}] Finished`); + }); + }); + busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => { + console.log(`Field [${fieldname}]: value: ${inspect(val)}`); + }); + busboy.on('finish', () => { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end(` +
+
+
+ +
+ `); + } +}).listen(8000, () => { + console.log('Listening for requests'); +}); + +// Example output, using http://nodejs.org/images/ryan-speaker.jpg as the file: +// +// Listening for requests +// File [filefield]: filename: ryan-speaker.jpg, encoding: binary +// File [filefield] got 11971 bytes +// Field [textfield]: value: 'testing! :-)' +// File [filefield] Finished +// Done parsing form! +``` + +* Save all incoming files to disk: + +```javascript +const http = require('node:http'); +const path = require('node:path'); +const os = require('node:os'); +const fs = require('node:fs'); + +const Busboy = require('busboy'); + +http.createServer(function(req, res) { + if (req.method === 'POST') { + const busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + var saveTo = path.join(os.tmpdir(), path.basename(fieldname)); + file.pipe(fs.createWriteStream(saveTo)); + }); + busboy.on('finish', function() { + res.writeHead(200, { 'Connection': 'close' }); + res.end("That's all folks!"); + }); + return req.pipe(busboy); + } + res.writeHead(404); + res.end(); +}).listen(8000, function() { + console.log('Listening for requests'); +}); +``` + +* Parsing (urlencoded) with default options: + +```javascript +const http = require('node:http'); +const { inspect } = require('node:util'); + +const Busboy = require('busboy'); + +http.createServer(function(req, res) { + if (req.method === 'POST') { + const busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + console.log('File [' + fieldname + ']: filename: ' + filename); + file.on('data', function(data) { + console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); + }); + file.on('end', function() { + console.log('File [' + fieldname + '] Finished'); + }); + }); + busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) { + console.log('Field [' + fieldname + ']: value: ' + inspect(val)); + }); + busboy.on('finish', function() { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end('\ +
\ +
\ +
\ + Node.js rules!
\ + \ +
\ + '); + } +}).listen(8000, function() { + console.log('Listening for requests'); +}); + +// Example output: +// +// Listening for requests +// Field [textfield]: value: 'testing! :-)' +// Field [selectfield]: value: '9001' +// Field [checkfield]: value: 'on' +// Done parsing form! +``` + + +API +=== + +_Busboy_ is a _Writable_ stream + +Busboy (special) events +----------------------- + +* **file**(< _string_ >fieldname, < _ReadableStream_ >stream, < _string_ >filename, < _string_ >transferEncoding, < _string_ >mimeType) - Emitted for each new file form field found. `transferEncoding` contains the 'Content-Transfer-Encoding' value for the file stream. `mimeType` contains the 'Content-Type' value for the file stream. + * Note: if you listen for this event, you should always handle the `stream` no matter if you care about the file contents or not (e.g. you can simply just do `stream.resume();` if you want to discard the contents), otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about **any** incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically and safely discarded (these discarded files do still count towards `files` and `parts` limits). + * If a configured file size limit was reached, `stream` will both have a boolean property `truncated` (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens. + * The property `bytesRead` informs about the number of bytes that have been read so far. + +* **field**(< _string_ >fieldname, < _string_ >value, < _boolean_ >fieldnameTruncated, < _boolean_ >valueTruncated, < _string_ >transferEncoding, < _string_ >mimeType) - Emitted for each new non-file field found. + +* **partsLimit**() - Emitted when specified `parts` limit has been reached. No more 'file' or 'field' events will be emitted. + +* **filesLimit**() - Emitted when specified `files` limit has been reached. No more 'file' events will be emitted. + +* **fieldsLimit**() - Emitted when specified `fields` limit has been reached. No more 'field' events will be emitted. + + +Busboy methods +-------------- + +* **(constructor)**(< _object_ >config) - Creates and returns a new Busboy instance. + + * The constructor takes the following valid `config` settings: + + * **headers** - _object_ - These are the HTTP headers of the incoming request, which are used by individual parsers. + + * **autoDestroy** - _boolean_ - Whether this stream should automatically call .destroy() on itself after ending. (Default: false). + + * **highWaterMark** - _integer_ - highWaterMark to use for this Busboy instance (Default: WritableStream default). + + * **fileHwm** - _integer_ - highWaterMark to use for file streams (Default: ReadableStream default). + + * **defCharset** - _string_ - Default character set to use when one isn't defined (Default: 'utf8'). + + * **preservePath** - _boolean_ - If paths in the multipart 'filename' field shall be preserved. (Default: false). + + * **isPartAFile** - __function__ - Use this function to override the default file detection functionality. It has following parameters: + + * fieldName - __string__ The name of the field. + + * contentType - __string__ The content-type of the part, e.g. `text/plain`, `image/jpeg`, `application/octet-stream` + + * fileName - __string__ The name of a file supplied by the part. + + (Default: `(fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)`) + + * **limits** - _object_ - Various limits on incoming data. Valid properties are: + + * **fieldNameSize** - _integer_ - Max field name size (in bytes) (Default: 100 bytes). + + * **fieldSize** - _integer_ - Max field value size (in bytes) (Default: 1 MiB, which is 1024 x 1024 bytes). + + * **fields** - _integer_ - Max number of non-file fields (Default: Infinity). + + * **fileSize** - _integer_ - For multipart forms, the max file size (in bytes) (Default: Infinity). + + * **files** - _integer_ - For multipart forms, the max number of file fields (Default: Infinity). + + * **parts** - _integer_ - For multipart forms, the max number of parts (fields + files) (Default: Infinity). + + * **headerPairs** - _integer_ - For multipart forms, the max number of header key=>value pairs to parse **Default:** 2000 + + * **headerSize** - _integer_ - For multipart forms, the max size of a multipart header **Default:** 81920. + + * The constructor can throw errors: + + * **Busboy expected an options-Object.** - Busboy expected an Object as first parameters. + + * **Busboy expected an options-Object with headers-attribute.** - The first parameter is lacking of a headers-attribute. + + * **Limit $limit is not a valid number** - Busboy expected the desired limit to be of type number. Busboy throws this Error to prevent a potential security issue by falling silently back to the Busboy-defaults. Potential source for this Error can be the direct use of environment variables without transforming them to the type number. + + * **Unsupported Content-Type.** - The `Content-Type` isn't one Busboy can parse. + + * **Missing Content-Type-header.** - The provided headers don't include `Content-Type` at all. diff --git a/node_modules/@fastify/busboy/deps/dicer/LICENSE b/node_modules/@fastify/busboy/deps/dicer/LICENSE new file mode 100644 index 0000000..290762e --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/LICENSE @@ -0,0 +1,19 @@ +Copyright Brian White. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js b/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js new file mode 100644 index 0000000..3c8c081 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js @@ -0,0 +1,213 @@ +'use strict' + +const WritableStream = require('node:stream').Writable +const inherits = require('node:util').inherits + +const StreamSearch = require('../../streamsearch/sbmh') + +const PartStream = require('./PartStream') +const HeaderParser = require('./HeaderParser') + +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} + +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) + + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } + + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } + + this._headerFirst = cfg.headerFirst + + this._dashes = 0 + this._parts = 0 + this._finished = false + this._realFinish = false + this._isPreamble = true + this._justMatched = false + this._firstWrite = true + this._inHeader = true + this._part = undefined + this._cb = undefined + this._ignoreData = false + this._partOpts = { highWaterMark: cfg.partHwm } + this._pause = false + + const self = this + this._hparser = new HeaderParser(cfg) + this._hparser.on('header', function (header) { + self._inHeader = false + self._part.emit('header', header) + }) +} +inherits(Dicer, WritableStream) + +Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this + process.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')) + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part') + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) + self._part.push(null) + process.nextTick(function () { + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + return + } + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + } + } else { WritableStream.prototype.emit.apply(this, arguments) } +} + +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } + + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts) + if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } + } + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } + } + + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } + + this._bparser.push(data) + + if (this._pause) { this._cb = cb } else { cb() } +} + +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined +} + +Dicer.prototype.setBoundary = function (boundary) { + const self = this + this._bparser = new StreamSearch('\r\n--' + boundary) + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end) + }) +} + +Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true + this._part.on('error', EMPTY_FN) + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume() + } +} + +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true + + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i + ++this._dashes + } else { + if (this._dashes) { buf = B_ONEDASH } + this._dashes = 0 + break + } + } + if (this._dashes === 2) { + if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } + this.reset() + this._finished = true + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } + } + if (this._dashes) { return } + } + if (this._justMatched) { this._justMatched = false } + if (!this._part) { + this._part = new PartStream(this._partOpts) + this._part._read = function (n) { + self._unpause() + } + if (this._isPreamble && this.listenerCount('preamble') !== 0) { + this.emit('preamble', this._part) + } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { + this.emit('part', this._part) + } else { + this._ignore() + } + if (!this._isPreamble) { this._inHeader = true } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf) } + shouldWriteMore = this._part.push(data.slice(start, end)) + if (!shouldWriteMore) { this._pause = true } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf) } + r = this._hparser.push(data.slice(start, end)) + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } + } + } + if (isMatch) { + this._hparser.reset() + if (this._isPreamble) { this._isPreamble = false } else { + if (start !== end) { + ++this._parts + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } else { + self._unpause() + } + } + }) + } + } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 + } +} + +Dicer.prototype._unpause = function () { + if (!this._pause) { return } + + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() + } +} + +module.exports = Dicer diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js b/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js new file mode 100644 index 0000000..65f667b --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js @@ -0,0 +1,100 @@ +'use strict' + +const EventEmitter = require('node:events').EventEmitter +const inherits = require('node:util').inherits +const getLimit = require('../../../lib/utils/getLimit') + +const StreamSearch = require('../../streamsearch/sbmh') + +const B_DCRLF = Buffer.from('\r\n\r\n') +const RE_CRLF = /\r\n/g +const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex + +function HeaderParser (cfg) { + EventEmitter.call(this) + + cfg = cfg || {} + const self = this + this.nread = 0 + this.maxed = false + this.npairs = 0 + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) + this.buffer = '' + this.header = {} + this.finished = false + this.ss = new StreamSearch(B_DCRLF) + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start + self.nread = self.maxHeaderSize + self.maxed = true + } else { self.nread += (end - start) } + + self.buffer += data.toString('binary', start, end) + } + if (isMatch) { self._finish() } + }) +} +inherits(HeaderParser, EventEmitter) + +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } +} + +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() +} + +HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader() } + this.ss.matches = this.ss.maxMatches + const header = this.header + this.header = {} + this.buffer = '' + this.finished = true + this.nread = this.npairs = 0 + this.maxed = false + this.emit('header', header) +} + +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } + + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i] + continue + } + } + + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return + } + m = RE_HDR.exec(lines[i]) + h = m[1].toLowerCase() + this.header[h] = this.header[h] || [] + this.header[h].push((m[2] || '')) + if (++this.npairs === this.maxHeaderPairs) { break } + } +} + +module.exports = HeaderParser diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js b/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js new file mode 100644 index 0000000..c91da1c --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js @@ -0,0 +1,13 @@ +'use strict' + +const inherits = require('node:util').inherits +const ReadableStream = require('node:stream').Readable + +function PartStream (opts) { + ReadableStream.call(this, opts) +} +inherits(PartStream, ReadableStream) + +PartStream.prototype._read = function (n) {} + +module.exports = PartStream diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts b/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts new file mode 100644 index 0000000..3c5b896 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts @@ -0,0 +1,164 @@ +// Type definitions for dicer 0.2 +// Project: https://github.com/mscdex/dicer +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +/// + +import stream = require("stream"); + +// tslint:disable:unified-signatures + +/** + * A very fast streaming multipart parser for node.js. + * Dicer is a WritableStream + * + * Dicer (special) events: + * - on('finish', ()) - Emitted when all parts have been parsed and the Dicer instance has been ended. + * - on('part', (stream: PartStream)) - Emitted when a new part has been found. + * - on('preamble', (stream: PartStream)) - Emitted for preamble if you should happen to need it (can usually be ignored). + * - on('trailer', (data: Buffer)) - Emitted when trailing data was found after the terminating boundary (as with the preamble, this can usually be ignored too). + */ +export class Dicer extends stream.Writable { + /** + * Creates and returns a new Dicer instance with the following valid config settings: + * + * @param config The configuration to use + */ + constructor(config: Dicer.Config); + /** + * Sets the boundary to use for parsing and performs some initialization needed for parsing. + * You should only need to use this if you set headerFirst to true in the constructor and are parsing the boundary from the preamble header. + * + * @param boundary The boundary to use + */ + setBoundary(boundary: string): void; + addListener(event: "finish", listener: () => void): this; + addListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "trailer", listener: (data: 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: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "part", listener: (stream: Dicer.PartStream) => void): this; + on(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + on(event: "trailer", listener: (data: 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: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "part", listener: (stream: Dicer.PartStream) => void): this; + once(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + once(event: "trailer", listener: (data: 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: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "trailer", listener: (data: 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: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "trailer", listener: (data: 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: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "trailer", listener: (data: Buffer) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pipe", listener: (src: stream.Readable) => void): this; + removeListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; +} + +declare namespace Dicer { + interface Config { + /** + * This is the boundary used to detect the beginning of a new part. + */ + boundary?: string | undefined; + /** + * If true, preamble header parsing will be performed first. + */ + headerFirst?: boolean | undefined; + /** + * The maximum number of header key=>value pairs to parse Default: 2000 (same as node's http). + */ + maxHeaderPairs?: number | undefined; + } + + /** + * PartStream is a _ReadableStream_ + * + * PartStream (special) events: + * - on('header', (header: object)) - An object containing the header for this particular part. Each property value is an array of one or more string values. + */ + interface PartStream extends stream.Readable { + addListener(event: "header", listener: (header: object) => 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, listener: (...args: any[]) => void): this; + on(event: "header", listener: (header: object) => 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, listener: (...args: any[]) => void): this; + once(event: "header", listener: (header: object) => 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, listener: (...args: any[]) => void): this; + prependListener(event: "header", listener: (header: object) => 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, listener: (...args: any[]) => void): this; + prependOnceListener(event: "header", listener: (header: object) => 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, listener: (...args: any[]) => void): this; + removeListener(event: "header", listener: (header: object) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + } +} \ No newline at end of file diff --git a/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js b/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js new file mode 100644 index 0000000..b90c0e8 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js @@ -0,0 +1,228 @@ +'use strict' + +/** + * Copyright Brian White. All rights reserved. + * + * @see https://github.com/mscdex/streamsearch + * + * 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. + * + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool + */ +const EventEmitter = require('node:events').EventEmitter +const inherits = require('node:util').inherits + +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) + } + + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') + } + + const needleLength = needle.length + + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') + } + + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } + + this.maxMatches = Infinity + this.matches = 0 + + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 + + this._lookbehind = Buffer.alloc(needleLength) + + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLength - 1 - i + } +} +inherits(SBMH, EventEmitter) + +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 +} + +SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary') + } + const chlen = chunk.length + this._bufpos = pos || 0 + let r + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } + return r +} + +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] + + // 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[lookbehind_size - 2] + let pos = -this._lookbehind_size + let ch + + 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 <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1) + + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) + + return (this._bufpos = pos + needleLength) + } + pos += this._occ[ch] + } + + // No match. + + if (pos < 0) { + // 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 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + } + + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) + this._lookbehind_size = 0 + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff) + } + + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff + + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len + + this._bufpos = len + return len + } + } + + pos += (pos >= 0) * this._bufpos + + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos) + ++this.matches + if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } + + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength + } + + // 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 && + ( + data[pos] !== needle[0] || + ( + (Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0) + ) + ) + ) { + ++pos + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos + } + + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } + + this._bufpos = len + return len +} + +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} + +SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } + } + return true +} + +module.exports = SBMH diff --git a/node_modules/@fastify/busboy/lib/main.d.ts b/node_modules/@fastify/busboy/lib/main.d.ts new file mode 100644 index 0000000..91b6448 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/main.d.ts @@ -0,0 +1,196 @@ +// Definitions by: Jacob Baskin +// BendingBender +// Igor Savin + +/// + +import * as http from 'http'; +import { Readable, Writable } from 'stream'; +export { Dicer } from "../deps/dicer/lib/dicer"; + +export const Busboy: BusboyConstructor; +export default Busboy; + +export interface BusboyConfig { + /** + * These are the HTTP headers of the incoming request, which are used by individual parsers. + */ + headers: BusboyHeaders; + /** + * `highWaterMark` to use for this Busboy instance. + * @default WritableStream default. + */ + highWaterMark?: number | undefined; + /** + * highWaterMark to use for file streams. + * @default ReadableStream default. + */ + fileHwm?: number | undefined; + /** + * Default character set to use when one isn't defined. + * @default 'utf8' + */ + defCharset?: string | undefined; + /** + * Detect if a Part is a file. + * + * By default a file is detected if contentType + * is application/octet-stream or fileName is not + * undefined. + * + * Modify this to handle e.g. Blobs. + */ + isPartAFile?: (fieldName: string | undefined, contentType: string | undefined, fileName: string | undefined) => boolean; + /** + * If paths in the multipart 'filename' field shall be preserved. + * @default false + */ + preservePath?: boolean | undefined; + /** + * Various limits on incoming data. + */ + limits?: + | { + /** + * Max field name size (in bytes) + * @default 100 bytes + */ + fieldNameSize?: number | undefined; + /** + * Max field value size (in bytes) + * @default 1MB + */ + fieldSize?: number | undefined; + /** + * Max number of non-file fields + * @default Infinity + */ + fields?: number | undefined; + /** + * For multipart forms, the max file size (in bytes) + * @default Infinity + */ + fileSize?: number | undefined; + /** + * For multipart forms, the max number of file fields + * @default Infinity + */ + files?: number | undefined; + /** + * For multipart forms, the max number of parts (fields + files) + * @default Infinity + */ + parts?: number | undefined; + /** + * For multipart forms, the max number of header key=>value pairs to parse + * @default 2000 + */ + headerPairs?: number | undefined; + + /** + * For multipart forms, the max size of a header part + * @default 81920 + */ + headerSize?: number | undefined; + } + | undefined; +} + +export type BusboyHeaders = { 'content-type': string } & http.IncomingHttpHeaders; + +export interface BusboyFileStream extends + Readable { + + truncated: boolean; + + /** + * The number of bytes that have been read so far. + */ + bytesRead: number; +} + +export interface Busboy extends Writable { + addListener(event: Event, listener: BusboyEvents[Event]): this; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + on(event: Event, listener: BusboyEvents[Event]): this; + + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: Event, listener: BusboyEvents[Event]): this; + + once(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: Event, listener: BusboyEvents[Event]): this; + + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: Event, listener: BusboyEvents[Event]): this; + + off(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: Event, listener: BusboyEvents[Event]): this; + + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: Event, listener: BusboyEvents[Event]): this; + + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; +} + +export interface BusboyEvents { + /** + * Emitted for each new file form field found. + * + * * Note: if you listen for this event, you should always handle the `stream` no matter if you care about the + * file contents or not (e.g. you can simply just do `stream.resume();` if you want to discard the contents), + * otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about **any** + * incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically + * and safely discarded (these discarded files do still count towards `files` and `parts` limits). + * * If a configured file size limit was reached, `stream` will both have a boolean property `truncated` + * (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens. + * + * @param listener.transferEncoding Contains the 'Content-Transfer-Encoding' value for the file stream. + * @param listener.mimeType Contains the 'Content-Type' value for the file stream. + */ + file: ( + fieldname: string, + stream: BusboyFileStream, + filename: string, + transferEncoding: string, + mimeType: string, + ) => void; + /** + * Emitted for each new non-file field found. + */ + field: ( + fieldname: string, + value: string, + fieldnameTruncated: boolean, + valueTruncated: boolean, + transferEncoding: string, + mimeType: string, + ) => void; + finish: () => void; + /** + * Emitted when specified `parts` limit has been reached. No more 'file' or 'field' events will be emitted. + */ + partsLimit: () => void; + /** + * Emitted when specified `files` limit has been reached. No more 'file' events will be emitted. + */ + filesLimit: () => void; + /** + * Emitted when specified `fields` limit has been reached. No more 'field' events will be emitted. + */ + fieldsLimit: () => void; + error: (error: unknown) => void; +} + +export interface BusboyConstructor { + (options: BusboyConfig): Busboy; + + new(options: BusboyConfig): Busboy; +} + diff --git a/node_modules/@fastify/busboy/lib/main.js b/node_modules/@fastify/busboy/lib/main.js new file mode 100644 index 0000000..8794beb --- /dev/null +++ b/node_modules/@fastify/busboy/lib/main.js @@ -0,0 +1,85 @@ +'use strict' + +const WritableStream = require('node:stream').Writable +const { inherits } = require('node:util') +const Dicer = require('../deps/dicer/lib/Dicer') + +const MultipartParser = require('./types/multipart') +const UrlencodedParser = require('./types/urlencoded') +const parseParams = require('./utils/parseParams') + +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } + + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } + + const { + headers, + ...streamOptions + } = opts + + this.opts = { + autoDestroy: false, + ...streamOptions + } + WritableStream.call(this, this.opts) + + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) + +Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end() + return + } else if (this._finished) { + return + } + this._finished = true + } + WritableStream.prototype.emit.apply(this, arguments) +} + +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) + + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath + } + + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') +} + +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} + +module.exports = Busboy +module.exports.default = Busboy +module.exports.Busboy = Busboy + +module.exports.Dicer = Dicer diff --git a/node_modules/@fastify/busboy/lib/types/multipart.js b/node_modules/@fastify/busboy/lib/types/multipart.js new file mode 100644 index 0000000..d691eca --- /dev/null +++ b/node_modules/@fastify/busboy/lib/types/multipart.js @@ -0,0 +1,306 @@ +'use strict' + +// TODO: +// * support 1 nested multipart level +// (see second multipart example here: +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) +// * support limits.fieldNameSize +// -- this will require modifications to utils.parseParams + +const { Readable } = require('node:stream') +const { inherits } = require('node:util') + +const Dicer = require('../../deps/dicer/lib/Dicer') + +const parseParams = require('../utils/parseParams') +const decodeText = require('../utils/decodeText') +const basename = require('../utils/basename') +const getLimit = require('../utils/getLimit') + +const RE_BOUNDARY = /^boundary$/i +const RE_FIELD = /^form-data$/i +const RE_CHARSET = /^charset$/i +const RE_FILENAME = /^filename$/i +const RE_NAME = /^name$/i + +Multipart.detect = /^multipart\/form-data/i +function Multipart (boy, cfg) { + let i + let len + const self = this + let boundary + const limits = cfg.limits + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) + const parsedConType = cfg.parsedConType || [] + const defCharset = cfg.defCharset || 'utf8' + const preservePath = cfg.preservePath + const fileOpts = { highWaterMark: cfg.fileHwm } + + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1] + break + } + } + + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } + + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } + + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) + const filesLimit = getLimit(limits, 'files', Infinity) + const fieldsLimit = getLimit(limits, 'fields', Infinity) + const partsLimit = getLimit(limits, 'parts', Infinity) + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) + + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false + + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy + + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + } + + this.parser = new Dicer(parserCfg) + this.parser.on('drain', function () { + self._needDrain = false + if (self._cb && !self._pause) { + const cb = self._cb + self._cb = undefined + cb() + } + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart) + self.parser.on('part', skipPart) + boy.hitPartsLimit = true + boy.emit('partsLimit') + return skipPart(part) + } + + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField + field.emit('end') + field.removeAllListeners('end') + } + + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 + + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]) + if (parsed[0]) { + contype = parsed[0].toLowerCase() + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase() + break + } + } + } + } + + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } + + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]) + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1] + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1] + if (!preservePath) { filename = basename(filename) } + } + } + } else { return skipPart(part) } + + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } + + let onData, + onEnd + + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } + + ++nfiles + + if (boy.listenerCount('file') === 0) { + self.parser._ignore() + return + } + + ++nends + const file = new FileStream(fileOpts) + curFile = file + file.on('end', function () { + --nends + self._pause = false + checkFinished() + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + }) + file._read = function (n) { + if (!self._pause) { return } + self._pause = false + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + } + boy.emit('file', fieldname, file, filename, encoding, contype) + + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length + if (extralen > 0) { file.push(data.slice(0, extralen)) } + file.truncated = true + file.bytesRead = fileSizeLimit + part.removeAllListeners('data') + file.emit('limit') + return + } else if (!file.push(data)) { self._pause = true } + + file.bytesRead = nsize + } + + onEnd = function () { + curFile = undefined + file.push(null) + } + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true + boy.emit('fieldsLimit') + } + return skipPart(part) + } + + ++nfields + ++nends + let buffer = '' + let truncated = false + curField = part + + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)) + buffer += data.toString('binary', 0, extralen) + truncated = true + part.removeAllListeners('data') + } else { buffer += data.toString('binary') } + } + + onEnd = function () { + curField = undefined + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) + --nends + checkFinished() + } + } + + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false + + part.on('data', onData) + part.on('end', onEnd) + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err) } + }) + }).on('error', function (err) { + boy.emit('error', err) + }).on('finish', function () { + finished = true + checkFinished() + }) +} + +Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk) + if (r && !this._pause) { + cb() + } else { + this._needDrain = !r + this._cb = cb + } +} + +Multipart.prototype.end = function () { + const self = this + + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) + } +} + +function skipPart (part) { + part.resume() +} + +function FileStream (opts) { + Readable.call(this, opts) + + this.bytesRead = 0 + + this.truncated = false +} + +inherits(FileStream, Readable) + +FileStream.prototype._read = function (n) {} + +module.exports = Multipart diff --git a/node_modules/@fastify/busboy/lib/types/urlencoded.js b/node_modules/@fastify/busboy/lib/types/urlencoded.js new file mode 100644 index 0000000..6f5f784 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/types/urlencoded.js @@ -0,0 +1,190 @@ +'use strict' + +const Decoder = require('../utils/Decoder') +const decodeText = require('../utils/decodeText') +const getLimit = require('../utils/getLimit') + +const RE_CHARSET = /^charset$/i + +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy + + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) + + let charset + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase() + break + } + } + + if (charset === undefined) { charset = cfg.defCharset || 'utf8' } + + this.decoder = new Decoder() + this.charset = charset + this._fields = 0 + this._state = 'key' + this._checkingBytes = true + this._bytesKey = 0 + this._bytesVal = 0 + this._key = '' + this._val = '' + this._keyTrunc = false + this._valTrunc = false + this._hitLimit = false +} + +UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true + this.boy.emit('fieldsLimit') + } + return cb() + } + + let idxeq; let idxamp; let i; let p = 0; const len = data.length + + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x3D/* = */) { + idxeq = i + break + } else if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesKey } + } + + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' + + this._hitLimit = false + this._checkingBytes = true + this._val = '' + this._bytesVal = 0 + this._valTrunc = false + this.decoder.reset() + + p = idxeq + 1 + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields + let key; const keyTrunc = this._keyTrunc + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false) + } + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._keyTrunc = true + } + } else { + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } + p = len + } + } else { + idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesVal } + } + + if (idxamp !== undefined) { + ++this._fields + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + this._state = 'key' + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._valTrunc = true + } + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } + p = len + } + } + } + cb() +} + +UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } + + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false) + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + } + this.boy._done = true + this.boy.emit('finish') +} + +module.exports = UrlEncoded diff --git a/node_modules/@fastify/busboy/lib/utils/Decoder.js b/node_modules/@fastify/busboy/lib/utils/Decoder.js new file mode 100644 index 0000000..7917678 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/Decoder.js @@ -0,0 +1,54 @@ +'use strict' + +const RE_PLUS = /\+/g + +const HEX = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +] + +function Decoder () { + this.buffer = undefined +} +Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' ') + let res = '' + let i = 0; let p = 0; const len = str.length + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer + this.buffer = undefined + --i // retry character + } else { + this.buffer += str[i] + ++p + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)) + this.buffer = undefined + } + } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i) + p = i + } + this.buffer = '' + ++p + } + } + if (p < len && this.buffer === undefined) { res += str.substring(p) } + return res +} +Decoder.prototype.reset = function () { + this.buffer = undefined +} + +module.exports = Decoder diff --git a/node_modules/@fastify/busboy/lib/utils/basename.js b/node_modules/@fastify/busboy/lib/utils/basename.js new file mode 100644 index 0000000..db58819 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/basename.js @@ -0,0 +1,14 @@ +'use strict' + +module.exports = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1) + return (path === '..' || path === '.' ? '' : path) + } + } + return (path === '..' || path === '.' ? '' : path) +} diff --git a/node_modules/@fastify/busboy/lib/utils/decodeText.js b/node_modules/@fastify/busboy/lib/utils/decodeText.js new file mode 100644 index 0000000..eac7d35 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/decodeText.js @@ -0,0 +1,114 @@ +'use strict' + +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) + +function getDecoder (charset) { + let lc + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true + charset = charset.toLowerCase() + continue + } + return decoders.other.bind(charset) + } + } +} + +const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.utf8Slice(0, data.length) + }, + + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + return data + } + return data.latin1Slice(0, data.length) + }, + + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.ucs2Slice(0, data.length) + }, + + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.base64Slice(0, data.length) + }, + + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch {} + } + return typeof data === 'string' + ? data + : data.toString() + } +} + +function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) + } + return text +} + +module.exports = decodeText diff --git a/node_modules/@fastify/busboy/lib/utils/getLimit.js b/node_modules/@fastify/busboy/lib/utils/getLimit.js new file mode 100644 index 0000000..cb64fd6 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/getLimit.js @@ -0,0 +1,16 @@ +'use strict' + +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } + + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } + + return limits[name] +} diff --git a/node_modules/@fastify/busboy/lib/utils/parseParams.js b/node_modules/@fastify/busboy/lib/utils/parseParams.js new file mode 100644 index 0000000..1698e62 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/parseParams.js @@ -0,0 +1,196 @@ +/* eslint-disable object-property-newline */ +'use strict' + +const decodeText = require('./decodeText') + +const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g + +const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +} + +function encodedReplacer (match) { + return EncodedLookup[match] +} + +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 + +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = STATE_KEY + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = STATE_KEY + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } + } + tmp += char + } + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } + + return res +} + +module.exports = parseParams diff --git a/node_modules/@fastify/busboy/package.json b/node_modules/@fastify/busboy/package.json new file mode 100644 index 0000000..83693ac --- /dev/null +++ b/node_modules/@fastify/busboy/package.json @@ -0,0 +1,86 @@ +{ + "name": "@fastify/busboy", + "version": "2.1.1", + "private": false, + "author": "Brian White ", + "contributors": [ + { + "name": "Igor Savin", + "email": "kibertoad@gmail.com", + "url": "https://github.com/kibertoad" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com", + "url": "https://github.com/uzlopak" + } + ], + "description": "A streaming parser for HTML form data for node.js", + "main": "lib/main", + "type": "commonjs", + "types": "lib/main.d.ts", + "scripts": { + "bench:busboy": "cd benchmarks && npm install && npm run benchmark-fastify", + "bench:dicer": "node bench/dicer/dicer-bench-multipart-parser.js", + "coveralls": "nyc report --reporter=lcov", + "lint": "npm run lint:standard", + "lint:everything": "npm run lint && npm run test:types", + "lint:fix": "standard --fix", + "lint:standard": "standard --verbose | snazzy", + "test:mocha": "tap", + "test:types": "tsd", + "test:coverage": "nyc npm run test", + "test": "npm run test:mocha" + }, + "engines": { + "node": ">=14" + }, + "devDependencies": { + "@types/node": "^20.1.0", + "busboy": "^1.0.0", + "photofinish": "^1.8.0", + "snazzy": "^9.0.0", + "standard": "^17.0.0", + "tap": "^16.3.8", + "tinybench": "^2.5.1", + "tsd": "^0.30.0", + "typescript": "^5.0.2" + }, + "keywords": [ + "uploads", + "forms", + "multipart", + "form-data" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/busboy.git" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "esModuleInterop": false, + "module": "commonjs", + "target": "ES2017" + } + }, + "standard": { + "globals": [ + "describe", + "it" + ], + "ignore": [ + "bench" + ] + }, + "files": [ + "README.md", + "LICENSE", + "lib/*", + "deps/encoding/*", + "deps/dicer/lib", + "deps/streamsearch/", + "deps/dicer/LICENSE" + ] +} diff --git a/node_modules/@jridgewell/resolve-uri/LICENSE b/node_modules/@jridgewell/resolve-uri/LICENSE new file mode 100644 index 0000000..0a81b2a --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/LICENSE @@ -0,0 +1,19 @@ +Copyright 2019 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/README.md b/node_modules/@jridgewell/resolve-uri/README.md new file mode 100644 index 0000000..2fe70df --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/README.md @@ -0,0 +1,40 @@ +# @jridgewell/resolve-uri + +> Resolve a URI relative to an optional base URI + +Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths. + +## Installation + +```sh +npm install @jridgewell/resolve-uri +``` + +## Usage + +```typescript +function resolve(input: string, base?: string): string; +``` + +```js +import resolve from '@jridgewell/resolve-uri'; + +resolve('foo', 'https://example.com'); // => 'https://example.com/foo' +``` + +| Input | Base | Resolution | Explanation | +|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------| +| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only | +| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol | +| `//example.com` | _rest_ | `//example.com/` | Input is normalized only | +| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin | +| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative | +| `/example` | _rest_ | `/example` | Input is normalized only | +| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base | +| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file | +| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory | +| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file | +| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory | +| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file | +| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory | +| `example` | `base/file` | `base/example` | Input is joined with the base without its file | diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs new file mode 100644 index 0000000..e958e88 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs @@ -0,0 +1,232 @@ +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +export { resolve as default }; +//# sourceMappingURL=resolve-uri.mjs.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map new file mode 100644 index 0000000..1de97d0 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.mjs","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":"AAAA;AACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC;;;;;;;;;;AAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;AAE5F;;;;;;;;;AASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;AAuBpF,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAa;IACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;IACpC,OAAO,OAAO,CACZ,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,GAAG,EACf,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CACf,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CAAC,KAAa;IACjC,MAAM,KAAK,GA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zB;QAED;YACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;QAE9B;YACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;KACpF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js new file mode 100644 index 0000000..a783049 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js @@ -0,0 +1,240 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory()); +})(this, (function () { 'use strict'; + + // Matches the scheme of a URL, eg "http://" + const schemeRegex = /^[\w+.-]+:\/\//; + /** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ + const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; + /** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ + const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; + function isAbsoluteUrl(input) { + return schemeRegex.test(input); + } + function isSchemeRelativeUrl(input) { + return input.startsWith('//'); + } + function isAbsolutePath(input) { + return input.startsWith('/'); + } + function isFileUrl(input) { + return input.startsWith('file:'); + } + function isRelative(input) { + return /^[.?#]/.test(input); + } + function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); + } + function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); + } + function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; + } + function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; + } + function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } + } + /** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ + function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; + } + /** + * Attempts to resolve `input` URL/path relative to `base`. + */ + function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } + } + + return resolve; + +})); +//# sourceMappingURL=resolve-uri.umd.js.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map new file mode 100644 index 0000000..70a37f2 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.umd.js","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":";;;;;;IAAA;IACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;IAErC;;;;;;;;;;IAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;IAE5F;;;;;;;;;IASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;IAuBpF,SAAS,aAAa,CAAC,KAAa;QAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,SAAS,mBAAmB,CAAC,KAAa;QACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;IAED,SAAS,cAAc,CAAC,KAAa;QACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,SAAS,SAAS,CAAC,KAAa;QAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACnC,CAAC;IAED,SAAS,UAAU,CAAC,KAAa;QAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,SAAS,gBAAgB,CAAC,KAAa;QACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;QACpC,OAAO,OAAO,CACZ,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,C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AC,CAAC,CAAC,CAAC;gBAE/B,IAAI,CAAC,IAAI;oBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;gBAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;oBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;iBAChC;gBAED,OAAO,IAAI,GAAG,SAAS,CAAC;aACzB;YAED;gBACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;YAE9B;gBACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;SACpF;IACH;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts new file mode 100644 index 0000000..b7f0b3b --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts @@ -0,0 +1,4 @@ +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/resolve-uri/package.json b/node_modules/@jridgewell/resolve-uri/package.json new file mode 100644 index 0000000..02a4c51 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/package.json @@ -0,0 +1,69 @@ +{ + "name": "@jridgewell/resolve-uri", + "version": "3.1.2", + "description": "Resolve a URI relative to an optional base URI", + "keywords": [ + "resolve", + "uri", + "url", + "path" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/resolve-uri", + "main": "dist/resolve-uri.umd.js", + "module": "dist/resolve-uri.mjs", + "types": "dist/types/resolve-uri.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/resolve-uri.d.ts", + "browser": "./dist/resolve-uri.umd.js", + "require": "./dist/resolve-uri.umd.js", + "import": "./dist/resolve-uri.mjs" + }, + "./dist/resolve-uri.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@jridgewell/resolve-uri-latest": "npm:@jridgewell/resolve-uri@*", + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/LICENSE b/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 0000000..a331065 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2015 Rich Harris + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@jridgewell/sourcemap-codec/README.md b/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 0000000..5cbb315 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,200 @@ +# @jridgewell/sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install @jridgewell/sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 5479160 bytes +sourcemap-codec 5659336 bytes +source-map-0.6.1 17144440 bytes +source-map-0.8.0 6867424 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 502 ops/sec ±1.03% (90 runs sampled) +decode: sourcemap-codec x 445 ops/sec ±0.97% (92 runs sampled) +decode: source-map-0.6.1 x 36.01 ops/sec ±1.64% (49 runs sampled) +decode: source-map-0.8.0 x 367 ops/sec ±0.04% (95 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 1261620 bytes +sourcemap-codec 9119248 bytes +source-map-0.6.1 8968560 bytes +source-map-0.8.0 8952952 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 738 ops/sec ±0.42% (98 runs sampled) +encode: sourcemap-codec x 238 ops/sec ±0.73% (88 runs sampled) +encode: source-map-0.6.1 x 162 ops/sec ±0.43% (84 runs sampled) +encode: source-map-0.8.0 x 191 ops/sec ±0.34% (90 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 35338184 bytes +sourcemap-codec 35922736 bytes +source-map-0.6.1 62366360 bytes +source-map-0.8.0 44337416 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 40.35 ops/sec ±4.47% (54 runs sampled) +decode: sourcemap-codec x 36.76 ops/sec ±3.67% (51 runs sampled) +decode: source-map-0.6.1 x 4.44 ops/sec ±2.15% (16 runs sampled) +decode: source-map-0.8.0 x 59.35 ops/sec ±0.05% (78 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +@jridgewell/sourcemap-codec 7212604 bytes +sourcemap-codec 21421456 bytes +source-map-0.6.1 25286888 bytes +source-map-0.8.0 25498744 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 112 ops/sec ±0.13% (84 runs sampled) +encode: sourcemap-codec x 30.23 ops/sec ±2.76% (53 runs sampled) +encode: source-map-0.6.1 x 19.43 ops/sec ±3.70% (37 runs sampled) +encode: source-map-0.8.0 x 19.40 ops/sec ±3.26% (37 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 500272 bytes +sourcemap-codec 516864 bytes +source-map-0.6.1 1596672 bytes +source-map-0.8.0 517272 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 16,137 ops/sec ±0.17% (99 runs sampled) +decode: sourcemap-codec x 12,139 ops/sec ±0.13% (99 runs sampled) +decode: source-map-0.6.1 x 1,264 ops/sec ±0.12% (100 runs sampled) +decode: source-map-0.8.0 x 9,894 ops/sec ±0.08% (101 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 321026 bytes +sourcemap-codec 830832 bytes +source-map-0.6.1 586608 bytes +source-map-0.8.0 586680 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 19,876 ops/sec ±0.78% (95 runs sampled) +encode: sourcemap-codec x 6,983 ops/sec ±0.15% (100 runs sampled) +encode: source-map-0.6.1 x 5,070 ops/sec ±0.12% (102 runs sampled) +encode: source-map-0.8.0 x 5,641 ops/sec ±0.17% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 734848 bytes +sourcemap-codec 954200 bytes +source-map-0.6.1 2276432 bytes +source-map-0.8.0 955488 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 5,723 ops/sec ±0.12% (98 runs sampled) +decode: sourcemap-codec x 4,555 ops/sec ±0.09% (101 runs sampled) +decode: source-map-0.6.1 x 437 ops/sec ±0.11% (93 runs sampled) +decode: source-map-0.8.0 x 3,441 ops/sec ±0.15% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 638672 bytes +sourcemap-codec 1109840 bytes +source-map-0.6.1 1321224 bytes +source-map-0.8.0 1324448 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 6,801 ops/sec ±0.48% (98 runs sampled) +encode: sourcemap-codec x 2,533 ops/sec ±0.13% (101 runs sampled) +encode: source-map-0.6.1 x 2,248 ops/sec ±0.08% (100 runs sampled) +encode: source-map-0.8.0 x 2,303 ops/sec ±0.15% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec +``` + +# License + +MIT diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 0000000..3dff372 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,164 @@ +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +// Provide a fallback for older environments. +const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +export { decode, encode }; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 0000000..236fd12 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.mjs","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport function decode(mappings: string): SourceMapMappings {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const decoded: SourceMapMappings = [];\n\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n\n for (let i = index; i < semi; i++) {\n let seg: SourceMapSegment;\n\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol) sorted = false;\n lastCol = col;\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n } else {\n seg = [col, state[1], state[2], state[3]];\n }\n } else {\n seg = [col];\n }\n\n line.push(seg);\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n\n return decoded;\n}\n\nfunction indexOf(mappings: string, index: number): number {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\n\nfunction decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n state[j] += value;\n return pos;\n}\n\nfunction hasMoreVlq(mappings: string, i: number, length: number): boolean {\n if (i >= length) return false;\n return mappings.charCodeAt(i) !== comma;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0) continue;\n\n state[0] = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0) buf[pos++] = comma;\n\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n\n if (segment.length === 1) continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n\n if (segment.length === 4) continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n\n return out + td.decode(buf.subarray(0, pos));\n}\n\nfunction encodeInteger(\n buf: Uint8Array,\n pos: number,\n state: SourceMapSegment,\n segment: SourceMapSegment,\n j: number,\n): number {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0) clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n\n return pos;\n}\n"],"names":[],"mappings":"AAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;AACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACjB,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;CAClB;AAED;AACA,MAAM,EAAE,GACN,OAAO,WAAW,KAAK,WAAW;sBACd,IAAI,WAAW,EAAE;MACjC,OAAO,MAAM,KAAK,WAAW;UAC7B;YAC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,CAAC;QAC7B,GAAG,MAAM,CAAC,CAAC;QACX,IAAI,GAAG,GAAG,CAAC;YAAE,OAAO,IAAI,QAAQ,CAAC;QACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;KACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;IAElB,OAAO,GAAG,CAAC;AACb;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..bec92a9 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,175 @@ +(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.sourcemapCodec = {})); +})(this, (function (exports) { 'use strict'; + + const comma = ','.charCodeAt(0); + const semicolon = ';'.charCodeAt(0); + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const intToChar = new Uint8Array(64); // 64 possible chars. + const charToInt = new Uint8Array(128); // z is 122 in ASCII + for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; + } + // Provide a fallback for older environments. + const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; + } + function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; + } + function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; + } + function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; + } + function sort(line) { + line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[0] - b[0]; + } + function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); + } + function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; + } + + exports.decode = decode; + exports.encode = encode; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..b6b2003 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.umd.js","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport function decode(mappings: string): SourceMapMappings {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const decoded: SourceMapMappings = [];\n\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n\n for (let i = index; i < semi; i++) {\n let seg: SourceMapSegment;\n\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol) sorted = false;\n lastCol = col;\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n } else {\n seg = [col, state[1], state[2], state[3]];\n }\n } else {\n seg = [col];\n }\n\n line.push(seg);\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n\n return decoded;\n}\n\nfunction indexOf(mappings: string, index: number): number {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\n\nfunction decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n state[j] += value;\n return pos;\n}\n\nfunction hasMoreVlq(mappings: string, i: number, length: number): boolean {\n if (i >= length) return false;\n return mappings.charCodeAt(i) !== comma;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0) continue;\n\n state[0] = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0) buf[pos++] = comma;\n\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n\n if (segment.length === 1) continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n\n if (segment.length === 4) continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n\n return out + td.decode(buf.subarray(0, pos));\n}\n\nfunction encodeInteger(\n buf: Uint8Array,\n pos: number,\n state: SourceMapSegment,\n segment: SourceMapSegment,\n j: number,\n): number {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0) clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n\n return pos;\n}\n"],"names":[],"mappings":";;;;;;IAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;IACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;IAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACjB,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClB;IAED;IACA,MAAM,EAAE,GACN,OAAO,WAAW,KAAK,WAAW;0BACd,IAAI,WAAW,EAAE;UACjC,OAAO,MAAM,KAAK,WAAW;cAC7B;gBACE,MAAM,CAAC,GAAe;oBACpB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;oBACpE,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;iBACvB;aACF;cACD;gBACE,MAAM,CAAC,GAAe;oBACpB,IAAI,GAAG,GAAG,EAAE,CAAC;oBACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;wBACnC,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,CAA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AK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;gBACjD,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;gBAEjD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;oBAAE,SAAS;gBACnC,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;aAClD;SACF;QAED,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;IAC/C,CAAC;IAED,SAAS,aAAa,CACpB,GAAe,EACf,GAAW,EACX,KAAuB,EACvB,OAAyB,EACzB,CAAS;QAET,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,GAAG,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAC1B,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;QAEhB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;QAC3C,GAAG;YACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;YAC7B,GAAG,MAAM,CAAC,CAAC;YACX,IAAI,GAAG,GAAG,CAAC;gBAAE,OAAO,IAAI,QAAQ,CAAC;YACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;SACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;QAElB,OAAO,GAAG,CAAC;IACb;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts new file mode 100644 index 0000000..410d320 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts @@ -0,0 +1,6 @@ +export declare type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export declare type SourceMapLine = SourceMapSegment[]; +export declare type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; diff --git a/node_modules/@jridgewell/sourcemap-codec/package.json b/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 0000000..578448f --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,74 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.4.15", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "types": "dist/types/sourcemap-codec.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": [ + { + "types": "./dist/types/sourcemap-codec.d.ts", + "browser": "./dist/sourcemap-codec.umd.js", + "require": "./dist/sourcemap-codec.umd.js", + "import": "./dist/sourcemap-codec.mjs" + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemap-codec.git" + }, + "author": "Rich Harris", + "license": "MIT", + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@types/node": "17.0.15", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.64.0", + "source-map": "0.6.1", + "source-map-js": "1.0.2", + "sourcemap-codec": "1.4.8", + "typescript": "4.5.4" + } +} diff --git a/node_modules/@jridgewell/trace-mapping/LICENSE b/node_modules/@jridgewell/trace-mapping/LICENSE new file mode 100644 index 0000000..37bb488 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/trace-mapping/README.md b/node_modules/@jridgewell/trace-mapping/README.md new file mode 100644 index 0000000..8286cee --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/README.md @@ -0,0 +1,193 @@ +# @jridgewell/trace-mapping + +> Trace the original position through a source map + +`trace-mapping` allows you to take the line and column of an output file and trace it to the +original location in the source file through a source map. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This +provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM. + +## Installation + +```sh +npm install @jridgewell/trace-mapping +``` + +## Usage + +```typescript +import { TraceMap, originalPositionFor, generatedPositionFor } from '@jridgewell/trace-mapping'; + +const tracer = new TraceMap({ + version: 3, + sources: ['input.js'], + names: ['foo'], + mappings: 'KAyCIA', +}); + +// Lines start at line 1, columns at column 0. +const traced = originalPositionFor(tracer, { line: 1, column: 5 }); +assert.deepEqual(traced, { + source: 'input.js', + line: 42, + column: 4, + name: 'foo', +}); + +const generated = generatedPositionFor(tracer, { + source: 'input.js', + line: 42, + column: 4, +}); +assert.deepEqual(generated, { + line: 1, + column: 5, +}); +``` + +We also provide a lower level API to get the actual segment that matches our line and column. Unlike +`originalPositionFor`, `traceSegment` uses a 0-base for `line`: + +```typescript +import { traceSegment } from '@jridgewell/trace-mapping'; + +// line is 0-base. +const traced = traceSegment(tracer, /* line */ 0, /* column */ 5); + +// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] +// Again, line is 0-base and so is sourceLine +assert.deepEqual(traced, [5, 0, 41, 4, 0]); +``` + +### SectionedSourceMaps + +The sourcemap spec defines a special `sections` field that's designed to handle concatenation of +output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool +produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap` +helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a +`TraceMap` instance: + +```typescript +import { AnyMap } from '@jridgewell/trace-mapping'; +const fooOutput = 'foo'; +const barOutput = 'bar'; +const output = [fooOutput, barOutput].join('\n'); + +const sectioned = new AnyMap({ + version: 3, + sections: [ + { + // 0-base line and column + offset: { line: 0, column: 0 }, + // fooOutput's sourcemap + map: { + version: 3, + sources: ['foo.js'], + names: ['foo'], + mappings: 'AAAAA', + }, + }, + { + // barOutput's sourcemap will not affect the first line, only the second + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['bar.js'], + names: ['bar'], + mappings: 'AAAAA', + }, + }, + ], +}); + +const traced = originalPositionFor(sectioned, { + line: 2, + column: 0, +}); + +assert.deepEqual(traced, { + source: 'bar.js', + line: 1, + column: 0, + name: 'bar', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map +trace-mapping: decoded JSON input x 183 ops/sec ±0.41% (87 runs sampled) +trace-mapping: encoded JSON input x 384 ops/sec ±0.89% (89 runs sampled) +trace-mapping: decoded Object input x 3,085 ops/sec ±0.24% (100 runs sampled) +trace-mapping: encoded Object input x 452 ops/sec ±0.80% (84 runs sampled) +source-map-js: encoded Object input x 88.82 ops/sec ±0.45% (77 runs sampled) +source-map-0.6.1: encoded Object input x 38.39 ops/sec ±1.88% (52 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 4,025,347 ops/sec ±0.15% (97 runs sampled) +trace-mapping: encoded originalPositionFor x 3,333,136 ops/sec ±1.26% (90 runs sampled) +source-map-js: encoded originalPositionFor x 824,978 ops/sec ±1.06% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 741,300 ops/sec ±0.93% (92 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 2,587,603 ops/sec ±0.75% (97 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +*** + +babel.min.js.map +trace-mapping: decoded JSON input x 17.43 ops/sec ±8.81% (33 runs sampled) +trace-mapping: encoded JSON input x 34.18 ops/sec ±4.67% (50 runs sampled) +trace-mapping: decoded Object input x 1,010 ops/sec ±0.41% (98 runs sampled) +trace-mapping: encoded Object input x 39.45 ops/sec ±4.01% (52 runs sampled) +source-map-js: encoded Object input x 6.57 ops/sec ±3.04% (21 runs sampled) +source-map-0.6.1: encoded Object input x 4.23 ops/sec ±2.93% (15 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 7,576,265 ops/sec ±0.74% (96 runs sampled) +trace-mapping: encoded originalPositionFor x 5,019,743 ops/sec ±0.74% (94 runs sampled) +source-map-js: encoded originalPositionFor x 3,396,137 ops/sec ±42.32% (95 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 3,753,176 ops/sec ±0.72% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 6,423,633 ops/sec ±0.74% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +*** + +preact.js.map +trace-mapping: decoded JSON input x 3,499 ops/sec ±0.18% (98 runs sampled) +trace-mapping: encoded JSON input x 6,078 ops/sec ±0.25% (99 runs sampled) +trace-mapping: decoded Object input x 254,788 ops/sec ±0.13% (100 runs sampled) +trace-mapping: encoded Object input x 14,063 ops/sec ±0.27% (94 runs sampled) +source-map-js: encoded Object input x 2,465 ops/sec ±0.25% (98 runs sampled) +source-map-0.6.1: encoded Object input x 1,174 ops/sec ±1.90% (95 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 7,720,171 ops/sec ±0.14% (97 runs sampled) +trace-mapping: encoded originalPositionFor x 6,864,485 ops/sec ±0.16% (101 runs sampled) +source-map-js: encoded originalPositionFor x 2,387,219 ops/sec ±0.28% (98 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 1,565,339 ops/sec ±0.32% (101 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 3,819,732 ops/sec ±0.38% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +*** + +react.js.map +trace-mapping: decoded JSON input x 1,719 ops/sec ±0.19% (99 runs sampled) +trace-mapping: encoded JSON input x 4,284 ops/sec ±0.51% (99 runs sampled) +trace-mapping: decoded Object input x 94,668 ops/sec ±0.08% (99 runs sampled) +trace-mapping: encoded Object input x 5,287 ops/sec ±0.24% (99 runs sampled) +source-map-js: encoded Object input x 814 ops/sec ±0.20% (98 runs sampled) +source-map-0.6.1: encoded Object input x 429 ops/sec ±0.24% (94 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 28,927,989 ops/sec ±0.61% (94 runs sampled) +trace-mapping: encoded originalPositionFor x 27,394,475 ops/sec ±0.55% (97 runs sampled) +source-map-js: encoded originalPositionFor x 16,856,730 ops/sec ±0.45% (96 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 12,258,950 ops/sec ±0.41% (97 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 22,272,990 ops/sec ±0.58% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor +``` + +[source-map]: https://www.npmjs.com/package/source-map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs new file mode 100644 index 0000000..8fce400 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs @@ -0,0 +1,514 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; +import resolveUri from '@jridgewell/resolve-uri'; + +function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; +const REV_GENERATED_LINE = 1; +const REV_GENERATED_COLUMN = 2; + +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +let found = false; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; i++, index++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; i--, index--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like +// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. +// Numeric properties on objects are magically sorted in ascending order by the engine regardless of +// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending +// order when iterating with for-in. +function buildNullArray() { + return { __proto__: null }; +} + +const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const { sections } = parsed; + let i = 0; + for (; i < sections.length - 1; i++) { + const no = sections[i + 1].offset; + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, no.line, no.column); + } + if (sections.length > 0) { + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, Infinity, Infinity); + } + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return presortedDecodedMap(joined); +}; +function addSection(section, mapUrl, mappings, sources, sourcesContent, names, stopLine, stopColumn) { + const map = AnyMap(section.map, mapUrl); + const { line: lineOffset, column: columnOffset } = section.offset; + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources } = map; + append(sources, resolvedSources); + append(sourcesContent, map.sourcesContent || fillSourcesContent(resolvedSources.length)); + append(names, map.names); + // If this section jumps forwards several lines, we need to add lines to the output mappings catch up. + for (let i = mappings.length; i <= lineOffset; i++) + mappings.push([]); + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. + const stopI = stopLine - lineOffset; + const len = Math.min(decoded.length, stopI + 1); + for (let i = 0; i < len; i++) { + const line = decoded[i]; + // On the 0th loop, the line will already exist due to a previous section, or the line catch up + // loop above. + const out = i === 0 ? mappings[lineOffset] : (mappings[lineOffset + i] = []); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (i === stopI && column >= stopColumn) + break; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + if (seg.length === 4) { + out.push([column, sourcesIndex, sourceLine, sourceColumn]); + continue; + } + out.push([column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); +} +// Sourcemaps don't need to have sourcesContent, and if they don't, we need to create an array of +// equal length to the sources. This is because the sources and sourcesContent are paired arrays, +// where `sourcesContent[i]` is the content of the `sources[i]` file. If we didn't, then joined +// sourcemap would desynchronize the sources/contents. +function fillSourcesContent(len) { + const sourcesContent = []; + for (let i = 0; i < len; i++) + sourcesContent[i] = null; + return sourcesContent; +} + +const INVALID_ORIGINAL_MAPPING = Object.freeze({ + source: null, + line: null, + column: null, + name: null, +}); +const INVALID_GENERATED_MAPPING = Object.freeze({ + line: null, + column: null, +}); +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +let encodedMappings; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +let traceSegment; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +let originalPositionFor; +/** + * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided + * the found mapping is from the same source and line as the originalPositionFor mapping. + * + * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1` + * using the same needle that would return `id` when calling `originalPositionFor`. + */ +let generatedPositionFor; +/** + * Iterates each mapping in generated position order. + */ +let eachMapping; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +let presortedDecodedMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let decodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let encodedMap; +class TraceMap { + constructor(map, mapUrl) { + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + const isString = typeof map === 'string'; + if (!isString && map.constructor === TraceMap) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + if (sourceRoot || mapUrl) { + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + } + else { + this.resolvedSources = sources.map((s) => s || ''); + } + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + } +} +(() => { + encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = encode(map._decoded))); + }; + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + traceSegment = (map, line, column) => { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + }; + originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return INVALID_ORIGINAL_MAPPING; + const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_ORIGINAL_MAPPING; + if (segment.length == 1) + return INVALID_ORIGINAL_MAPPING; + const { names, resolvedSources } = map; + return { + source: resolvedSources[segment[SOURCES_INDEX]], + line: segment[SOURCE_LINE] + 1, + column: segment[SOURCE_COLUMN], + name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null, + }; + }; + generatedPositionFor = (map, { source, line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return INVALID_GENERATED_MAPPING; + const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const memos = map._bySourceMemos; + const segments = generated[sourceIndex][line]; + if (segments == null) + return INVALID_GENERATED_MAPPING; + const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_GENERATED_MAPPING; + return { + line: segment[REV_GENERATED_LINE] + 1, + column: segment[REV_GENERATED_COLUMN], + }; + }; + eachMapping = (map, cb) => { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + presortedDecodedMap = (map, mapUrl) => { + const clone = Object.assign({}, map); + clone.mappings = []; + const tracer = new TraceMap(clone, mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + decodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: decodedMappings(map), + }; + }; + encodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: encodedMappings(map), + }; + }; +})(); +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return null; + return segments[index]; +} + +export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, originalPositionFor, presortedDecodedMap, traceSegment }; +//# sourceMappingURL=trace-mapping.mjs.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map new file mode 100644 index 0000000..fec7769 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.mjs","sources":["../../src/resolve.ts","../../src/strip-filename.ts","../../src/sourcemap-segment.ts","../../src/sort.ts","../../src/binary-search.ts","../../src/by-source.ts","../../src/any-map.ts","../../src/trace-mapping.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["bsFound"],"mappings":";;;SAEw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IA,KAAO,EAAE;QACX,KAAK,GAAG,CAAC,IAAI,KAAK,iBAAiB,GAAG,UAAU,GAAG,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;KACzF;SAAM,IAAI,IAAI,KAAK,iBAAiB;QAAE,KAAK,EAAE,CAAC;IAE/C,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,KAAK,KAAK,QAAQ,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IAC3D,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;AACzB;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js new file mode 100644 index 0000000..8b755bd --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js @@ -0,0 +1,528 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/sourcemap-codec'), require('@jridgewell/resolve-uri')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/sourcemap-codec', '@jridgewell/resolve-uri'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.traceMapping = {}, global.sourcemapCodec, global.resolveURI)); +})(this, (function (exports, sourcemapCodec, resolveUri) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var resolveUri__default = /*#__PURE__*/_interopDefaultLegacy(resolveUri); + + function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri__default["default"](input, base); + } + + /** + * Removes everything after the last "/", but leaves the slash. + */ + function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + const REV_GENERATED_LINE = 1; + const REV_GENERATED_COLUMN = 2; + + function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; + } + function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; + } + function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; + } + function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; + } + + let found = false; + /** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ + function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; + } + function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; i++, index++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; i--, index--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; + } + /** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ + function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); + } + + // Rebuilds the original source files, with mappings that are ordered by source line/column instead + // of generated line/column. + function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like + // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. + // Numeric properties on objects are magically sorted in ascending order by the engine regardless of + // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending + // order when iterating with for-in. + function buildNullArray() { + return { __proto__: null }; + } + + const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const { sections } = parsed; + let i = 0; + for (; i < sections.length - 1; i++) { + const no = sections[i + 1].offset; + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, no.line, no.column); + } + if (sections.length > 0) { + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, Infinity, Infinity); + } + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return exports.presortedDecodedMap(joined); + }; + function addSection(section, mapUrl, mappings, sources, sourcesContent, names, stopLine, stopColumn) { + const map = AnyMap(section.map, mapUrl); + const { line: lineOffset, column: columnOffset } = section.offset; + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = exports.decodedMappings(map); + const { resolvedSources } = map; + append(sources, resolvedSources); + append(sourcesContent, map.sourcesContent || fillSourcesContent(resolvedSources.length)); + append(names, map.names); + // If this section jumps forwards several lines, we need to add lines to the output mappings catch up. + for (let i = mappings.length; i <= lineOffset; i++) + mappings.push([]); + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. + const stopI = stopLine - lineOffset; + const len = Math.min(decoded.length, stopI + 1); + for (let i = 0; i < len; i++) { + const line = decoded[i]; + // On the 0th loop, the line will already exist due to a previous section, or the line catch up + // loop above. + const out = i === 0 ? mappings[lineOffset] : (mappings[lineOffset + i] = []); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (i === stopI && column >= stopColumn) + break; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + if (seg.length === 4) { + out.push([column, sourcesIndex, sourceLine, sourceColumn]); + continue; + } + out.push([column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } + } + function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); + } + // Sourcemaps don't need to have sourcesContent, and if they don't, we need to create an array of + // equal length to the sources. This is because the sources and sourcesContent are paired arrays, + // where `sourcesContent[i]` is the content of the `sources[i]` file. If we didn't, then joined + // sourcemap would desynchronize the sources/contents. + function fillSourcesContent(len) { + const sourcesContent = []; + for (let i = 0; i < len; i++) + sourcesContent[i] = null; + return sourcesContent; + } + + const INVALID_ORIGINAL_MAPPING = Object.freeze({ + source: null, + line: null, + column: null, + name: null, + }); + const INVALID_GENERATED_MAPPING = Object.freeze({ + line: null, + column: null, + }); + const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; + const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + const LEAST_UPPER_BOUND = -1; + const GREATEST_LOWER_BOUND = 1; + /** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ + exports.encodedMappings = void 0; + /** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ + exports.decodedMappings = void 0; + /** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ + exports.traceSegment = void 0; + /** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ + exports.originalPositionFor = void 0; + /** + * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided + * the found mapping is from the same source and line as the originalPositionFor mapping. + * + * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1` + * using the same needle that would return `id` when calling `originalPositionFor`. + */ + exports.generatedPositionFor = void 0; + /** + * Iterates each mapping in generated position order. + */ + exports.eachMapping = void 0; + /** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ + exports.presortedDecodedMap = void 0; + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.decodedMap = void 0; + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.encodedMap = void 0; + class TraceMap { + constructor(map, mapUrl) { + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + const isString = typeof map === 'string'; + if (!isString && map.constructor === TraceMap) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + if (sourceRoot || mapUrl) { + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + } + else { + this.resolvedSources = sources.map((s) => s || ''); + } + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + } + } + (() => { + exports.encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = sourcemapCodec.encode(map._decoded))); + }; + exports.decodedMappings = (map) => { + return (map._decoded || (map._decoded = sourcemapCodec.decode(map._encoded))); + }; + exports.traceSegment = (map, line, column) => { + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + }; + exports.originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return INVALID_ORIGINAL_MAPPING; + const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_ORIGINAL_MAPPING; + if (segment.length == 1) + return INVALID_ORIGINAL_MAPPING; + const { names, resolvedSources } = map; + return { + source: resolvedSources[segment[SOURCES_INDEX]], + line: segment[SOURCE_LINE] + 1, + column: segment[SOURCE_COLUMN], + name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null, + }; + }; + exports.generatedPositionFor = (map, { source, line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return INVALID_GENERATED_MAPPING; + const generated = (map._bySources || (map._bySources = buildBySources(exports.decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const memos = map._bySourceMemos; + const segments = generated[sourceIndex][line]; + if (segments == null) + return INVALID_GENERATED_MAPPING; + const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_GENERATED_MAPPING; + return { + line: segment[REV_GENERATED_LINE] + 1, + column: segment[REV_GENERATED_COLUMN], + }; + }; + exports.eachMapping = (map, cb) => { + const decoded = exports.decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + exports.presortedDecodedMap = (map, mapUrl) => { + const clone = Object.assign({}, map); + clone.mappings = []; + const tracer = new TraceMap(clone, mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + exports.decodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: exports.decodedMappings(map), + }; + }; + exports.encodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: exports.encodedMappings(map), + }; + }; + })(); + function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return null; + return segments[index]; + } + + exports.AnyMap = AnyMap; + exports.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND; + exports.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND; + exports.TraceMap = TraceMap; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=trace-mapping.umd.js.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map new file mode 100644 index 0000000..4ef72e7 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.umd.js","sources":["../../src/resolve.ts","../../src/strip-filename.ts","../../src/sourcemap-segment.ts","../../src/sort.ts","../../src/binary-search.ts","../../src/by-source.ts","../../src/any-map.ts","../../src/trace-mapping.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["resolveUri","presortedDecodedMap","decodedMappings","encodedMappings","traceSegment","originalPositionFor","generatedPositionFor","eachMapping","decodedMap","encodedMap","encode","decode","bsFound"],"mappings":";;;;;;;;;;aAEwB,OAAO,CAAC,KAAa,EAAE,IAAwB;;;;QAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,IAAI,IAAI,GAAG,CAAC;QAE7C,OAAOA,8BAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACjC;;ICTA;;;aAGwB,aAAa,CAAC,IAA+B;QACnE,IAAI,CAAC,IAAI;YAAE,OAAO,EAAE,CAAC;QACrB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IAClC;;ICQO,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IACtB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IAEtB,MAAM,kBAAkB,GAAG,CAAC,CAAC;IAC7B,MAAM,oBAAoB,GAAG,CAAC;;aClBb,SAAS,CAC/B,QAA8B,EAC9B,KAAc;QAEd,MAAM,aAAa,GAAG,uBAAuB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;QAC3D,IAAI,aAAa,KAAK,QAAQ,CAAC,MAAM;YAAE,OAAO,QAAQ,CAAC;;;QAIvD,IAAI,CAAC,KAAK;YAAE,QAAQ,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC;QAExC,KAAK,IAAI,CAAC,GAAG,aAAa,EAAE,CAAC,G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UAAU,EAAE,GAAG,CAAC,UAAU;gBAC1B,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,cAAc,EAAE,GAAG,CAAC,cAAc;gBAClC,QAAQ,EAAEN,uBAAe,CAAC,GAAG,CAAC;aAC/B,CAAC;SACH,CAAC;IACJ,CAAC,GAAA,CAAA;IAiBH,SAAS,oBAAoB,CAC3B,QAA+C,EAC/C,IAAe,EACf,IAAY,EACZ,MAAc,EACd,IAA4D;QAE5D,IAAI,KAAK,GAAG,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QAC/D,IAAIS,KAAO,EAAE;YACX,KAAK,GAAG,CAAC,IAAI,KAAK,iBAAiB,GAAG,UAAU,GAAG,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;SACzF;aAAM,IAAI,IAAI,KAAK,iBAAiB;YAAE,KAAK,EAAE,CAAC;QAE/C,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,KAAK,KAAK,QAAQ,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QAC3D,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts new file mode 100644 index 0000000..08bca6b --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts @@ -0,0 +1,8 @@ +import { TraceMap } from './trace-mapping'; +import type { SectionedSourceMapInput } from './types'; +declare type AnyMap = { + new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; + (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; +}; +export declare const AnyMap: AnyMap; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts new file mode 100644 index 0000000..88820e5 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts @@ -0,0 +1,32 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +export declare type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts new file mode 100644 index 0000000..8d1e538 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts @@ -0,0 +1,7 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; +import type { MemoState } from './binary-search'; +export declare type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: MemoState[]): Source[]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts new file mode 100644 index 0000000..cf7d4f8 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts @@ -0,0 +1 @@ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts new file mode 100644 index 0000000..2bfb5dc --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts @@ -0,0 +1,2 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..6d70924 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,16 @@ +declare type GeneratedColumn = number; +declare type SourcesIndex = number; +declare type SourceLine = number; +declare type SourceColumn = number; +declare type NamesIndex = number; +declare type GeneratedLine = number; +export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts new file mode 100644 index 0000000..bead5c1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts @@ -0,0 +1,4 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts new file mode 100644 index 0000000..8cd4574 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts @@ -0,0 +1,70 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping } from './types'; +export type { SourceMapSegment } from './sourcemap-segment'; +export type { SourceMapInput, SectionedSourceMapInput, DecodedSourceMap, EncodedSourceMap, SectionedSourceMap, InvalidOriginalMapping, OriginalMapping as Mapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, EachMapping, } from './types'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare let decodedMappings: (map: TraceMap) => Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare let traceSegment: (map: TraceMap, line: number, column: number) => Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare let originalPositionFor: (map: TraceMap, needle: Needle) => OriginalMapping | InvalidOriginalMapping; +/** + * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided + * the found mapping is from the same source and line as the originalPositionFor mapping. + * + * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1` + * using the same needle that would return `id` when calling `originalPositionFor`. + */ +export declare let generatedPositionFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping | InvalidGeneratedMapping; +/** + * Iterates each mapping in generated position order. + */ +export declare let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let decodedMap: (map: TraceMap) => Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let encodedMap: (map: TraceMap) => EncodedSourceMap; +export { AnyMap } from './any-map'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: SourceMapInput, mapUrl?: string | null); +} diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..2cc90c0 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts @@ -0,0 +1,85 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { TraceMap } from './trace-mapping'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export declare type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export declare type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export declare type GeneratedMapping = { + line: number; + column: number; +}; +export declare type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export declare type SourceMapInput = string | EncodedSourceMap | DecodedSourceMap | TraceMap; +export declare type SectionedSourceMapInput = SourceMapInput | SectionedSourceMap; +export declare type Needle = { + line: number; + column: number; + bias?: 1 | -1; +}; +export declare type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: 1 | -1; +}; +export declare type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; +} diff --git a/node_modules/@jridgewell/trace-mapping/package.json b/node_modules/@jridgewell/trace-mapping/package.json new file mode 100644 index 0000000..a957780 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/package.json @@ -0,0 +1,70 @@ +{ + "name": "@jridgewell/trace-mapping", + "version": "0.3.9", + "description": "Trace the original position through a source map", + "keywords": [ + "source", + "map" + ], + "main": "dist/trace-mapping.umd.js", + "module": "dist/trace-mapping.mjs", + "typings": "dist/types/trace-mapping.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": { + "browser": "./dist/trace-mapping.umd.js", + "require": "./dist/trace-mapping.umd.js", + "import": "./dist/trace-mapping.mjs" + }, + "./package.json": "./package.json" + }, + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/trace-mapping.git" + }, + "license": "MIT", + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node benchmark/index.mjs", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "ava debug", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts' '**/*.md'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "c8 ava", + "test:watch": "ava --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "ava": "4.0.1", + "benchmark": "2.1.4", + "c8": "7.11.0", + "esbuild": "0.14.14", + "esbuild-node-loader": "0.6.4", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.64.0", + "typescript": "4.5.4" + }, + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } +} diff --git a/node_modules/@types/node-forge/LICENSE b/node_modules/@types/node-forge/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/node-forge/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/node_modules/@types/node-forge/README.md b/node_modules/@types/node-forge/README.md new file mode 100644 index 0000000..cb19873 --- /dev/null +++ b/node_modules/@types/node-forge/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node-forge` + +# Summary +This package contains type definitions for node-forge (https://github.com/digitalbazaar/forge). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node-forge. + +### Additional Details + * Last updated: Tue, 02 Jan 2024 22:35:21 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [Seth Westphal ](https://github.com/westy92), [Kay Schecker ](https://github.com/flynetworks), [Aakash Goenka ](https://github.com/a-k-g), [Rafal2228 ](https://github.com/rafal2228), [Beeno Tung ](https://github.com/beenotung), [Joe Flateau ](https://github.com/joeflateau), [timhwang21 ](https://github.com/timhwang21), [Anders Kaseorg ](https://github.com/andersk), [Sascha Zarhuber ](https://github.com/saschazar21), [Rogier Schouten ](https://github.com/rogierschouten), [Ivan Aseev ](https://github.com/aseevia), [Wiktor Kwapisiewicz](https://github.com/wiktor-k), [Ligia Frangello ](https://github.com/frangello), [Dmitry Avezov ](https://github.com/avezov), [Jose Fuentes ](https://github.com/j-fuentes), [Anya Reyes ](https://github.com/darkade), and [BendingBender ](https://github.com/BendingBender). diff --git a/node_modules/@types/node-forge/index.d.ts b/node_modules/@types/node-forge/index.d.ts new file mode 100644 index 0000000..4f50ff5 --- /dev/null +++ b/node_modules/@types/node-forge/index.d.ts @@ -0,0 +1,1591 @@ +/// + +declare module "node-forge" { + type Byte = number; + type Bytes = string; + type Hex = string; + type Base64 = string; + type Utf8 = string; + type OID = string; + type Encoding = "raw" | "utf8"; + + namespace jsbn { + interface RandomGenerator { + nextBytes(bytes: number[]): void; + } + class BigInteger { + static ZERO: BigInteger; + static ONE: BigInteger; + constructor(a: null); + constructor(a: number, c: RandomGenerator); + constructor(a: number, b: number, c: RandomGenerator); + constructor(a: string, b?: number); + constructor(a: number[], b?: number); + constructor(a: BigInteger); + data: number[]; + t: number; + s: number; + am(i: number, x: number, w: BigInteger, j: number, c: number, n: number): number; + toString(b?: number): string; + bitLength(): number; + negate(): BigInteger; + abs(): BigInteger; + compareTo(a: BigInteger): number; + bitLength(): number; + mod(a: BigInteger): BigInteger; + modPowInt(e: number, m: BigInteger): BigInteger; + clone(): BigInteger; + intValue(): number; + byteValue(): number; + shortValue(): number; + signum(): number; + toByteArray(): number[]; + equals(a: BigInteger): boolean; + min(a: BigInteger): BigInteger; + max(a: BigInteger): BigInteger; + and(a: BigInteger): BigInteger; + or(a: BigInteger): BigInteger; + xor(a: BigInteger): BigInteger; + andNot(a: BigInteger): BigInteger; + not(): BigInteger; + shiftLeft(n: number): BigInteger; + shiftRight(n: number): BigInteger; + getLowestSetBit(): number; + bitCount(): number; + testBit(n: number): boolean; + clearBit(n: number): BigInteger; + flipBit(n: number): BigInteger; + add(a: BigInteger): BigInteger; + subtract(a: BigInteger): BigInteger; + multiply(a: BigInteger): BigInteger; + squareTo(a: BigInteger): BigInteger; + divide(a: BigInteger): BigInteger; + remainder(a: BigInteger): BigInteger; + divideAndRemainder(a: BigInteger): BigInteger[]; // Array of 2 items + pow(e: number): BigInteger; + modPow(e: BigInteger, m: BigInteger): BigInteger; + gcd(a: BigInteger): BigInteger; + modInverse(m: BigInteger): BigInteger; + isProbablePrime(t: number): boolean; + } + } + + namespace rc2 { + type pad_function = (blockSize: number, buffer: util.ByteBuffer, decrypt: boolean) => boolean; + interface cipher { + start(iv: util.ByteBuffer | string | null, output?: util.ByteBuffer): void; + update(input: util.ByteBuffer): void; + finish(pad?: pad_function): boolean; + output: util.ByteBuffer; + } + + function expandKey(key: string | util.ByteBuffer, effKeyBits?: number): util.ByteBuffer; + function startEncrypting( + key: string | util.ByteBuffer, + iv: util.ByteBuffer | Byte[] | Bytes, + output: util.ByteBuffer | null, + ): rc2.cipher; + function createEncryptionCipher(key: string | util.ByteBuffer, bits?: number): rc2.cipher; + function startDecrypting( + key: string | util.ByteBuffer, + iv: util.ByteBuffer | Byte[] | Bytes, + output: util.ByteBuffer | null, + ): rc2.cipher; + function createDecryptionCipher(key: string | util.ByteBuffer, bits?: number): rc2.cipher; + } + + namespace kem { + namespace rsa { + interface kem { + /** + * Generates a secret key and its encapsulation. + * + * @param publicKey the RSA public key to encrypt with. + * @param keyLength the length, in bytes, of the secret key to generate. + */ + encrypt(publicKey: pki.rsa.PublicKey, keyLength: number): EncryptResult; + /** + * Decrypts an encapsulated secret key. + * + * @param privateKey the RSA private key to decrypt with. + * @param encapsulation the ciphertext for generating the secret key, as a binary-encoded + * string of bytes. + * @param keyLength the length, in bytes, of the secret key to generate. + * + * @return the secret key as a binary-encoded string of bytes. + */ + decrypt(privateKey: pki.rsa.PrivateKey, encapsulation: string, keyLength: number): string; + } + + interface random { + getBytesSync(count: number): Bytes; + } + + interface Options { + /** + * A custom crypto-secure pseudo-random number generator to use. + */ + prng?: random | undefined; + } + + /** + * Creates an RSA KEM API object for generating a secret asymmetric key. + * + * The symmetric key may be generated via a call to 'encrypt', which will + * produce a ciphertext to be transmitted to the recipient and a key to be + * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which + * will produce the same secret key for the recipient to use to decrypt a + * message that was encrypted with the secret key. + * + * @param kdf the KDF API to use (eg: `new forge.kem.kdf1()`). + * @param options the options to use. + */ + function create(kdf: KDF, options?: Options): kem; + } + + interface EncryptResult { + /** + * The ciphertext for generating the secret key, as a binary-encoded string of bytes. + */ + encapsulation: string; + /** + * The secret key to use for encrypting a message. + */ + key: string; + } + + interface KDF { + /** + * Generate a key of the specified length. + * + * @param x the binary-encoded byte string to generate a key from. + * @param length the number of bytes to generate (the size of the key). + * + * @return the key as a binary-encoded string. + */ + generate(x: string, length: number): string; + } + + /** + * Creates a key derivation API object that implements KDF1 per ISO 18033-2. + * + * @param md the hash API to use. + * @param digestLength a digest length that must be positive and less than or equal to `md.digestLength`. + * + * @return a KDF1 API object. + */ + class kdf1 implements KDF { + constructor(md: md.MessageDigest, digestLength?: number); + /** + * Generate a key of the specified length. + * + * @param x the binary-encoded byte string to generate a key from. + * @param length the number of bytes to generate (the size of the key). + * + * @return the key as a binary-encoded string. + */ + generate(x: string, length: number): string; + } + + /** + * Creates a key derivation API object that implements KDF2 per ISO 18033-2. + * + * @param md the hash API to use. + * @param digestLength a digest length that must be positive and less than or equal to `md.digestLength`. + * + * @return a KDF2 API object. + */ + class kdf2 implements KDF { + constructor(md: md.MessageDigest, digestLength?: number); + /** + * Generate a key of the specified length. + * + * @param x the binary-encoded byte string to generate a key from. + * @param length the number of bytes to generate (the size of the key). + * + * @return the key as a binary-encoded string. + */ + generate(x: string, length: number): string; + } + } + + namespace pem { + interface EncodeOptions { + maxline?: number | undefined; + } + + interface ObjectPEM { + type: string; + body: Bytes; + procType?: any; + contentDomain?: any; + dekInfo?: any; + headers?: any[] | undefined; + } + + function encode(msg: ObjectPEM, options?: EncodeOptions): string; + function decode(str: string): ObjectPEM[]; + } + + namespace pki { + type PEM = string; + type PublicKey = rsa.PublicKey | ed25519.Key; + type PrivateKey = rsa.PrivateKey | ed25519.Key; + type EncryptionOptions = { + algorithm?: "aes128" | "aes192" | "aes256" | "3des" | undefined; + count?: number | undefined; + saltSize?: number | undefined; + prfAlgorithm?: "sha1" | "sha224" | "sha256" | "sha384" | "sha512" | undefined; + legacy?: boolean | undefined; + }; + + interface ByteBufferFingerprintOptions { + /** + * @description The type of fingerprint. If not specified, defaults to 'RSAPublicKey' + */ + type?: "SubjectPublicKeyInfo" | "RSAPublicKey" | undefined; + /** + * @description the delimiter to use between bytes for `hex` encoded output + */ + delimiter?: string | undefined; + /** + * @description if not specified defaults to `md.md5` + */ + md?: md.MessageDigest | undefined; + } + + interface HexFingerprintOptions extends ByteBufferFingerprintOptions { + /** + * @description if not specified, the function will return `ByteStringBuffer` + */ + encoding: "hex"; + } + + interface BinaryFingerprintOptions extends ByteBufferFingerprintOptions { + /** + * @description if not specified, the function will return `ByteStringBuffer` + */ + encoding: "binary"; + } + + interface KeyPair { + publicKey: PublicKey; + privateKey: PrivateKey; + } + + interface oids { + [key: string]: string; + } + var oids: oids; + + namespace rsa { + type EncryptionScheme = "RSAES-PKCS1-V1_5" | "RSA-OAEP" | "RAW" | "NONE" | null; + type SignatureScheme = "RSASSA-PKCS1-V1_5" | pss.PSS | "NONE" | null; + + interface PublicKey { + n: jsbn.BigInteger; + e: jsbn.BigInteger; + encrypt(data: Bytes, scheme?: EncryptionScheme, schemeOptions?: any): Bytes; + verify(digest: Bytes, signature: Bytes, scheme?: SignatureScheme): boolean; + } + + interface PrivateKey { + n: jsbn.BigInteger; + e: jsbn.BigInteger; + d: jsbn.BigInteger; + p: jsbn.BigInteger; + q: jsbn.BigInteger; + dP: jsbn.BigInteger; + dQ: jsbn.BigInteger; + qInv: jsbn.BigInteger; + decrypt(data: Bytes, scheme?: EncryptionScheme, schemeOptions?: any): Bytes; + sign(md: md.MessageDigest | Bytes, scheme?: SignatureScheme): Bytes; + } + + interface KeyPair { + publicKey: PublicKey; + privateKey: PrivateKey; + } + + interface GenerateKeyPairOptions { + bits?: number | undefined; + e?: number | undefined; + workerScript?: string | undefined; + workers?: number | undefined; + workLoad?: number | undefined; + prng?: any; + algorithm?: string | undefined; + } + + function setPublicKey(n: jsbn.BigInteger, e: jsbn.BigInteger): PublicKey; + + function setPrivateKey( + n: jsbn.BigInteger, + e: jsbn.BigInteger, + d: jsbn.BigInteger, + p: jsbn.BigInteger, + q: jsbn.BigInteger, + dP: jsbn.BigInteger, + dQ: jsbn.BigInteger, + qInv: jsbn.BigInteger, + ): PrivateKey; + + function generateKeyPair( + bits?: number, + e?: number, + callback?: (err: Error, keypair: KeyPair) => void, + ): KeyPair; + function generateKeyPair( + options?: GenerateKeyPairOptions, + callback?: (err: Error, keypair: KeyPair) => void, + ): KeyPair; + } + + namespace ed25519 { + type NativeBuffer = Buffer | Uint8Array; + type Key = NativeBuffer; + + type ToNativeBufferParameters = + | { + md: md.MessageDigest; + } + | { + message: NativeBuffer | util.ByteBuffer; + } + | { + message: string; + encoding: "binary" | "utf8"; + }; + + // `string`s will be converted by toNativeBuffer with `encoding: 'binary'` + type BinaryBuffer = NativeBuffer | util.ByteBuffer | string; + + namespace constants { + const PUBLIC_KEY_BYTE_LENGTH = 32; + const PRIVATE_KEY_BYTE_LENGTH = 64; + const SEED_BYTE_LENGTH = 32; + const SIGN_BYTE_LENGTH = 64; + const HASH_BYTE_LENGTH = 64; + } + + // generateKeyPair does not currently accept `util.ByteBuffer` as the seed. + function generateKeyPair(options?: { seed?: NativeBuffer | string | undefined }): { + publicKey: NativeBuffer; + privateKey: NativeBuffer; + }; + + function privateKeyFromAsn1(obj: asn1.Asn1): { privateKeyBytes: NativeBuffer }; + + function publicKeyFromAsn1(obj: asn1.Asn1): NativeBuffer; + + function publicKeyFromPrivateKey(options: { privateKey: BinaryBuffer }): NativeBuffer; + + function sign( + options: ToNativeBufferParameters & { + privateKey: BinaryBuffer; + }, + ): NativeBuffer; + + function verify( + options: ToNativeBufferParameters & { + signature: BinaryBuffer; + publicKey: BinaryBuffer; + }, + ): boolean; + } + + interface CertificateFieldOptions { + name?: string | undefined; + type?: string | undefined; + shortName?: string | undefined; + } + + interface CertificateField extends CertificateFieldOptions { + valueConstructed?: boolean | undefined; + valueTagClass?: asn1.Class | undefined; + value?: any[] | string | undefined; + extensions?: any[] | undefined; + } + + interface Certificate { + version: number; + serialNumber: string; + signatureOid: string; + signature: any; + siginfo: { + algorithmOid: string; + parameters: any; + }; + validity: { + notBefore: Date; + notAfter: Date; + }; + issuer: { + getField(sn: string | CertificateFieldOptions): any; + addField(attr: CertificateField): void; + attributes: CertificateField[]; + hash: any; + }; + subject: { + getField(sn: string | CertificateFieldOptions): any; + addField(attr: CertificateField): void; + attributes: CertificateField[]; + hash: any; + }; + extensions: any[]; + privateKey: PrivateKey; + publicKey: PublicKey; + md: md.MessageDigest; + signatureParameters: any; + tbsCertificate: asn1.Asn1; + /** + * Sets the subject of this certificate. + * + * @param attrs the array of subject attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + setSubject(attrs: CertificateField[], uniqueId?: string): void; + /** + * Sets the issuer of this certificate. + * + * @param attrs the array of subject attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + setIssuer(attrs: CertificateField[], uniqueId?: string): void; + /** + * Sets the extensions of this certificate. + * + * @param exts the array of extensions to use. + */ + setExtensions(exts: any[]): void; + /** + * Gets an extension by its name or id. + * + * @param options the name to use or an object with: + * name the name to use. + * id the id to use. + * + * @return the extension or null if not found. + */ + getExtension(options: string | { name: string } | { id: number }): {} | undefined; + + /** + * Signs this certificate using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + sign(key: pki.PrivateKey, md?: md.MessageDigest): void; + /** + * Attempts verify the signature on the passed certificate using this + * certificate's public key. + * + * @param child the certificate to verify. + * + * @return true if verified, false if not. + */ + verify(child: Certificate): boolean; + + /** + * Returns true if this certificate's issuer matches the passed + * certificate's subject. Note that no signature check is performed. + * + * @param parent the certificate to check. + * + * @return true if this certificate's issuer matches the passed certificate's + * subject. + */ + isIssuer(parent: Certificate): boolean; + + /** + * Returns true if this certificate's subject matches the issuer of the + * given certificate). Note that not signature check is performed. + * + * @param child the certificate to check. + * + * @return true if this certificate's subject matches the passed + * certificate's issuer. + */ + issued(child: Certificate): boolean; + + /** + * Generates the subjectKeyIdentifier for this certificate as byte buffer. + * + * @return the subjectKeyIdentifier for this certificate as byte buffer. + */ + generateSubjectKeyIdentifier(): util.ByteStringBuffer; + + /** + * Verifies the subjectKeyIdentifier extension value for this certificate + * against its public key. If no extension is found, false will be + * returned. + * + * @return true if verified, false if not. + */ + verifySubjectKeyIdentifier(): boolean; + } + + interface CertificateSigningRequest { + version: number; + signatureOid: string | null; + signature: any; + siginfo: { + algorithmOid: string | null; + }; + subject: { + getField(sn: string | CertificateFieldOptions): any; + addField(attr: CertificateField): void; + attributes: CertificateField[]; + hash: any; + }; + publicKey: PublicKey | null; + attributes: CertificateField[]; + /** + * Gets an issuer or subject attribute from its name, type, or short name. + * + * @param opts a short name string or an object with: + * shortName the short name for the attribute. + * name the name for the attribute. + * type the type for the attribute. + * + * @return the attribute. + */ + getAttribute(sn: string | GetAttributeOpts): Attribute | null; + addAttribute(attr: CertificateField): void; + md: md.MessageDigest | null; + signatureParameters: any; + certificationRequestInfo: asn1.Asn1 | null; + + /** + * Sets the subject of this csr. + * + * @param attrs the array of subject attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + setSubject(attrs: CertificateField[]): void; + setAttributes(attrs: CertificateField[]): void; + /** + * Signs this csr using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + sign(key: pki.PrivateKey, md?: md.MessageDigest): void; + /** + * Attempts verify the signature on this csr using this + * csr's public key. + * + * @return true if verified, false if not. + */ + verify(): boolean; + } + + /** + * Attribute members to search on; any one hit will return the attribute + */ + interface GetAttributeOpts { + /** + * OID + */ + type?: string | undefined; + /** + * Long name + */ + name?: string | undefined; + /** + * Short name + */ + shortName?: string | undefined; + } + + interface Attribute { + /** + * e.g. challengePassword + */ + name: string; + /** + * Short name, if available (e.g. 'CN' for 'commonName') + */ + shortName?: string | undefined; + /** + * OID, e.g. '1.2.840.113549.1.9.7' + */ + type: string; + /** + * Attribute value + */ + value: any; + /** + * Attribute value data type + */ + valueTagClass: number; + /** + * Extensions + */ + extensions?: any[] | undefined; + } + + interface CAStore { + addCertificate(cert: Certificate | string): void; + hasCertificate(cert: Certificate | string): boolean; + removeCertificate(cert: Certificate | string): Certificate | null; + listAllCertificates(): pki.Certificate[]; + getIssuer(subject: Certificate): Certificate | null; + getBySubject(subject: string): Certificate | null; + } + + function certificateFromAsn1(obj: asn1.Asn1, computeHash?: boolean): Certificate; + + function certificationRequestFromAsn1(obj: asn1.Asn1, computeHash?: boolean): CertificateSigningRequest; + + function certificateToAsn1(cert: Certificate): asn1.Asn1; + + function certificationRequestToAsn1(cert: CertificateSigningRequest): asn1.Asn1; + + function decryptRsaPrivateKey(pem: PEM, passphrase?: string): rsa.PrivateKey; + + function createCertificate(): Certificate; + + function certificationRequestToPem(csr: CertificateSigningRequest, maxline?: number): PEM; + + function certificationRequestFromPem( + pem: PEM, + computeHash?: boolean, + strict?: boolean, + ): CertificateSigningRequest; + + function createCertificationRequest(): CertificateSigningRequest; + + function certificateToPem(cert: Certificate, maxline?: number): PEM; + + function certificateFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; + + function createCaStore(certs?: ReadonlyArray): CAStore; + + function verifyCertificateChain( + caStore: CAStore, + chain: Certificate[], + options?: + | ((verified: boolean | string, depth: number, certs: Certificate[]) => boolean) + | { + verify?: + | ((verified: boolean | string, depth: number, certs: Certificate[]) => boolean) + | undefined; + validityCheckDate?: Date | null | undefined; + }, + ): boolean; + + function pemToDer(pem: PEM): util.ByteStringBuffer; + + function privateKeyToPem(key: PrivateKey, maxline?: number): PEM; + + function privateKeyInfoToPem(key: asn1.Asn1, maxline?: number): PEM; + + function publicKeyToPem(key: PublicKey, maxline?: number): PEM; + + function publicKeyToRSAPublicKeyPem(key: PublicKey, maxline?: number): PEM; + + function publicKeyFromPem(pem: PEM): rsa.PublicKey; + + function privateKeyFromPem(pem: PEM): rsa.PrivateKey; + + function decryptPrivateKeyInfo(obj: asn1.Asn1, password: string): asn1.Asn1; + + function encryptPrivateKeyInfo(obj: asn1.Asn1, password: string, options?: EncryptionOptions): asn1.Asn1; + + function encryptedPrivateKeyFromPem(pem: PEM): asn1.Asn1; + + function encryptedPrivateKeyToPem(obj: asn1.Asn1): PEM; + + function decryptRsaPrivateKey(pem: PEM, password: string): rsa.PrivateKey; + + function encryptRsaPrivateKey(privateKey: PrivateKey, password: string, options?: EncryptionOptions): PEM; + + function privateKeyFromAsn1(privateKey: asn1.Asn1): rsa.PrivateKey; + + function privateKeyToAsn1(privateKey: PrivateKey): asn1.Asn1; + + function publicKeyFromAsn1(publicKey: asn1.Asn1): rsa.PublicKey; + + function publicKeyToAsn1(publicKey: PublicKey): asn1.Asn1; + + function publicKeyToRSAPublicKey(publicKey: PublicKey): any; + + const setRsaPublicKey: typeof pki.rsa.setPublicKey; + + const setRsaPrivateKey: typeof pki.rsa.setPrivateKey; + + function wrapRsaPrivateKey(privateKey: asn1.Asn1): asn1.Asn1; + + function getPublicKeyFingerprint( + publicKey: PublicKey, + options?: ByteBufferFingerprintOptions, + ): util.ByteStringBuffer; + function getPublicKeyFingerprint(publicKey: PublicKey, options: HexFingerprintOptions): Hex; + function getPublicKeyFingerprint(publicKey: PublicKey, options: BinaryFingerprintOptions): Bytes; + } + + namespace random { + function getBytes(count: number, callback?: (err: Error | null, bytes: Bytes) => any): void; + function getBytesSync(count: number): Bytes; + type CB = (_: any, seed: string) => void; + interface Random { + seedFileSync: (needed: number) => string; + seedFile: (needed: number, cb: CB) => void; + } + function createInstance(): Random; + } + + namespace ssh { + interface FingerprintOptions { + /** + * @description the delimiter to use between bytes for `hex` encoded output + */ + delimiter?: string | undefined; + /** + * @description if not specified, the function will return `ByteStringBuffer` + */ + encoding?: "hex" | "binary" | undefined; + /** + * @description if not specified defaults to `md.md5` + */ + md?: md.MessageDigest | undefined; + } + + /** + * @description Encodes a private RSA key as an OpenSSH file + */ + function privateKeyToOpenSSH(privateKey: pki.PrivateKey, passphrase?: string): string; + + /** + * @description Encodes (and optionally encrypts) a private RSA key as a Putty PPK file + */ + function privateKeyToPutty(privateKey: pki.PrivateKey, passphrase?: string, comment?: string): string; + + /** + * @description Encodes a public RSA key as an OpenSSH file + */ + function publicKeyToOpenSSH(publicKey: pki.PublicKey, comment?: string): string | pki.PEM; + + /** + * @description Gets the SSH fingerprint for the given public key + */ + function getPublicKeyFingerprint( + publicKey: pki.PublicKey, + options?: FingerprintOptions, + ): util.ByteStringBuffer | Hex | string; + } + + namespace asn1 { + enum Class { + UNIVERSAL = 0x00, + APPLICATION = 0x40, + CONTEXT_SPECIFIC = 0x80, + PRIVATE = 0xc0, + } + + enum Type { + NONE = 0, + BOOLEAN = 1, + INTEGER = 2, + BITSTRING = 3, + OCTETSTRING = 4, + NULL = 5, + OID = 6, + ODESC = 7, + EXTERNAL = 8, + REAL = 9, + ENUMERATED = 10, + EMBEDDED = 11, + UTF8 = 12, + ROID = 13, + SEQUENCE = 16, + SET = 17, + PRINTABLESTRING = 19, + IA5STRING = 22, + UTCTIME = 23, + GENERALIZEDTIME = 24, + BMPSTRING = 30, + } + + interface Asn1 { + tagClass: Class; + type: Type; + constructed: boolean; + composed: boolean; + value: Bytes | Asn1[]; + } + + function create(tagClass: Class, type: Type, constructed: boolean, value: Bytes | Asn1[]): Asn1; + function fromDer(bytes: Bytes | util.ByteBuffer, strict?: boolean): Asn1; + function toDer(obj: Asn1): util.ByteBuffer; + + /** + * Converts an OID dot-separated string to a byte buffer. The byte buffer + * contains only the DER-encoded value, not any tag or length bytes. + * + * @param oid the OID dot-separated string. + * + * @return the byte buffer. + */ + function oidToDer(oid: OID): util.ByteBuffer; + + /** + * Converts a DER-encoded byte buffer to an OID dot-separated string. The + * byte buffer should contain only the DER-encoded value, not any tag or + * length bytes. + * + * @param bytes the byte buffer. + * + * @return the OID dot-separated string. + */ + function derToOid(bytes: Bytes | util.ByteBuffer): OID; + + function integerToDer(int: number): util.ByteBuffer; + function derToInteger(bytes: Bytes | util.ByteBuffer): number; + + function dateToUtcTime(date: Date | string): Bytes; + function utcTimeToDate(bytes: Bytes): Date; + + function dateToGeneralizedTime(date: Date | string): Bytes; + function generalizedTimeToDate(bytes: Bytes): Date; + } + + namespace util { + function isArray(x: any): boolean; + function isArrayBuffer(x: any): boolean; + function isArrayBufferView(x: any): boolean; + + interface ArrayBufferView { + buffer: ArrayBuffer; + byteLength: number; + } + + type ByteBuffer = ByteStringBuffer; + class ByteStringBuffer { + constructor(bytes?: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer); + data: string; + read: number; + length(): number; + isEmpty(): boolean; + putByte(byte: Byte): ByteStringBuffer; + fillWithByte(byte: Byte, n: number): ByteStringBuffer; + putBytes(bytes: Bytes): ByteStringBuffer; + putString(str: string): ByteStringBuffer; + putInt16(int: number): ByteStringBuffer; + putInt24(int: number): ByteStringBuffer; + putInt32(int: number): ByteStringBuffer; + putInt16Le(int: number): ByteStringBuffer; + putInt24Le(int: number): ByteStringBuffer; + putInt32Le(int: number): ByteStringBuffer; + putInt(int: number, numOfBits: number): ByteStringBuffer; + putSignedInt(int: number, numOfBits: number): ByteStringBuffer; + putBuffer(buffer: ByteStringBuffer): ByteStringBuffer; + getByte(): number; + getInt16(): number; + getInt24(): number; + getInt32(): number; + getInt16Le(): number; + getInt24Le(): number; + getInt32Le(): number; + getInt(numOfBits: number): number; + getSignedInt(numOfBits: number): number; + getBytes(count?: number): Bytes; + bytes(count?: number): Bytes; + at(index: number): Byte; + setAt(index: number, byte: number): ByteStringBuffer; + last(): Byte; + copy(): ByteStringBuffer; + compact(): ByteStringBuffer; + clear(): ByteStringBuffer; + truncate(): ByteStringBuffer; + toHex(): Hex; + toString(): string; + } + + function fillString(char: string, count: number): string; + function xorBytes(bytes1: string, bytes2: string, count: number): string; + function hexToBytes(hex: Hex): Bytes; + function bytesToHex(bytes: Bytes): Hex; + function int32ToBytes(int: number): Bytes; + function encode64(bytes: Bytes, maxline?: number): Base64; + function decode64(encoded: Base64): Bytes; + function encodeUtf8(str: string): Utf8; + function decodeUtf8(encoded: Utf8): string; + + function createBuffer(): ByteBuffer; + function createBuffer( + input: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer, + encoding?: Encoding, + ): ByteBuffer; + + namespace binary { + namespace raw { + function encode(x: Uint8Array): Bytes; + function decode(str: Bytes, output?: Uint8Array, offset?: number): Uint8Array; + } + namespace hex { + function encode(bytes: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer): Hex; + function decode(hex: Hex, output?: Uint8Array, offset?: number): Uint8Array; + } + namespace base64 { + function encode(input: Uint8Array, maxline?: number): Base64; + function decode(input: Base64, output?: Uint8Array, offset?: number): Uint8Array; + } + } + + namespace text { + namespace utf8 { + function encode(str: string, output?: Uint8Array, offset?: number): Uint8Array; + function decode(bytes: Uint8Array): Utf8; + } + namespace utf16 { + function encode(str: string, output?: Uint8Array, offset?: number): Uint8Array; + function decode(bytes: Uint8Array): string; + } + } + } + + namespace pkcs12 { + interface BagsFilter { + localKeyId?: string | undefined; + localKeyIdHex?: string | undefined; + friendlyName?: string | undefined; + bagType?: string | undefined; + } + + interface Bag { + type: string; + attributes: any; + key?: pki.PrivateKey | undefined; + cert?: pki.Certificate | undefined; + asn1: asn1.Asn1; + } + + interface Pkcs12Pfx { + version: string; + safeContents: Array<{ + encrypted: boolean; + safeBags: Bag[]; + }>; + getBags: (filter: BagsFilter) => { + [key: string]: Bag[] | undefined; + localKeyId?: Bag[] | undefined; + friendlyName?: Bag[] | undefined; + }; + getBagsByFriendlyName: (fiendlyName: string, bagType: string) => Bag[]; + getBagsByLocalKeyId: (localKeyId: string, bagType: string) => Bag[]; + } + + function pkcs12FromAsn1(obj: any, strict?: boolean, password?: string): Pkcs12Pfx; + function pkcs12FromAsn1(obj: any, password?: string): Pkcs12Pfx; + + function toPkcs12Asn1( + key: pki.PrivateKey | null, + cert: pki.Certificate | pki.Certificate[], + password: string | null, + options?: { + algorithm?: "aes128" | "aes192" | "aes256" | "3des" | undefined; + count?: number | undefined; + saltSize?: number | undefined; + useMac?: boolean | undefined; + localKeyId?: Hex | undefined; + friendlyName?: string | undefined; + generateLocalKeyId?: boolean | undefined; + }, + ): asn1.Asn1; + + function generateKey( + password: string | null | undefined, + salt: util.ByteBuffer, + id: Byte, + iter: number, + n: number, + md?: md.MessageDigest, + ): util.ByteBuffer; + } + + namespace pkcs7 { + interface PkcsSignedData { + content?: string | util.ByteBuffer | undefined; + contentInfo?: { value: any[] } | undefined; + + certificates: pki.Certificate[]; + + addCertificate(certificate: pki.Certificate | string): void; + addSigner(options: { + key: pki.rsa.PrivateKey | string; + certificate: pki.Certificate | string; + digestAlgorithm: string; + authenticatedAttributes?: Array<{ type: string; value?: string | undefined }> | undefined; + }): void; + sign(options?: { detached?: boolean | undefined }): void; + toAsn1(): asn1.Asn1; + } + + function createSignedData(): PkcsSignedData; + + interface Recipient { + version: number; + issuer: pki.CertificateField[]; + serialNumber: Hex; + encryptedContent: { + algorithm: OID; + parameter: Bytes; + content: Bytes; + }; + } + + interface PkcsEnvelopedData { + content?: string | util.ByteBuffer | undefined; + recipients: Recipient[]; + + /** + * Add (another) entity to list of recipients. + * + * @param certificate The certificate of the entity to add. + */ + addRecipient(certificate: pki.Certificate): void; + /** + * Encrypt enveloped content. + * + * This function supports two optional arguments, cipher and key, which + * can be used to influence symmetric encryption. Unless cipher is + * provided, the cipher specified in encryptedContent.algorithm is used + * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key + * is (re-)used. If that one's not set, a random key will be generated + * automatically. + * + * @param [key] The key to be used for symmetric encryption. + * @param [cipher] The OID of the symmetric cipher to use. + */ + encrypt(key?: util.ByteBuffer, cipher?: OID): void; + + /** + * Find recipient by X.509 certificate's issuer and serialNumber. + * + * @param cert the certificate with the issuer to look for. + * + * @return the recipient object, or `null` if no match. + */ + findRecipient(cert: pki.Certificate): Recipient | null; + /** + * Decrypt enveloped content + * + * @param recipient The recipient object related to the private key + * @param privKey The (RSA) private key object + */ + decrypt(recipient: Recipient, privKey: pki.rsa.PrivateKey): void; + + toAsn1(): asn1.Asn1; + } + + function createEnvelopedData(): PkcsEnvelopedData; + + /** When a PKCS#7 object has been created by reading from a message, the raw captured object is joined */ + type Captured = T & { + rawCapture: any; + }; + + /** + * Converts a PKCS#7 message to PEM format. + * + * @param msg The PKCS#7 message object + * @param maxline The maximum characters per line, defaults to 64. + * + * @return The PEM-formatted PKCS#7 message. + */ + function messageToPem(msg: PkcsSignedData, maxline?: number): string; + + /** + * Converts a PKCS#7 message from PEM format. + * + * @param pem the PEM-formatted PKCS#7 message. + * + * @return the PKCS#7 message. + */ + function messageFromPem(pem: pki.PEM): Captured; + + /** + * Converts a PKCS#7 message from an ASN.1 object. + * + * @param asn the ASN.1 representation of a ContentInfo. + * + * @return the PKCS#7 message. + */ + function messageFromAsn1(asn: asn1.Asn1): Captured; + } + + namespace pkcs5 { + function pbkdf2(password: string, salt: string, iterations: number, keySize: number): string; + function pbkdf2( + password: string, + salt: string, + iterations: number, + keySize: number, + messageDigest: md.MessageDigest | md.Algorithm, + ): string; + function pbkdf2( + password: string, + salt: string, + iterations: number, + keySize: number, + callback: (err: Error | null, dk: string | null) => any, + ): void; + function pbkdf2( + password: string, + salt: string, + iterations: number, + keySize: number, + messageDigest?: md.MessageDigest | md.Algorithm, + callback?: (err: Error | null, dk: string) => any, + ): void; + } + + const md: { + sha1: { + create(): md.sha1.MessageDigest; + }; + sha256: { + create(): md.sha256.MessageDigest; + }; + sha512: { + create( + /** @default 'SHA-512' */ + algorithm?: TAlg, + ): TAlg extends md.sha512.AlgorithmSelection.Sha384 ? md.sha512.Sha384MessageDigest + : TAlg extends md.sha512.AlgorithmSelection.Sha512224 ? md.sha512.Sha512224MessageDigest + : TAlg extends md.sha512.AlgorithmSelection.Sha512256 ? md.sha512.Sha512256MessageDigest + : TAlg extends md.sha512.AlgorithmSelection.Sha512 ? md.sha512.Sha512MessageDigest + : never; + sha224: { + create(): md.sha512.Sha512224MessageDigest; + }; + sha256: { + create(): md.sha512.Sha512256MessageDigest; + }; + sha384: { + create(): md.sha512.Sha384MessageDigest; + }; + }; + sha384: typeof md.sha512.sha384; + "sha512/224": typeof md.sha512.sha224; + "sha512/256": typeof md.sha512.sha256; + md5: { + create(): md.md5.MessageDigest; + }; + algorithms: { + md5: typeof md.md5; + sha1: typeof md.sha1; + sha256: typeof md.sha256; + sha384: typeof md.sha384; + sha512: typeof md.sha512; + "sha512/224": (typeof md)["sha512/224"]; + "sha512/256": (typeof md)["sha512/256"]; + }; + }; + + const md5: typeof md.md5; + const sha1: typeof md.sha1; + const sha256: typeof md.sha256; + const sha384: typeof md.sha384; + const sha512: typeof md.sha512; + + namespace md { + type Algorithm = md5.Algorithm | sha1.Algorithm | sha256.Algorithm | sha512.Algorithm; + + interface MessageDigest { + readonly algorithm: Algorithm; + readonly blockLength: number; + readonly digestLength: number; + messageLength: number; + fullMessageLength: number[] | null; + readonly messageLengthSize: number; + update(msg: string, encoding?: Encoding): this; + digest(): util.ByteStringBuffer; + } + + namespace md5 { + type Algorithm = "md5"; + + interface MessageDigest extends md.MessageDigest { + readonly algorithm: Algorithm; + readonly blockLength: 64; + readonly digestLength: 16; + readonly messageLengthSize: 8; + } + } + + namespace sha1 { + type Algorithm = "sha1"; + + interface MessageDigest extends md.MessageDigest { + readonly algorithm: Algorithm; + readonly blockLength: 64; + readonly digestLength: 20; + readonly messageLengthSize: 8; + } + } + + namespace sha256 { + type Algorithm = "sha256"; + + interface MessageDigest extends md.MessageDigest { + readonly algorithm: Algorithm; + readonly blockLength: 64; + readonly digestLength: 32; + readonly messageLengthSize: 8; + } + } + + namespace sha512 { + type Algorithm = Algorithm.Sha384 | Algorithm.Sha512 | Algorithm.Sha512224 | Algorithm.Sha512256; + namespace Algorithm { + type Sha384 = "sha384"; + type Sha512 = "sha512"; + type Sha512224 = "sha512/224"; + type Sha512256 = "sha512/256"; + } + + type AlgorithmSelection = + | AlgorithmSelection.Sha384 + | AlgorithmSelection.Sha512 + | AlgorithmSelection.Sha512224 + | AlgorithmSelection.Sha512256; + namespace AlgorithmSelection { + type Sha384 = "SHA-384"; + type Sha512 = "SHA-512"; + type Sha512224 = "SHA-512/224"; + type Sha512256 = "SHA-512/256"; + } + + interface MessageDigest extends md.MessageDigest { + readonly algorithm: Algorithm; + readonly blockLength: 128; + readonly messageLengthSize: 16; + } + + interface Sha512224MessageDigest extends MessageDigest { + readonly algorithm: Algorithm.Sha512224; + readonly digestLength: 28; + } + + interface Sha512256MessageDigest extends MessageDigest { + readonly algorithm: Algorithm.Sha512256; + readonly digestLength: 32; + } + + interface Sha384MessageDigest extends MessageDigest { + readonly algorithm: Algorithm.Sha384; + readonly digestLength: 48; + } + + interface Sha512MessageDigest extends MessageDigest { + readonly algorithm: Algorithm.Sha512; + readonly digestLength: 64; + } + } + } + + namespace hmac { + type Algorithm = md.Algorithm; + + interface HMAC { + digest(): util.ByteBuffer; + getMac(): util.ByteBuffer; + start(md: Algorithm | md.MessageDigest, key: string | util.ByteBuffer | null): void; + update(bytes: string): void; + } + + function create(): HMAC; + } + + namespace cipher { + type Algorithm = + | "AES-ECB" + | "AES-CBC" + | "AES-CFB" + | "AES-OFB" + | "AES-CTR" + | "AES-GCM" + | "3DES-ECB" + | "3DES-CBC" + | "DES-ECB" + | "DES-CBC"; + + function createCipher(algorithm: Algorithm, payload: util.ByteBuffer | Bytes): BlockCipher; + function createDecipher(algorithm: Algorithm, payload: util.ByteBuffer | Bytes): BlockCipher; + + interface StartOptions { + iv?: util.ByteBuffer | Byte[] | Bytes | undefined; + tag?: util.ByteStringBuffer | undefined; + tagLength?: number | undefined; + additionalData?: string | undefined; + } + + interface BlockCipher { + start: (options?: StartOptions) => void; + update: (payload: util.ByteBuffer) => void; + finish: () => boolean; + output: util.ByteStringBuffer; + mode: Mode; + } + + interface Mode { + tag: util.ByteStringBuffer; + } + } + + namespace pss { + type PSS = any; + + function create(any: any): PSS; + } + + namespace mgf { + namespace mgf1 { + function create(any: any): any; + } + } + + namespace tls { + interface ProtocolVersion { + major: Byte; + minor: Byte; + } + + const Versions: ProtocolVersion[]; + const SupportedVersions: ProtocolVersion[]; + const Version: ProtocolVersion; + + const MaxFragment: number; + + enum ConnectionEnd { + server = 0, + client = 1, + } + + enum PRFAlgorithm { + tls_prf_sha256 = 0, + } + + enum BulkCipherAlgorithm { + rc4 = 0, + des3 = 1, + aes = 2, + } + + enum CipherType { + stream = 0, + block = 1, + aead = 2, + } + + enum MACAlgorithm { + hmac_md5 = 0, + hmac_sha1 = 1, + hmac_sha256 = 2, + hmac_sha384 = 3, + hmac_sha512 = 4, + } + + enum CompressionMethod { + none = 0, + deflate = 1, + } + + enum ContentType { + change_cipher_spec = 20, + alert = 21, + handshake = 22, + application_data = 23, + heartbeat = 24, + } + + enum HandshakeType { + hello_request = 0, + client_hello = 1, + server_hello = 2, + certificate = 11, + server_key_exchange = 12, + certificate_request = 13, + server_hello_done = 14, + certificate_verify = 15, + client_key_exchange = 16, + finished = 20, + } + + namespace Alert { + enum Level { + warning = 1, + fatal = 2, + } + + enum Description { + close_notify = 0, + unexpected_message = 10, + bad_record_mac = 20, + decryption_failed = 21, + record_overflow = 22, + decompression_failure = 30, + handshake_failure = 40, + bad_certificate = 42, + unsupported_certificate = 43, + certificate_revoked = 44, + certificate_expired = 45, + certificate_unknown = 46, + illegal_parameter = 47, + unknown_ca = 48, + access_denied = 49, + decode_error = 50, + decrypt_error = 51, + export_restriction = 60, + protocol_version = 70, + insufficient_security = 71, + internal_error = 80, + user_canceled = 90, + no_renegotiation = 100, + } + } + + enum HeartbeatMessageType { + heartbeat_request = 1, + heartbeat_response = 2, + } + + interface CipherSuite { + id: [Byte, Byte]; + name: string; + } + + const CipherSuites: { [name: string]: CipherSuite }; + + interface CertificateRequest { + certificate_types: util.ByteBuffer; + certificate_authorities: util.ByteBuffer; + } + + type ConnectionState = any; + + interface Connection { + version: ProtocolVersion; + entity: ConnectionEnd; + sessionId: Bytes | null; + caStore: pki.CAStore; + sessionCache: SessionCache | null; + cipherSuites: CipherSuite[]; + connected(conn: Connection): void; + virtualHost: string | null; + verifyClient: boolean; + verify(conn: Connection, verified: Verified, depth: number, certs: pki.Certificate[]): Verified; + getCertificate: + | ((conn: Connection, hint: CertificateRequest | string[]) => pki.PEM | readonly pki.PEM[]) + | null; + getPrivateKey: ((conn: Connection, certificate: pki.Certificate) => pki.PEM) | null; + getSignature: + | ((conn: Connection, bytes: Bytes, callback: (conn: Connection, bytes: Bytes) => void) => void) + | null; + input: util.ByteBuffer; + tlsData: util.ByteBuffer; + data: util.ByteBuffer; + tlsDataReady(conn: Connection): void; + dataReady(conn: Connection): void; + heartbeatReceived: ((conn: Connection, payload: util.ByteBuffer) => void) | undefined; + closed(conn: Connection): void; + error(conn: Connection, error: TLSError): void; + deflate: ((inBytes: Bytes) => Bytes) | null; + inflate: ((inBytes: Bytes) => Bytes) | null; + reset(clearFail?: boolean): void; + record: Record | null; + session: Session | null; + peerCertificate: pki.Certificate | null; + state: { pending: ConnectionState | null; current: ConnectionState }; + expect: number; + fragmented: Record | null; + records: Record[]; + open: boolean; + handshakes: number; + handshaking: boolean; + isConnected: boolean; + fail: boolean; + handshake(sessionId?: Bytes | null): void; + process(data: Bytes): number; + prepare(data: Bytes): boolean; + prepareHeartbeatRequest(payload: Bytes | util.ByteBuffer, payloadLength?: number): boolean; + close(clearFail?: boolean): Connection; + } + + interface Record { + type: ContentType; + version: ProtocolVersion; + length: number; + fragment: util.ByteBuffer; + ready?: boolean | undefined; + } + + interface Session { + version: ProtocolVersion | null; + extensions: { [_: string]: object }; + cipherSuite: CipherSuite | null; + compressionMethod: CompressionMethod | null; + serverCertificate: pki.Certificate | null; + clientCertificate: pki.Certificate | null; + md5: md.MessageDigest; + sha1: md.MessageDigest; + } + + interface SessionCache { + cache: { [key: string]: Session }; + capacity: number; + order: [Hex]; + getSession(sessionId: Bytes): Session; + setSession(sessionId: Bytes, session: Session): void; + } + + function createSessionCache(cache?: SessionCache | { [key: string]: Session }, capacity?: number): SessionCache; + + interface Alert { + level: Alert.Level; + description: Alert.Description; + } + + interface TLSError extends Error { + message: string; + send: boolean; + origin: "server" | "client"; + alert: Alert; + } + + type Verified = true | { message?: string | undefined; alert?: Alert.Description | undefined }; + + function createConnection(options: { + server?: boolean | undefined; + sessionId?: Bytes | null | undefined; + caStore?: pki.CAStore | readonly pki.Certificate[] | undefined; + sessionCache?: SessionCache | { [key: string]: Session } | undefined; + cipherSuites?: CipherSuite[] | undefined; + connected(conn: Connection): void; + virtualHost?: string | undefined; + verifyClient?: boolean | undefined; + verify?(conn: Connection, verified: Verified, depth: number, certs: pki.Certificate[]): Verified; + getCertificate?(conn: Connection, hint: CertificateRequest | string[]): pki.PEM | readonly pki.PEM[]; + getPrivateKey?(conn: Connection, certificate: pki.Certificate): pki.PEM; + getSignature?(conn: Connection, bytes: Bytes, callback: (conn: Connection, bytes: Bytes) => void): void; + tlsDataReady(conn: Connection): void; + dataReady(conn: Connection): void; + heartbeatReceived?(conn: Connection, payload: util.ByteBuffer): void; + closed(conn: Connection): void; + error(conn: Connection, error: TLSError): void; + deflate?(inBytes: Bytes): Bytes; + inflate?(inBytes: Bytes): Bytes; + }): Connection; + + function prf_tls1(secret: string, label: string, seed: string, length: number): util.ByteBuffer; + + function hmac_sha1( + key: string | readonly Byte[] | util.ByteBuffer, + seqNum: [number, number], + record: Record, + ): Bytes; + } +} diff --git a/node_modules/@types/node-forge/package.json b/node_modules/@types/node-forge/package.json new file mode 100644 index 0000000..5c6f510 --- /dev/null +++ b/node_modules/@types/node-forge/package.json @@ -0,0 +1,107 @@ +{ + "name": "@types/node-forge", + "version": "1.3.11", + "description": "TypeScript definitions for node-forge", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node-forge", + "license": "MIT", + "contributors": [ + { + "name": "Seth Westphal ", + "githubUsername": "westy92", + "url": "https://github.com/westy92" + }, + { + "name": "Kay Schecker ", + "githubUsername": "flynetworks", + "url": "https://github.com/flynetworks" + }, + { + "name": "Aakash Goenka ", + "githubUsername": "a-k-g", + "url": "https://github.com/a-k-g" + }, + { + "name": "Rafal2228 ", + "githubUsername": "rafal2228", + "url": "https://github.com/rafal2228" + }, + { + "name": "Beeno Tung ", + "githubUsername": "beenotung", + "url": "https://github.com/beenotung" + }, + { + "name": "Joe Flateau ", + "githubUsername": "joeflateau", + "url": "https://github.com/joeflateau" + }, + { + "name": "timhwang21 ", + "githubUsername": "timhwang21", + "url": "https://github.com/timhwang21" + }, + { + "name": "Anders Kaseorg ", + "githubUsername": "andersk", + "url": "https://github.com/andersk" + }, + { + "name": "Sascha Zarhuber ", + "githubUsername": "saschazar21", + "url": "https://github.com/saschazar21" + }, + { + "name": "Rogier Schouten ", + "githubUsername": "rogierschouten", + "url": "https://github.com/rogierschouten" + }, + { + "name": "Ivan Aseev ", + "githubUsername": "aseevia", + "url": "https://github.com/aseevia" + }, + { + "name": "Wiktor Kwapisiewicz", + "githubUsername": "wiktor-k", + "url": "https://github.com/wiktor-k" + }, + { + "name": "Ligia Frangello ", + "githubUsername": "frangello", + "url": "https://github.com/frangello" + }, + { + "name": "Dmitry Avezov ", + "githubUsername": "avezov", + "url": "https://github.com/avezov" + }, + { + "name": "Jose Fuentes ", + "githubUsername": "j-fuentes", + "url": "https://github.com/j-fuentes" + }, + { + "name": "Anya Reyes ", + "githubUsername": "darkade", + "url": "https://github.com/darkade" + }, + { + "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/node-forge" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*" + }, + "typesPublisherContentHash": "1f94eadd96d1ed1e3b8513ff0af0af616821310570eb410699b93f6b3e3f3903", + "typeScriptVersion": "4.6" +} \ No newline at end of file diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/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/node_modules/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100644 index 0000000..9469bad --- /dev/null +++ b/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. + +### Additional Details + * Last updated: Wed, 08 May 2024 12:09:52 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), [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/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..08fada9 --- /dev/null +++ b/node_modules/@types/node/assert.d.ts @@ -0,0 +1,1040 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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 `node:assert` module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Set to the passed in operator value. + */ + operator: string; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + 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 deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. + * @since v14.2.0, v12.19.0 + * @deprecated Deprecated + */ + 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 'node: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 A function 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: undefined, arguments: [1, 2, 3] }]); + * ``` + * @since v18.8.0, v16.18.0 + * @return An array with all 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 'node: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); + * + * // Returns an array containing information on callsfunc() + * console.log(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 An array of objects containing information about the wrapper functions returned by {@link tracker.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 + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); + * + * tracker.reset(callsfunc); + * assert.strictEqual(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 {@link tracker.calls()} and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: 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 'node: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 'node: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 'node: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 'node: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: + * assert.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: + * assert.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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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](https://nodejs.org/docs/latest-v20.x/api/errors.html#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 `{@link AssertionError}` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node: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 'node: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](https://nodejs.org/docs/latest-v20.x/api/errors.html#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 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node: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 'node: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 `{@link 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](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) then it will be thrown instead of the `{@link 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 'node: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 `{@link 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](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, + * {@link deepEqual} will behave like {@link deepStrictEqual}. + * + * In strict assertion mode, error messages for objects display a diff. In legacy assertion mode, error + * messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert';COPY + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` environment variables. This will also + * deactivate the colors in the REPL. For more on color support in terminal environments, read the tty + * `getColorDepth()` documentation. + * + * @since v15.0.0, v13.9.0, v12.16.2, v9.9.0 + */ + namespace strict { + type AssertionError = assert.AssertionError; + type AssertPredicate = assert.AssertPredicate; + type CallTrackerCall = assert.CallTrackerCall; + type CallTrackerReportInformation = assert.CallTrackerReportInformation; + } + 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/node_modules/@types/node/assert/strict.d.ts b/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..f333913 --- /dev/null +++ b/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/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..9930a7e --- /dev/null +++ b/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,541 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v20.x/api/async_context.html#class-asynclocalstorage) tracks async context + * * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v20.x/api/process.html#processgetactiveresourcesinfo) tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * 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](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#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 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node: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 'node: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](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#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. + * + * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. + * @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 'node: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 'node: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. + * @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; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * 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 `node: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 'node:http'; + * import { AsyncLocalStorage } from 'node: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 v19.8.0 + * @experimental + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * 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. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @experimental + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * 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/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..53d62ad --- /dev/null +++ b/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2363 @@ +/** + * `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/v20.12.2/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 v19.4.0, 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 v19.6.0, 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" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "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 v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, 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" + | "utf-16le" + | "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 v19.8.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/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..f56ac79 --- /dev/null +++ b/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1542 @@ +/** + * The `node: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('node: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 `node: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/v20.12.2/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 `null` or `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('node:child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined`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` or `undefined`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 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('node:assert'); + * const fs = require('node:fs'); + * const child_process = require('node: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('node: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('node: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('node: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 v20.5.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('node: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('node:child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('node: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 `node:net` module,`node: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, 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('node: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('node: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('node: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('node: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('node: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('node: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('node: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 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('node: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; + stdout?: string; + stderr?: string; + } + /** + * 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('node: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('node: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('node:util'); + * const exec = util.promisify(require('node: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('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(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('node: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('node:util'); + * const execFile = util.promisify(require('node: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('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(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('node: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, 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/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..a2b86d1 --- /dev/null +++ b/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-v20.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/v20.12.2/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-v20.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v20.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-v20.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-v20.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-v20.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-v20.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-v20.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-v20.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-v20.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v20.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-v20.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-v20.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-v20.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/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..d0b0797 --- /dev/null +++ b/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-v20.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v20.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-v20.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/v20.12.2/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-v20.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-v20.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-v20.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-v20.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-v20.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-v20.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-v20.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-v20.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-v20.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v20.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-v20.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/v20.11.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-v20.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/node_modules/@types/node/constants.d.ts b/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..c3ac2b8 --- /dev/null +++ b/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/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..9c6843d --- /dev/null +++ b/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4522 @@ +/** + * The `node: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('node: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/v20.12.2/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. + * + * `` 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 `node: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/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node: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('node: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 'node:buffer'; + * const { Certificate } = await import('node: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-v20.x/docs/api/crypto.html#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; + /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ + const SSL_OP_ALLOW_NO_DHE_KEX: 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; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + /** Instructs OpenSSL to disable encrypt-then-MAC. */ + const SSL_OP_NO_ENCRYPT_THEN_MAC: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to disable renegotiation. */ + const SSL_OP_NO_RENEGOTIATION: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + /** Instructs OpenSSL to turn off SSL v2 */ + const SSL_OP_NO_SSLv2: number; + /** Instructs OpenSSL to turn off SSL v3 */ + const SSL_OP_NO_SSLv3: number; + /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ + const SSL_OP_NO_TICKET: number; + /** Instructs OpenSSL to turn off TLS v1 */ + const SSL_OP_NO_TLSv1: number; + /** Instructs OpenSSL to turn off TLS v1.1 */ + const SSL_OP_NO_TLSv1_1: number; + /** Instructs OpenSSL to turn off TLS v1.2 */ + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to turn off TLS v1.3 */ + const SSL_OP_NO_TLSv1_3: number; + /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ + const SSL_OP_PRIORITIZE_CHACHA: 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 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 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node: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`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node: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" | "utf-16le" | "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('node: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 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node: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('node: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('node: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?: HashOptions): 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('node: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 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node: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('node: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 { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * 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 v17.7.0, v16.15.0 + * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. + */ + 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`. + * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/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/man3.0/man3/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('node: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 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node: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('node: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. + * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/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/man3.0/man3/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 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node: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', () => { + * let chunk; + * 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 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node: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 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node: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('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @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('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @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('node: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('node: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 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node: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 unless they have been + * generated or computed already, 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. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @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`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @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 `node: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 listed in the documentation for `DiffieHellmanGroup`. + * + * 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('node: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. + * + * 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('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * 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`. + * + * 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('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * 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('node: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('node: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('node: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('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node: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 'node:buffer'; + * const { randomFillSync } = await import('node: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 'node:buffer'; + * const { randomFillSync } = await import('node: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 'node:buffer'; + * const { randomFill } = await import('node: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 'node:buffer'; + * const { randomFill } = await import('node: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('node: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('node: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('node: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('node: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('node: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 'node:assert'; + * + * const { + * createECDH, + * } = await import('node: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('node: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 compares the underlying bytes that represent the given`ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak 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. + * + * **When both of the inputs are `Float32Array`s or`Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor`Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * 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; + 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('node: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('node: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; + /** + * A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. 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: + * + * ```js + * const crypto = require('node:crypto'); + * const { Buffer } = require('node:buffer'); + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user + * could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead. + * @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v20.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest. + */ + function hash(algorithm: string, data: BinaryLike, outputEncoding?: BinaryToTextEncoding): string; + function hash(algorithm: string, data: BinaryLike, outputEncoding: "buffer"): Buffer; + function hash( + algorithm: string, + data: BinaryLike, + outputEncoding?: BinaryToTextEncoding | "buffer", + ): string | 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 'node:buffer'; + * const { + * hkdf, + * } = await import('node: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. Must be provided but can be zero-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 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node: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. Must be provided but can be zero-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('node: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. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, 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. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @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` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return 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; + } + } + + global { + var crypto: typeof globalThis extends { + crypto: infer T; + onmessage: any; + } ? T + : webcrypto.Crypto; + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..3b32bd8 --- /dev/null +++ b/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,596 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`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/v20.12.2/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 'node:cluster'; + * import dgram from 'node: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 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`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, v16.19.0 + * @return Number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return 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 'node:dgram'; + * import { Buffer } from 'node: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 'node:dgram'; + * import { Buffer } from 'node: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 'node:dgram'; + * import { Buffer } from 'node: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 additional 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 v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..c5b365e --- /dev/null +++ b/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,545 @@ +/** + * The `node: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 'node: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. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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 'node: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 publish to 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 'node: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 'node: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 {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node: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 + * @return `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 used 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 'node: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 'node: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 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} + * @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 'node: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 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} + * @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 v19.9.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 v19.9.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 v19.9.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 v19.9.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 v19.9.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 v19.9.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 v19.9.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 v19.9.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/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..92d23b8 --- /dev/null +++ b/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-v20.x/api/dns.html#implementation-considerations) for more information. + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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-v20.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-v20.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-v20.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-v20.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-v20.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-v20.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-v20.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-v20.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v20.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-v20.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-v20.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-v20.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v20.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-v20.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/node_modules/@types/node/dns/promises.d.ts b/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000..8256fcd --- /dev/null +++ b/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-v20.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-v20.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-v20.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-v20.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-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.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-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.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-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.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-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.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-v20.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/node_modules/@types/node/dom-events.d.ts b/node_modules/@types/node/dom-events.d.ts new file mode 100644 index 0000000..f47f71d --- /dev/null +++ b/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/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..6a2e4c4 --- /dev/null +++ b/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/v20.12.2/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 low-level 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('node:domain'); + * const fs = require('node: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/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..62d6e7e --- /dev/null +++ b/node_modules/@types/node/events.d.ts @@ -0,0 +1,884 @@ +/** + * 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 + * import { EventEmitter } from 'node: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/v20.12.2/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; + } + 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 `node:events` module: + * + * ```js + * import { EventEmitter } from 'node: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 + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * 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.error('error happened', err); + * } + * ``` + * + * 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 + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node: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: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * 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 + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * 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 An `AsyncIterator` 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 + * import { EventEmitter, listenerCount } from 'node: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 + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: EventTarget | 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 v19.9.0 + */ + static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node: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): 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 v20.5.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. + * @since v13.6.0, v12.17.0 + */ + static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ + static readonly captureRejectionSymbol: unique symbol; + /** + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property + * can be used. If this value is not a positive number, a `RangeError` is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_ `EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single + * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + 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 `events.EventEmitterAsyncResource` will run within its `async context`. + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @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 returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + 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 + * import { EventEmitter } from 'node:events'; + * 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 + * import { EventEmitter } from 'node:events'; + * 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 + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * 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 + * import { EventEmitter } from 'node:events'; + * 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(eventName?: 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 + * import { EventEmitter } from 'node:events'; + * 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 + * import { EventEmitter } from 'node: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 for 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 + * import { EventEmitter } from 'node: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/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..e68012d --- /dev/null +++ b/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4317 @@ +/** + * The `node: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 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node: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/v20.12.2/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}, {@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 its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, 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 v20.12.0 + */ + parentPath: string; + /** + * Alias for `dirent.parentPath`. + * @since v20.1.0 + * @deprecated Since v20.12.0 + */ + path: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node: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 fulfilled 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 fulfilled 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 'node: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 'node: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 'node: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 'node: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`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * 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 'node: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)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + 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)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + 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 a string, 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. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node: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 + * @param [type='null'] + */ + 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 + * @param [type='null'] + */ + 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 'node: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 (for instance, if it was previously 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. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./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 'node: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 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(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('node:path').sep`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node: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 'node: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 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + 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 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @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 + * @param [position='null'] + */ + 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 'node: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 'node: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 'node: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 'node: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 'node: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; + flush?: boolean | 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 'node:fs'; + * import { Buffer } from 'node: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 'node: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 'node:fs'; + * import { Buffer } from 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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. + */ + 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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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; + signal?: AbortSignal | null | 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; + flush?: boolean | undefined; + } + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `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 'node: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 'node: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 'node: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 'node: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 + * @param [position='null'] + */ + 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 + * @param [position='null'] + * @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 + * @param [position='null'] + */ + 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 + * @param [position='null'] + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + * @experimental + */ + export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + export interface OpenDirOptions { + /** + * @default 'utf8' + */ + 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; + /** + * @default false + */ + recursive?: boolean; + } + /** + * 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/node_modules/@types/node/fs/promises.d.ts b/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000..3199063 --- /dev/null +++ b/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1245 @@ +/** + * 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; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + /** + * Whether to open a normal or a `'bytes'` stream. + * @since v20.0.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 & { flush?: boolean | undefined }) + | 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 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `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 'node: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 'node: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 Fulfills 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. + * See `filehandle.createReadStream()` for the options. + * + * ```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 + */ + 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 'node: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 fulfills 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 an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled 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 fulfilled (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 & { flush?: boolean | undefined }) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled 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 fulfilled (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 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='null'] 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 fulfilled 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 fulfilled (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='null'] 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='null'] 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 'node: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 v20.4.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 fulfilled 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, constants } from 'node:fs/promises'; + * + * 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 { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('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.error('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. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @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 returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node: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 + * fulfilled 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'`. If the `type` argument is not a string, 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. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @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 v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + 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 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(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('node:path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system 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 an + * [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 'node:fs/promises'; + * import { Buffer } from 'node: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; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | 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 & { flush?: boolean | undefined }) | 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. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * 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 'node: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 'node: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('node: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/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..5f25006 --- /dev/null +++ b/node_modules/@types/node/globals.d.ts @@ -0,0 +1,411 @@ +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; +type _File = typeof globalThis extends { onmessage: any } ? {} : import("node:buffer").File; +// #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; + + /** + * is this an async call (i.e. await, Promise.all(), or Promise.any())? + */ + isAsync(): boolean; + + /** + * is this an async call to Promise.all()? + */ + isPromiseAll(): boolean; + + /** + * returns the index of the promise element that was followed in + * Promise.all() or Promise.any() for async stack traces, or null + * if the CallSite is not an async + */ + getPromiseIndex(): number | null; + + getScriptNameOrSourceURL(): string; + getScriptHash(): string; + + getEnclosingColumnNumber(): number; + getEnclosingLineNumber(): number; + getPosition(): number; + + toString(): string; + } + + 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 | globalThis.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; + + interface File extends _File {} + var File: typeof globalThis extends { + onmessage: any; + File: infer T; + } ? T + : typeof import("node:buffer").File; +} diff --git a/node_modules/@types/node/globals.global.d.ts b/node_modules/@types/node/globals.global.d.ts new file mode 100644 index 0000000..ef1198c --- /dev/null +++ b/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..6953c74 --- /dev/null +++ b/node_modules/@types/node/http.d.ts @@ -0,0 +1,1889 @@ +/** + * To use the HTTP server and client one must `require('node: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: + * + * ```json + * { "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/v20.12.2/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + 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 v20.1.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 outgoing message from + * the perspective of the participants of an 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; + /** + * Alias 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. 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 to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple + * times. + * + * If there were no previous values for the header, this is equivalent to 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 the HTTP header with the given name. If that header is not + * set, the returned value 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 containing the unique names of the current outgoing headers. + * 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 will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names 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; + /** + * 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 message. + * @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 read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will 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 \[`Error`\]\[\] being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a 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. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the`Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @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 + * import http from 'node: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 + * import http from 'node: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.headers); + * ``` + * + * 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. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `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.headers.host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `request.headers.host` is`'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.headers.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. + * + * ```js + * import http from 'node:http'; + * + * // 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); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @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 + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * 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'`, or the error with which `req.destroy()` was called + * * `'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'`, or the error with which `req.destroy()` was called + * * `'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'`, or the error with which `req.destroy()` was called + * * `'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. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'`and the `cause`, if one was provided. + * @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 by default 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 set to GET by default. + */ + 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'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + 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'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: 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/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..2fb2d6a --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2418 @@ +/** + * The `node: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('node:http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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('node: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('node: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('node: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('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. 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('node: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('node:http2'); + * const fs = require('node: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('node:http2'); + * const fs = require('node: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('node: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.error(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('node: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('node: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('node: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('node: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('node: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('node: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('node: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; + remoteCustomSettings?: number[] | 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; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * 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('node: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 `node: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, + * }); + * ``` + * @since v18.11.0 + */ + 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('node: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('node: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(8000); + * ``` + * @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('node:http2'); + * const fs = require('node: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(8443); + * ``` + * @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('node: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; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + export function performServerHandshake(socket: stream.Duplex, options?: ServerOptions): ServerHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..797202a --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,550 @@ +/** + * 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/v20.12.2/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('node:https'); + * const fs = require('node: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('node:https'); + * const fs = require('node: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('node: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('node:tls'); + * const https = require('node:https'); + * const crypto = require('node: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-sha256 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('node: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/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..f043abe --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,89 @@ +/** + * 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/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..5395db6 --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2746 @@ +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * + * It can be accessed using: + * + * ```js + * import * as inspector from 'node:inspector/promises'; + * ``` + * + * or + * + * ```js + * import * as inspector from 'node:inspector'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + /** + * 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/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..c38a9b8 --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,315 @@ +/** + * @since v0.3.7 + * @experimental + */ +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('node:fs'); + * const assert = require('node:assert'); + * const { syncBuiltinESMExports } = require('node:module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node: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 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + 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 { + /** + * The directory name of the current module. This is the same as the `path.dirname()` of the `import.meta.filename`. + * **Caveat:** only present on `file:` modules. + */ + dirname: string; + /** + * The full absolute path and filename of the current module, with symlinks resolved. + * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. + * **Caveat:** only local modules support this property. Modules not using the `file:` protocol will not provide it. + */ + filename: string; + /** + * The absolute `file:` URL of the module. + */ + url: string; + /** + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * Second `parent` parameter is only used when the `--experimental-import-meta-resolve` + * command flag enabled. + * + * @since v20.6.0 + * + * @param specifier The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. + * @returns The absolute (`file:`) URL string for the resolved module. + */ + resolve(specifier: string, parent?: string | URL | undefined): string; + } + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..3010c1d --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,996 @@ +/** + * > Stability: 2 - Stable + * + * The `node: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('node:net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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, v16.17.0 + */ + 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 is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * 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 v11.2.0, 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, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @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'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @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. connectionAttempt + * 4. connectionAttemptFailed + * 5. connectionAttemptTimeout + * 6. data + * 7. drain + * 8. end + * 9. error + * 10. lookup + * 11. ready + * 12. 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: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + addListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => 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: "connectionAttempt", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptFailed", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): 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: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + on(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this; + on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => 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: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => 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: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + prependListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => 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: "connectionAttempt", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => 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.error('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 + */ + readonly 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 v20.5.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('node: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`: + * + * ```bash + * 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: + * + * ```bash + * 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; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250`. + * @since v19.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @since v19.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * 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); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @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/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..b727c3e --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,495 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('node:os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + 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 array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * 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. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @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 v19.4.0, v18.14.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`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-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 dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: 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; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`,`'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, + * and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v20.x/api/process.html#processarch). + * @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`, `arm64`, `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, v16.18.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/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100644 index 0000000..3347f13 --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,217 @@ +{ + "name": "@types/node", + "version": "20.12.11", + "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": "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": "3c6750c01df9bf9654e033bbfe80e7598cdc02093dff2896bca92bc4e1911134", + "typeScriptVersion": "4.7" +} \ No newline at end of file diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..e98c7c3 --- /dev/null +++ b/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 `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * const path = require('node:path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..6ba48e0 --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,645 @@ +/** + * 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/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * const { PerformanceObserver, performance } = require('node: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/v20.12.2/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http" | "dns" | "net"; + 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; + } + /** + * The constructor of this class is not exposed to users directly. + * @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; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + 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('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * 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('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * 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('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * 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; + /** + * @since v8.5.0 + */ + 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('node: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 + */ + 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('node: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/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..ac7233f --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,1747 @@ +declare module "process" { + import * as net from "node:net"; + import * as os from "node:os"; + 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 { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + 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" + | "loong64" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "riscv64" + | "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]; + /** + * The `bigint` version of the `{@link hrtime()}` method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike `{@link hrtime()}`, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + 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 'node: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; + }; + /** + * 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 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * 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. + * + * ```bash + * 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 'node: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 'node: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 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v20.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * 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 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node: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, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @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: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node: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 'node: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 'node: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 'node: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. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @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 'node: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 'node: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 'node: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. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null | undefined): 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`. + * @default undefined + * @since v0.11.8 + */ + exitCode?: number | string | number | undefined; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * 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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node: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 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `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_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @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 'node: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; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: string | URL | Buffer): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node: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 'node: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'`, `'loong64'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node: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 'node: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. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + * @experimental + */ + 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 'node: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 'node: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 'node: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 'node: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; + /** + * This API is available through the [--experimental-permission](https://nodejs.org/api/cli.html#--experimental-permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * 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: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/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?: { + keepOpen?: 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 'node: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 'node: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 initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * 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/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..e947711 --- /dev/null +++ b/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/v20.12.2/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/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..900b9c4 --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,153 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('node: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/v20.12.2/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + 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: + * + * ```json + * { + * "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/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..a69c667 --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,540 @@ +/** + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v20.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdin)) 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 `node: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/v20.12.2/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](https://nodejs.org/docs/latest-v20.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v20.x/api/stream.html#writable-streams) 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-v20.x/docs/api/readline.html#class-interfaceconstructor + */ + 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-v20.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.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 `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 `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 `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. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * 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); + * ``` + * @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 `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 `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 `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 `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('node: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 an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `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('node: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('node:fs'); + * const readline = require('node: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('node:fs'); + * const readline = require('node: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('node:events'); + * const { createReadStream } = require('node:fs'); + * const { createInterface } = require('node: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](https://nodejs.org/docs/latest-v20.x/api/tty.html) 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](https://nodejs.org/docs/latest-v20.x/api/tty.html) 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](https://nodejs.org/docs/latest-v20.x/api/tty.html) `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](https://nodejs.org/docs/latest-v20.x/api/tty.html) `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 moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/node_modules/@types/node/readline/promises.d.ts b/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..f2826bb --- /dev/null +++ b/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,150 @@ +/** + * @since v17.0.0 + * @experimental + */ +declare module "readline/promises" { + import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; + import { Abortable } from "node:events"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.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 v17.0.0 + */ + 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 `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. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + 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. + * @since v17.0.0 + * @return this + */ + 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. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + 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. + * @since v17.0.0 + * @return this + */ + 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. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + 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). + * @since v17.0.0 + */ + 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/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..d7f8962 --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,430 @@ +/** + * The `node: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('node:repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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-v20.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v20.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-v20.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-v20.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('node: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-v20.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-v20.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-v20.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-v20.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-v20.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-v20.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('node: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('node: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-v20.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/node_modules/@types/node/sea.d.ts b/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000..6f1d1ea --- /dev/null +++ b/node_modules/@types/node/sea.d.ts @@ -0,0 +1,153 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.12.0/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): string | ArrayBuffer; +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..c070861 --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1703 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node: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 `node:stream` module: + * + * ```js + * const stream = require('node:stream'); + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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; + } + import Stream = internal.Stream; + import Readable = internal.Readable; + import ReadableOptions = internal.ReadableOptions; + 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; + } + class ReadableBase extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * 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('node: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('node: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 `node: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('node: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 v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + import WritableOptions = internal.WritableOptions; + class WritableBase extends Stream implements NodeJS.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('node: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; + } + 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; + } + /** + * @since v0.9.4 + */ + class Readable extends ReadableBase { + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + } + 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 WritableBase { + /** + * 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; + } + 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 ReadableBase implements WritableBase { + 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 `true`. + * + * 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; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * 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 {} + /** + * A stream to attach a signal to. + * + * 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, and `controller.error(new + * AbortError())` for webstreams. + * + * ```js + * const fs = require('node: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; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @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 v19.9.0 + * @param objectMode + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.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 readable and/or writable stream/webstream. + * + * 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('node:stream'); + * const fs = require('node:fs'); + * + * 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`. + * + * `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('node:stream'); + * const fs = require('node:fs'); + * const zlib = require('node: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`. + * + * `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('node:fs'); + * const http = require('node:http'); + * const { pipeline } = require('node: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, v16.14.0 + * @experimental + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + * @experimental + */ + 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/node_modules/@types/node/stream/consumers.d.ts b/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..5ad9cba --- /dev/null +++ b/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/node_modules/@types/node/stream/promises.d.ts b/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..6eac5b7 --- /dev/null +++ b/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/node_modules/@types/node/stream/web.d.ts b/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..8dd0ded --- /dev/null +++ b/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,367 @@ +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 ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value?: T; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + 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; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + 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; + from(iterable: Iterable | AsyncIterable): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + read(view: T): 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: "deflate" | "deflate-raw" | "gzip"): CompressionStream; + }; + interface DecompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; + }; +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..a8952a9 --- /dev/null +++ b/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/v20.12.2/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/node_modules/@types/node/test.d.ts b/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..2bafdcd --- /dev/null +++ b/node_modules/@types/node/test.d.ts @@ -0,0 +1,1470 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/lib/test.js) + */ +declare module "node:test" { + import { Readable } from "node:stream"; + import { AsyncResource } from "node:async_hooks"; + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. The following properties are supported: + */ + 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 `TestsStream`. + * + * The `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 `Promise` that fulfills once the test completes. + * if `test()` is called within a `describe()` block, it fulfills immediately. + * 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); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param [name='The name'] The name of the test, which is displayed when reporting test results. + * @param options Configuration options for the test. The following properties are supported: + * @param [fn='A no-op function'] 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. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within {@link describe}. + */ + 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 }; + } + /** + * The `describe()` function imported from the `node:test` module. Each + * invocation of this function results in the creation of a Subtest. + * After invocation of top level `describe` functions, + * all top level tests and suites will execute. + * @param [name='The name'] The name of the suite, which is displayed when reporting test results. + * @param options Configuration options for the suite. supports the same options as `test([name][, options][, fn])`. + * @param [fn='A no-op function'] The function under suite declaring all subtests and subsuites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + */ + 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; + } + /** + * Shorthand for `test()`. + * + * The `it()` function is imported from the `node:test` module. + * @since v18.6.0, v16.17.0 + */ + 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 v20.2.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 v20.2.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 v20.2.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) => void | Promise; + /** + * 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 + */ + 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. + * @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 to `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 definition + * @since v18.9.0, v16.19.0 + */ + class TestsStream extends Readable implements 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, v16.17.0 + */ + class 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 v20.1.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='A no-op function'] 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. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The name of the test. + * @since v18.8.0, v16.18.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. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.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. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + 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. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + 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. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after running a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running + * before each subtest of the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running + * after each subtest of the current test. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + 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]; + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + class MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param [original='A no-op function'] 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. The following properties are supported: + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked 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. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @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. The following properties are supported: + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked 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 `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + 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 `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + 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. + * @since v19.1.0, v18.13.0 + */ + 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. + * @since v19.1.0, v18.13.0 + */ + 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; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + class MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + 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. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @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. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @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. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + type Timer = "setInterval" | "setTimeout" | "setImmediate" | "Date"; + + interface MockTimersOptions { + apis: Timer[]; + now?: number | Date; + } + /** + * 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 MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.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. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. + * Note: This method will execute any mocked timers that are in the past from the new time. + * In the below example we are setting a new time for the mocked date. + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * test('sets the time of a date object', (context) => { + * // Optionally choose what to mock + * context.mock.timers.enable({ apis: ['Date'], now: 100 }); + * assert.strictEqual(Date.now(), 100); + * // Advance in time will also advance the date + * context.mock.timers.setTime(1000); + * context.mock.timers.tick(200); + * assert.strictEqual(Date.now(), 1200); + * }); + * ``` + */ + setTime(time: number): 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 v20.4.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({ apis: ['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({ apis: ['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); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```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({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * 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({ apis: ['setTimeout', 'Date'] }); + * 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]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **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 v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + export { + after, + afterEach, + before, + beforeEach, + describe, + it, + Mock, + mock, + only, + run, + skip, + SuiteContext, + test, + test as default, + TestContext, + todo, + }; +} + +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 20.0.0, 19.9.0, 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 20.0.0, 19.9.0, 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 v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } 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; + class Lcov extends Transform { + constructor(opts?: TransformOptions); + } + export { dot, junit, Lcov as lcov, Spec as spec, tap, TestEvent }; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..4e37b8e --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,240 @@ +/** + * 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('node: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/v20.12.2/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; + } + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` functions that can be used to + * control this default behavior. + */ + class Immediate implements RefCounted { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @return a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` 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 `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @return a reference to `immediate` + */ + unref(): this; + /** + * 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 v20.5.0 + */ + [Symbol.dispose](): void; + } + /** + * This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the + * scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + class Timeout implements Timer { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @return a reference to `timeout` + */ + ref(): this; + /** + * When called, the active `Timeout` 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 `Timeout` object's callback is invoked. Calling `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @return a reference to `timeout` + */ + unref(): this; + /** + * 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 v20.5.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` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearTimeout} + */ + 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; + } + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * 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` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearInterval} + */ + 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; + } + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of the Node.js `Event Loop` + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearImmediate} + */ + 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; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by {@link setImmediate}. + */ + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/node_modules/@types/node/timers/promises.d.ts b/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..50cee98 --- /dev/null +++ b/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,97 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via `require('node: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. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```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 { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/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. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: Pick) => Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking) 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/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..0b2d6b6 --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1217 @@ +/** + * The `node: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('node:tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * 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), or a TLS context object created + * with {@link createSecureContext} itself. + */ + 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. + */ + 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 `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('node:tls'); + * const fs = require('node: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('node:tls'); + * const fs = require('node: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 `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * 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). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @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](https://nodejs.org/docs/latest-v20.x/api/tls.html#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 `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link 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. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link 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. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link 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`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..1089c93 --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,197 @@ +/** + * The `node: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`](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html) 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.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v20.x/api/perf_hooks.html) 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 `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v20.x/api/v8.html) events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * 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 `node:trace_events` module: + * + * ```js + * const trace_events = require('node: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`](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html#class-worker) threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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. + * @since v10.0.0 + */ + 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. + * + * ```js + * const trace_events = require('node:trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + 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('node: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 + */ + 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('node: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/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..08727a8 --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,208 @@ +/** + * The `node: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('node: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/v20.12.2/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. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @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/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..b00d418 --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,944 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @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('node: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}. + * + * ```js + * import url from 'node: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}. + * + * ```js + * import url from 'node: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 'node: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 'node: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 'node: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('node: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 v19.9.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'; + * 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 v19.8.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/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..deed654 --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,2276 @@ +/** + * The `node: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('node:util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.12.2/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('node: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 + * @experimental + * @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 + * @experimental + * @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. + * + * ```js + * import { aborted } from 'node:util'; + * + * const dependent = obtainSomethingAbortable(); + * + * aborted(dependent.signal, dependent).then(() => { + * // Do something when dependent is aborted. + * }); + * + * dependent.on('event', () => { + * dependent.abort(); + * }); + * ``` + * @since v19.7.0 + * @experimental + * @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('node: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('node:util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('node: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('node: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('node:util'); + * const assert = require('node: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('node:util'); + * + * const thousand = 1_000; + * const million = 1_000_000; + * const bigNumber = 123_456_789n; + * const bigDecimal = 1_234.123_45; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. 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('node: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('node: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('node: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('node: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('node: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('node:util'); + * const EventEmitter = require('node: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('node: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('node: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('node: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('node: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('node: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('node: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('node: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('node: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('node: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('node: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('node: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 - 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('node: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('node: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('node: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('node: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('node: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('node: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('node: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('node:util'); + * const fs = require('node: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('node:util'); + * const fs = require('node:fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * 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('node: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; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * const { parseEnv } = require('node:util'); + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): object; + // https://nodejs.org/docs/latest/api/util.html#foreground-colors + type ForegroundColors = + | "black" + | "blackBright" + | "blue" + | "blueBright" + | "cyan" + | "cyanBright" + | "gray" + | "green" + | "greenBright" + | "grey" + | "magenta" + | "magentaBright" + | "red" + | "redBright" + | "white" + | "whiteBright" + | "yellow" + | "yellowBright"; + // https://nodejs.org/docs/latest/api/util.html#background-colors + type BackgroundColors = + | "bgBlack" + | "bgBlackBright" + | "bgBlue" + | "bgBlueBright" + | "bgCyan" + | "bgCyanBright" + | "bgGray" + | "bgGreen" + | "bgGreenBright" + | "bgGrey" + | "bgMagenta" + | "bgMagentaBright" + | "bgRed" + | "bgRedBright" + | "bgWhite" + | "bgWhiteBright" + | "bgYellow" + | "bgYellowBright"; + // https://nodejs.org/docs/latest/api/util.html#modifiers + type Modifiers = + | "blink" + | "bold" + | "dim" + | "doubleunderline" + | "framed" + | "hidden" + | "inverse" + | "italic" + | "overlined" + | "reset" + | "strikethrough" + | "underline"; + /** + * Stability: 1.1 - Active development + * + * This function returns a formatted text considering the `format` passed. + * + * ```js + * const { styleText } = require('node:util'); + * const errorMessage = styleText('red', 'Error! Error!'); + * console.log(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText('underline', util.styleText('italic', 'My italic underlined message')), + * ); + * ``` + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v20.x/api/util.html#modifiers). + * @param format A text format defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText(format: ForegroundColors | BackgroundColors | Modifiers, text: string): string; + /** + * 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 higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + 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; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + * @experimental + */ + 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. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object 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; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, 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. + * 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`. + */ + 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. + * @return or `null` if there is no name-value pair with the given `name`. + */ + 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. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + 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`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + 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 was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` for these errors: + * + * ```js + * const vm = require('node:vm'); + * const context = vm.createContext({}); + * const myError = vm.runInContext('new Error()', context); + * console.log(util.types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // 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/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..0bd038c --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,764 @@ +/** + * 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/v20.12.2/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; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean; + } + /** + * 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 containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): 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, options?: HeapSnapshotOptions): 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-v20.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 v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, 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 v19.6.0, 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/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..8a4baed --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,921 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node: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('node: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/v20.12.2/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; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v20.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + */ + importModuleDynamically?: + | ((specifier: string, script: Script, importAttributes: ImportAttributes) => Module) + | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER + | 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('node: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('node: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('node: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. + * + * The code cache of the `Script` doesn't contain any JavaScript observable + * states. The code cache is safe to be saved along side the script source and + * used to construct new `Script` instances multiple times. + * + * Functions in the `Script` source can be marked as lazily compiled and they are + * not compiled at construction of the `Script`. These functions are going to be + * compiled when they are invoked the first time. The code cache serializes the + * metadata that V8 currently knows about the `Script` that it can use to speed up + * future compilations. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutAdd = script.createCachedData(); + * // In `cacheWithoutAdd` the function `add()` is marked for full compilation + * // upon invocation. + * + * script.runInThisContext(); + * + * const cacheWithAdd = script.createCachedData(); + * // `cacheWithAdd` contains fully compiled function `add()`. + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + /** + * When `cachedData` is supplied to create the `vm.Script`, this value will be set + * to either `true` or `false` depending on acceptance of the data by V8. + * Otherwise the value is `undefined`. + * @since v5.7.0 + */ + 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. + * + * ```js + * import vm from 'node:vm'; + * + * const script = new vm.Script(` + * function myFunc() {} + * //# sourceMappingURL=sourcemap.json + * `); + * + * console.log(script.sourceMapURL); + * // Prints: sourcemap.json + * ``` + * @since v19.1.0, v18.13.0 + */ + 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('node: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 ` +``` + +(It also works with various module systems, if you prefer that sort of thing - it has a dependency on [vlq](https://github.com/Rich-Harris/vlq).) + +## Usage + +These examples assume you're in node.js, or something similar: + +```js +import MagicString from 'magic-string'; +import fs from 'fs' + +const s = new MagicString('problems = 99'); + +s.overwrite(0, 8, 'answer'); +s.toString(); // 'answer = 99' + +s.overwrite(11, 13, '42'); // character indices always refer to the original string +s.toString(); // 'answer = 42' + +s.prepend('var ').append(';'); // most methods are chainable +s.toString(); // 'var answer = 42;' + +const map = s.generateMap({ + source: 'source.js', + file: 'converted.js.map', + includeContent: true +}); // generates a v3 sourcemap + +fs.writeFileSync('converted.js', s.toString()); +fs.writeFileSync('converted.js.map', map.toString()); +``` + +You can pass an options argument: + +```js +const s = new MagicString(someCode, { + // both these options will be used if you later + // call `bundle.addSource( s )` - see below + filename: 'foo.js', + indentExclusionRanges: [/*...*/] +}); +``` + +## Methods + +### s.addSourcemapLocation( index ) + +Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is `false` (see below). + +### s.append( content ) + +Appends the specified content to the end of the string. Returns `this`. + +### s.appendLeft( index, content ) + +Appends the specified `content` at the `index` in the original string. If a range *ending* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependLeft(...)`. + +### s.appendRight( index, content ) + +Appends the specified `content` at the `index` in the original string. If a range *starting* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependRight(...)`. + +### s.clone() + +Does what you'd expect. + +### s.generateDecodedMap( options ) + +Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. See `generateMap` documentation below for options details. Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead. + +### s.generateMap( options ) + +Generates a [version 3 sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). All options are, well, optional: + +* `file` - the filename where you plan to write the sourcemap +* `source` - the filename of the file containing the original source +* `includeContent` - whether to include the original content in the map's `sourcesContent` array +* `hires` - whether the mapping should be high-resolution. Hi-res mappings map every single character, meaning (for example) your devtools will always be able to pinpoint the exact location of function calls and so on. With lo-res mappings, devtools may only be able to identify the correct line - but they're quicker to generate and less bulky. If sourcemap locations have been specified with `s.addSourceMapLocation()`, they will be used here. + +The returned sourcemap has two (non-enumerable) methods attached for convenience: + +* `toString` - returns the equivalent of `JSON.stringify(map)` +* `toUrl` - returns a DataURI containing the sourcemap. Useful for doing this sort of thing: + +```js +code += '\n//# sourceMappingURL=' + map.toUrl(); +``` + +### s.indent( prefix[, options] ) + +Prefixes each line of the string with `prefix`. If `prefix` is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. Returns `this`. + +The `options` argument can have an `exclude` property, which is an array of `[start, end]` character ranges. These ranges will be excluded from the indentation - useful for (e.g.) multiline strings. + +### s.insertLeft( index, content ) + +**DEPRECATED** since 0.17 – use `s.appendLeft(...)` instead + +### s.insertRight( index, content ) + +**DEPRECATED** since 0.17 – use `s.prependRight(...)` instead + +### s.locate( index ) + +**DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30) + +### s.locateOrigin( index ) + +**DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30) + +### s.move( start, end, newIndex ) + +Moves the characters from `start` and `end` to `index`. Returns `this`. + +### s.overwrite( start, end, content[, options] ) + +Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. Returns `this`. + +The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and a `contentOnly` property which determines whether only the content is overwritten, or anything that was appended/prepended to the range as well. + +### s.prepend( content ) + +Prepends the string with the specified content. Returns `this`. + +### s.prependLeft ( index, content ) + +Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at `index` + +### s.prependRight ( index, content ) + +Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index` + +### s.remove( start, end ) + +Removes the characters from `start` to `end` (of the original string, **not** the generated string). Removing the same content twice, or making removals that partially overlap, will cause an error. Returns `this`. + +### s.slice( start, end ) + +Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. Throws error if the indices are for characters that were already removed. + +### s.snip( start, end ) + +Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed. + +### s.toString() + +Returns the generated string. + +### s.trim([ charType ]) + +Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. Returns `this`. + +### s.trimStart([ charType ]) + +Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. Returns `this`. + +### s.trimEnd([ charType ]) + +Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. Returns `this`. + +### s.trimLines() + +Removes empty lines from the start and end. Returns `this`. + +### s.isEmpty() + +Returns true if the resulting source is empty (disregarding white space). + +## Bundling + +To concatenate several sources, use `MagicString.Bundle`: + +```js +const bundle = new MagicString.Bundle(); + +bundle.addSource({ + filename: 'foo.js', + content: new MagicString('var answer = 42;') +}); + +bundle.addSource({ + filename: 'bar.js', + content: new MagicString('console.log( answer )') +}); + +// Advanced: a source can include an `indentExclusionRanges` property +// alongside `filename` and `content`. This will be passed to `s.indent()` +// - see documentation above + +bundle.indent() // optionally, pass an indent string, otherwise it will be guessed + .prepend('(function () {\n') + .append('}());'); + +bundle.toString(); +// (function () { +// var answer = 42; +// console.log( answer ); +// }()); + +// options are as per `s.generateMap()` above +const map = bundle.generateMap({ + file: 'bundle.js', + includeContent: true, + hires: true +}); +``` + +As an alternative syntax, if you a) don't have `filename` or `indentExclusionRanges` options, or b) passed those in when you used `new MagicString(...)`, you can simply pass the `MagicString` instance itself: + +```js +const bundle = new MagicString.Bundle(); +const source = new MagicString(someCode, { + filename: 'foo.js' +}); + +bundle.addSource(source); +``` + +## License + +MIT diff --git a/node_modules/magic-string/dist/magic-string.cjs.js b/node_modules/magic-string/dist/magic-string.cjs.js new file mode 100644 index 0000000..4be44d8 --- /dev/null +++ b/node_modules/magic-string/dist/magic-string.cjs.js @@ -0,0 +1,1311 @@ +'use strict'; + +var sourcemapCodec = require('sourcemap-codec'); + +var BitSet = function BitSet(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; +}; + +BitSet.prototype.add = function add (n) { + this.bits[n >> 5] |= 1 << (n & 31); +}; + +BitSet.prototype.has = function has (n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); +}; + +var Chunk = function Chunk(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + // we make these non-enumerable, for sanity while debugging + Object.defineProperties(this, { + previous: { writable: true, value: null }, + next: { writable: true, value: null }, + }); +}; + +Chunk.prototype.appendLeft = function appendLeft (content) { + this.outro += content; +}; + +Chunk.prototype.appendRight = function appendRight (content) { + this.intro = this.intro + content; +}; + +Chunk.prototype.clone = function clone () { + var chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; +}; + +Chunk.prototype.contains = function contains (index) { + return this.start < index && index < this.end; +}; + +Chunk.prototype.eachNext = function eachNext (fn) { + var chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } +}; + +Chunk.prototype.eachPrevious = function eachPrevious (fn) { + var chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } +}; + +Chunk.prototype.edit = function edit (content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; +}; + +Chunk.prototype.prependLeft = function prependLeft (content) { + this.outro = content + this.outro; +}; + +Chunk.prototype.prependRight = function prependRight (content) { + this.intro = content + this.intro; +}; + +Chunk.prototype.split = function split (index) { + var sliceIndex = index - this.start; + + var originalBefore = this.original.slice(0, sliceIndex); + var originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + var newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) { newChunk.next.previous = newChunk; } + newChunk.previous = this; + this.next = newChunk; + + return newChunk; +}; + +Chunk.prototype.toString = function toString () { + return this.intro + this.content + this.outro; +}; + +Chunk.prototype.trimEnd = function trimEnd (rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + + var trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + } +}; + +Chunk.prototype.trimStart = function trimStart (rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + + var trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.end - trimmed.length); + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + } +}; + +var btoa = function () { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); +}; +if (typeof window !== 'undefined' && typeof window.btoa === 'function') { + btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); }; +} else if (typeof Buffer === 'function') { + btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); }; +} + +var SourceMap = function SourceMap(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = sourcemapCodec.encode(properties.mappings); +}; + +SourceMap.prototype.toString = function toString () { + return JSON.stringify(this); +}; + +SourceMap.prototype.toUrl = function toUrl () { + return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); +}; + +function guessIndent(code) { + var lines = code.split('\n'); + + var tabbed = lines.filter(function (line) { return /^\t+/.test(line); }); + var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); }); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + var min = spaced.reduce(function (previous, current) { + var numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + var fromParts = from.split(/[/\\]/); + var toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + var i = fromParts.length; + while (i--) { fromParts[i] = '..'; } + } + + return fromParts.concat(toParts).join('/'); +} + +var toString = Object.prototype.toString; + +function isObject(thing) { + return toString.call(thing) === '[object Object]'; +} + +function getLocator(source) { + var originalLines = source.split('\n'); + var lineOffsets = []; + + for (var i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + var i = 0; + var j = lineOffsets.length; + while (i < j) { + var m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + var line = i - 1; + var column = index - lineOffsets[line]; + return { line: line, column: column }; + }; +} + +var Mappings = function Mappings(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; +}; + +Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) { + if (content.length) { + var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + } else if (this.pending) { + this.rawSegments.push(this.pending); + } + + this.advance(content); + this.pending = null; +}; + +Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) { + var originalCharIndex = chunk.start; + var first = true; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; +}; + +Mappings.prototype.advance = function advance (str) { + if (!str) { return; } + + var lines = str.split('\n'); + + if (lines.length > 1) { + for (var i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; +}; + +var n = '\n'; + +var warned = { + insertLeft: false, + insertRight: false, + storeName: false, +}; + +var MagicString = function MagicString(string, options) { + if ( options === void 0 ) options = {}; + + var chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: guessIndent(string) }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; +}; + +MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) { + this.sourcemapLocations.add(char); +}; + +MagicString.prototype.append = function append (content) { + if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } + + this.outro += content; + return this; +}; + +MagicString.prototype.appendLeft = function appendLeft (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; +}; + +MagicString.prototype.appendRight = function appendRight (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; +}; + +MagicString.prototype.clone = function clone () { + var cloned = new MagicString(this.original, { filename: this.filename }); + + var originalChunk = this.firstChunk; + var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + var nextOriginalChunk = originalChunk.next; + var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; +}; + +MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) { + var this$1$1 = this; + + options = options || {}; + + var sourceIndex = 0; + var names = Object.keys(this.storedNames); + var mappings = new Mappings(options.hires); + + var locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext(function (chunk) { + var loc = locate(chunk.start); + + if (chunk.intro.length) { mappings.advance(chunk.intro); } + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1 + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations); + } + + if (chunk.outro.length) { mappings.advance(chunk.outro); } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : null, + sources: [options.source ? getRelativePath(options.file || '', options.source) : null], + sourcesContent: options.includeContent ? [this.original] : [null], + names: names, + mappings: mappings.raw, + }; +}; + +MagicString.prototype.generateMap = function generateMap (options) { + return new SourceMap(this.generateDecodedMap(options)); +}; + +MagicString.prototype.getIndentString = function getIndentString () { + return this.indentStr === null ? '\t' : this.indentStr; +}; + +MagicString.prototype.indent = function indent (indentStr, options) { + var pattern = /^[^\r\n]/gm; + + if (isObject(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t'; + + if (indentStr === '') { return this; } // noop + + options = options || {}; + + // Process exclusion ranges + var isExcluded = {}; + + if (options.exclude) { + var exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach(function (exclusion) { + for (var i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + var shouldIndentNextCharacter = options.indentStart !== false; + var replacer = function (match) { + if (shouldIndentNextCharacter) { return ("" + indentStr + match); } + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + var charIndex = 0; + var chunk = this.firstChunk; + + while (chunk) { + var end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + var char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; +}; + +MagicString.prototype.insert = function insert () { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' + ); +}; + +MagicString.prototype.insertLeft = function insertLeft (index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); +}; + +MagicString.prototype.insertRight = function insertRight (index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); +}; + +MagicString.prototype.move = function move (start, end, index) { + if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); } + + this._split(start); + this._split(end); + this._split(index); + + var first = this.byStart[start]; + var last = this.byEnd[end]; + + var oldLeft = first.previous; + var oldRight = last.next; + + var newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) { return this; } + var newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) { oldLeft.next = oldRight; } + if (oldRight) { oldRight.previous = oldLeft; } + + if (newLeft) { newLeft.next = first; } + if (newRight) { newRight.previous = last; } + + if (!first.previous) { this.firstChunk = last.next; } + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) { this.firstChunk = first; } + if (!newRight) { this.lastChunk = last; } + return this; +}; + +MagicString.prototype.overwrite = function overwrite (start, end, content, options) { + if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); } + + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + if (end > this.original.length) { throw new Error('end is out of bounds'); } + if (start === end) + { throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' + ); } + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + var storeName = options !== undefined ? options.storeName : false; + var contentOnly = options !== undefined ? options.contentOnly : false; + + if (storeName) { + var original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true }); + } + + var first = this.byStart[start]; + var last = this.byEnd[end]; + + if (first) { + var chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, contentOnly); + } else { + // must be inserting at the end + var newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; +}; + +MagicString.prototype.prepend = function prepend (content) { + if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } + + this.intro = content + this.intro; + return this; +}; + +MagicString.prototype.prependLeft = function prependLeft (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; +}; + +MagicString.prototype.prependRight = function prependRight (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; +}; + +MagicString.prototype.remove = function remove (start, end) { + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + if (start === end) { return this; } + + if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); } + if (start > end) { throw new Error('end must be greater than start'); } + + this._split(start); + this._split(end); + + var chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; +}; + +MagicString.prototype.lastChar = function lastChar () { + if (this.outro.length) { return this.outro[this.outro.length - 1]; } + var chunk = this.lastChunk; + do { + if (chunk.outro.length) { return chunk.outro[chunk.outro.length - 1]; } + if (chunk.content.length) { return chunk.content[chunk.content.length - 1]; } + if (chunk.intro.length) { return chunk.intro[chunk.intro.length - 1]; } + } while ((chunk = chunk.previous)); + if (this.intro.length) { return this.intro[this.intro.length - 1]; } + return ''; +}; + +MagicString.prototype.lastLine = function lastLine () { + var lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) { return this.outro.substr(lineIndex + 1); } + var lineStr = this.outro; + var chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) { return chunk.outro.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) { return chunk.content.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) { return chunk.intro.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) { return this.intro.substr(lineIndex + 1) + lineStr; } + return this.intro + lineStr; +}; + +MagicString.prototype.slice = function slice (start, end) { + if ( start === void 0 ) start = 0; + if ( end === void 0 ) end = this.original.length; + + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + var result = ''; + + // find start chunk + var chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); } + + var startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + var containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); } + + var sliceStart = startChunk === chunk ? start - chunk.start : 0; + var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; +}; + +// TODO deprecate this? not really very useful +MagicString.prototype.snip = function snip (start, end) { + var clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; +}; + +MagicString.prototype._split = function _split (index) { + if (this.byStart[index] || this.byEnd[index]) { return; } + + var chunk = this.lastSearchedChunk; + var searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) { return this._splitChunk(chunk, index); } + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } +}; + +MagicString.prototype._splitChunk = function _splitChunk (chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + var loc = getLocator(this.original)(index); + throw new Error( + ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") + ); + } + + var newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) { this.lastChunk = newChunk; } + + this.lastSearchedChunk = chunk; + return true; +}; + +MagicString.prototype.toString = function toString () { + var str = this.intro; + + var chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; +}; + +MagicString.prototype.isEmpty = function isEmpty () { + var chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + { return false; } + } while ((chunk = chunk.next)); + return true; +}; + +MagicString.prototype.length = function length () { + var chunk = this.firstChunk; + var length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; +}; + +MagicString.prototype.trimLines = function trimLines () { + return this.trim('[\\r\\n]'); +}; + +MagicString.prototype.trim = function trim (charType) { + return this.trimStart(charType).trimEnd(charType); +}; + +MagicString.prototype.trimEndAborted = function trimEndAborted (charType) { + var rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + + var chunk = this.lastChunk; + + do { + var end = chunk.end; + var aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) { return true; } + chunk = chunk.previous; + } while (chunk); + + return false; +}; + +MagicString.prototype.trimEnd = function trimEnd (charType) { + this.trimEndAborted(charType); + return this; +}; +MagicString.prototype.trimStartAborted = function trimStartAborted (charType) { + var rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + + var chunk = this.firstChunk; + + do { + var end = chunk.end; + var aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) { this.lastChunk = chunk.next; } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) { return true; } + chunk = chunk.next; + } while (chunk); + + return false; +}; + +MagicString.prototype.trimStart = function trimStart (charType) { + this.trimStartAborted(charType); + return this; +}; + +var hasOwnProp = Object.prototype.hasOwnProperty; + +var Bundle = function Bundle(options) { + if ( options === void 0 ) options = {}; + + this.intro = options.intro || ''; + this.separator = options.separator !== undefined ? options.separator : '\n'; + this.sources = []; + this.uniqueSources = []; + this.uniqueSourceIndexByFilename = {}; +}; + +Bundle.prototype.addSource = function addSource (source) { + if (source instanceof MagicString) { + return this.addSource({ + content: source, + filename: source.filename, + separator: this.separator, + }); + } + + if (!isObject(source) || !source.content) { + throw new Error( + 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`' + ); + } + + ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) { + if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; } + }); + + if (source.separator === undefined) { + // TODO there's a bunch of this sort of thing, needs cleaning up + source.separator = this.separator; + } + + if (source.filename) { + if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) { + this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length; + this.uniqueSources.push({ filename: source.filename, content: source.content.original }); + } else { + var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]]; + if (source.content.original !== uniqueSource.content) { + throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents")); + } + } + } + + this.sources.push(source); + return this; +}; + +Bundle.prototype.append = function append (str, options) { + this.addSource({ + content: new MagicString(str), + separator: (options && options.separator) || '', + }); + + return this; +}; + +Bundle.prototype.clone = function clone () { + var bundle = new Bundle({ + intro: this.intro, + separator: this.separator, + }); + + this.sources.forEach(function (source) { + bundle.addSource({ + filename: source.filename, + content: source.content.clone(), + separator: source.separator, + }); + }); + + return bundle; +}; + +Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) { + var this$1$1 = this; + if ( options === void 0 ) options = {}; + + var names = []; + this.sources.forEach(function (source) { + Object.keys(source.content.storedNames).forEach(function (name) { + if (!~names.indexOf(name)) { names.push(name); } + }); + }); + + var mappings = new Mappings(options.hires); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.sources.forEach(function (source, i) { + if (i > 0) { + mappings.advance(this$1$1.separator); + } + + var sourceIndex = source.filename ? this$1$1.uniqueSourceIndexByFilename[source.filename] : -1; + var magicString = source.content; + var locate = getLocator(magicString.original); + + if (magicString.intro) { + mappings.advance(magicString.intro); + } + + magicString.firstChunk.eachNext(function (chunk) { + var loc = locate(chunk.start); + + if (chunk.intro.length) { mappings.advance(chunk.intro); } + + if (source.filename) { + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1 + ); + } else { + mappings.addUneditedChunk( + sourceIndex, + chunk, + magicString.original, + loc, + magicString.sourcemapLocations + ); + } + } else { + mappings.advance(chunk.content); + } + + if (chunk.outro.length) { mappings.advance(chunk.outro); } + }); + + if (magicString.outro) { + mappings.advance(magicString.outro); + } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : null, + sources: this.uniqueSources.map(function (source) { + return options.file ? getRelativePath(options.file, source.filename) : source.filename; + }), + sourcesContent: this.uniqueSources.map(function (source) { + return options.includeContent ? source.content : null; + }), + names: names, + mappings: mappings.raw, + }; +}; + +Bundle.prototype.generateMap = function generateMap (options) { + return new SourceMap(this.generateDecodedMap(options)); +}; + +Bundle.prototype.getIndentString = function getIndentString () { + var indentStringCounts = {}; + + this.sources.forEach(function (source) { + var indentStr = source.content.indentStr; + + if (indentStr === null) { return; } + + if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; } + indentStringCounts[indentStr] += 1; + }); + + return ( + Object.keys(indentStringCounts).sort(function (a, b) { + return indentStringCounts[a] - indentStringCounts[b]; + })[0] || '\t' + ); +}; + +Bundle.prototype.indent = function indent (indentStr) { + var this$1$1 = this; + + if (!arguments.length) { + indentStr = this.getIndentString(); + } + + if (indentStr === '') { return this; } // noop + + var trailingNewline = !this.intro || this.intro.slice(-1) === '\n'; + + this.sources.forEach(function (source, i) { + var separator = source.separator !== undefined ? source.separator : this$1$1.separator; + var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator)); + + source.content.indent(indentStr, { + exclude: source.indentExclusionRanges, + indentStart: indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator ) + }); + + trailingNewline = source.content.lastChar() === '\n'; + }); + + if (this.intro) { + this.intro = + indentStr + + this.intro.replace(/^[^\n]/gm, function (match, index) { + return index > 0 ? indentStr + match : match; + }); + } + + return this; +}; + +Bundle.prototype.prepend = function prepend (str) { + this.intro = str + this.intro; + return this; +}; + +Bundle.prototype.toString = function toString () { + var this$1$1 = this; + + var body = this.sources + .map(function (source, i) { + var separator = source.separator !== undefined ? source.separator : this$1$1.separator; + var str = (i > 0 ? separator : '') + source.content.toString(); + + return str; + }) + .join(''); + + return this.intro + body; +}; + +Bundle.prototype.isEmpty = function isEmpty () { + if (this.intro.length && this.intro.trim()) { return false; } + if (this.sources.some(function (source) { return !source.content.isEmpty(); })) { return false; } + return true; +}; + +Bundle.prototype.length = function length () { + return this.sources.reduce( + function (length, source) { return length + source.content.length(); }, + this.intro.length + ); +}; + +Bundle.prototype.trimLines = function trimLines () { + return this.trim('[\\r\\n]'); +}; + +Bundle.prototype.trim = function trim (charType) { + return this.trimStart(charType).trimEnd(charType); +}; + +Bundle.prototype.trimStart = function trimStart (charType) { + var rx = new RegExp('^' + (charType || '\\s') + '+'); + this.intro = this.intro.replace(rx, ''); + + if (!this.intro) { + var source; + var i = 0; + + do { + source = this.sources[i++]; + if (!source) { + break; + } + } while (!source.content.trimStartAborted(charType)); + } + + return this; +}; + +Bundle.prototype.trimEnd = function trimEnd (charType) { + var rx = new RegExp((charType || '\\s') + '+$'); + + var source; + var i = this.sources.length - 1; + + do { + source = this.sources[i--]; + if (!source) { + this.intro = this.intro.replace(rx, ''); + break; + } + } while (!source.content.trimEndAborted(charType)); + + return this; +}; + +MagicString.Bundle = Bundle; +MagicString.SourceMap = SourceMap; +MagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121 + +module.exports = MagicString; +//# sourceMappingURL=magic-string.cjs.js.map diff --git a/node_modules/magic-string/dist/magic-string.cjs.js.map b/node_modules/magic-string/dist/magic-string.cjs.js.map new file mode 100644 index 0000000..964c77e --- /dev/null +++ b/node_modules/magic-string/dist/magic-string.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"magic-string.cjs.js","sources":["../src/BitSet.js","../src/Chunk.js","../src/SourceMap.js","../src/utils/guessIndent.js","../src/utils/getRelativePath.js","../src/utils/isObject.js","../src/utils/getLocator.js","../src/utils/Mappings.js","../src/MagicString.js","../src/Bundle.js","../src/index-legacy.js"],"sourcesContent":["export default class BitSet {\n\tconstructor(arg) {\n\t\tthis.bits = arg instanceof BitSet ? arg.bits.slice() : [];\n\t}\n\n\tadd(n) {\n\t\tthis.bits[n >> 5] |= 1 << (n & 31);\n\t}\n\n\thas(n) {\n\t\treturn !!(this.bits[n >> 5] & (1 << (n & 31)));\n\t}\n}\n","export default class Chunk {\n\tconstructor(start, end, content) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tthis.original = content;\n\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\n\t\tthis.content = content;\n\t\tthis.storeName = false;\n\t\tthis.edited = false;\n\n\t\t// we make these non-enumerable, for sanity while debugging\n\t\tObject.defineProperties(this, {\n\t\t\tprevious: { writable: true, value: null },\n\t\t\tnext: { writable: true, value: null },\n\t\t});\n\t}\n\n\tappendLeft(content) {\n\t\tthis.outro += content;\n\t}\n\n\tappendRight(content) {\n\t\tthis.intro = this.intro + content;\n\t}\n\n\tclone() {\n\t\tconst chunk = new Chunk(this.start, this.end, this.original);\n\n\t\tchunk.intro = this.intro;\n\t\tchunk.outro = this.outro;\n\t\tchunk.content = this.content;\n\t\tchunk.storeName = this.storeName;\n\t\tchunk.edited = this.edited;\n\n\t\treturn chunk;\n\t}\n\n\tcontains(index) {\n\t\treturn this.start < index && index < this.end;\n\t}\n\n\teachNext(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.next;\n\t\t}\n\t}\n\n\teachPrevious(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.previous;\n\t\t}\n\t}\n\n\tedit(content, storeName, contentOnly) {\n\t\tthis.content = content;\n\t\tif (!contentOnly) {\n\t\t\tthis.intro = '';\n\t\t\tthis.outro = '';\n\t\t}\n\t\tthis.storeName = storeName;\n\n\t\tthis.edited = true;\n\n\t\treturn this;\n\t}\n\n\tprependLeft(content) {\n\t\tthis.outro = content + this.outro;\n\t}\n\n\tprependRight(content) {\n\t\tthis.intro = content + this.intro;\n\t}\n\n\tsplit(index) {\n\t\tconst sliceIndex = index - this.start;\n\n\t\tconst originalBefore = this.original.slice(0, sliceIndex);\n\t\tconst originalAfter = this.original.slice(sliceIndex);\n\n\t\tthis.original = originalBefore;\n\n\t\tconst newChunk = new Chunk(index, this.end, originalAfter);\n\t\tnewChunk.outro = this.outro;\n\t\tthis.outro = '';\n\n\t\tthis.end = index;\n\n\t\tif (this.edited) {\n\t\t\t// TODO is this block necessary?...\n\t\t\tnewChunk.edit('', false);\n\t\t\tthis.content = '';\n\t\t} else {\n\t\t\tthis.content = originalBefore;\n\t\t}\n\n\t\tnewChunk.next = this.next;\n\t\tif (newChunk.next) newChunk.next.previous = newChunk;\n\t\tnewChunk.previous = this;\n\t\tthis.next = newChunk;\n\n\t\treturn newChunk;\n\t}\n\n\ttoString() {\n\t\treturn this.intro + this.content + this.outro;\n\t}\n\n\ttrimEnd(rx) {\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.start + trimmed.length).edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\tif (this.intro.length) return true;\n\t\t}\n\t}\n\n\ttrimStart(rx) {\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.end - trimmed.length);\n\t\t\t\tthis.edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.outro = this.outro.replace(rx, '');\n\t\t\tif (this.outro.length) return true;\n\t\t}\n\t}\n}\n","import { encode } from 'sourcemap-codec';\n\nlet btoa = () => {\n\tthrow new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');\n};\nif (typeof window !== 'undefined' && typeof window.btoa === 'function') {\n\tbtoa = (str) => window.btoa(unescape(encodeURIComponent(str)));\n} else if (typeof Buffer === 'function') {\n\tbtoa = (str) => Buffer.from(str, 'utf-8').toString('base64');\n}\n\nexport default class SourceMap {\n\tconstructor(properties) {\n\t\tthis.version = 3;\n\t\tthis.file = properties.file;\n\t\tthis.sources = properties.sources;\n\t\tthis.sourcesContent = properties.sourcesContent;\n\t\tthis.names = properties.names;\n\t\tthis.mappings = encode(properties.mappings);\n\t}\n\n\ttoString() {\n\t\treturn JSON.stringify(this);\n\t}\n\n\ttoUrl() {\n\t\treturn 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());\n\t}\n}\n","export default function guessIndent(code) {\n\tconst lines = code.split('\\n');\n\n\tconst tabbed = lines.filter((line) => /^\\t+/.test(line));\n\tconst spaced = lines.filter((line) => /^ {2,}/.test(line));\n\n\tif (tabbed.length === 0 && spaced.length === 0) {\n\t\treturn null;\n\t}\n\n\t// More lines tabbed than spaced? Assume tabs, and\n\t// default to tabs in the case of a tie (or nothing\n\t// to go on)\n\tif (tabbed.length >= spaced.length) {\n\t\treturn '\\t';\n\t}\n\n\t// Otherwise, we need to guess the multiple\n\tconst min = spaced.reduce((previous, current) => {\n\t\tconst numSpaces = /^ +/.exec(current)[0].length;\n\t\treturn Math.min(numSpaces, previous);\n\t}, Infinity);\n\n\treturn new Array(min + 1).join(' ');\n}\n","export default function getRelativePath(from, to) {\n\tconst fromParts = from.split(/[/\\\\]/);\n\tconst toParts = to.split(/[/\\\\]/);\n\n\tfromParts.pop(); // get dirname\n\n\twhile (fromParts[0] === toParts[0]) {\n\t\tfromParts.shift();\n\t\ttoParts.shift();\n\t}\n\n\tif (fromParts.length) {\n\t\tlet i = fromParts.length;\n\t\twhile (i--) fromParts[i] = '..';\n\t}\n\n\treturn fromParts.concat(toParts).join('/');\n}\n","const toString = Object.prototype.toString;\n\nexport default function isObject(thing) {\n\treturn toString.call(thing) === '[object Object]';\n}\n","export default function getLocator(source) {\n\tconst originalLines = source.split('\\n');\n\tconst lineOffsets = [];\n\n\tfor (let i = 0, pos = 0; i < originalLines.length; i++) {\n\t\tlineOffsets.push(pos);\n\t\tpos += originalLines[i].length + 1;\n\t}\n\n\treturn function locate(index) {\n\t\tlet i = 0;\n\t\tlet j = lineOffsets.length;\n\t\twhile (i < j) {\n\t\t\tconst m = (i + j) >> 1;\n\t\t\tif (index < lineOffsets[m]) {\n\t\t\t\tj = m;\n\t\t\t} else {\n\t\t\t\ti = m + 1;\n\t\t\t}\n\t\t}\n\t\tconst line = i - 1;\n\t\tconst column = index - lineOffsets[line];\n\t\treturn { line, column };\n\t};\n}\n","export default class Mappings {\n\tconstructor(hires) {\n\t\tthis.hires = hires;\n\t\tthis.generatedCodeLine = 0;\n\t\tthis.generatedCodeColumn = 0;\n\t\tthis.raw = [];\n\t\tthis.rawSegments = this.raw[this.generatedCodeLine] = [];\n\t\tthis.pending = null;\n\t}\n\n\taddEdit(sourceIndex, content, loc, nameIndex) {\n\t\tif (content.length) {\n\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\tif (nameIndex >= 0) {\n\t\t\t\tsegment.push(nameIndex);\n\t\t\t}\n\t\t\tthis.rawSegments.push(segment);\n\t\t} else if (this.pending) {\n\t\t\tthis.rawSegments.push(this.pending);\n\t\t}\n\n\t\tthis.advance(content);\n\t\tthis.pending = null;\n\t}\n\n\taddUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {\n\t\tlet originalCharIndex = chunk.start;\n\t\tlet first = true;\n\n\t\twhile (originalCharIndex < chunk.end) {\n\t\t\tif (this.hires || first || sourcemapLocations.has(originalCharIndex)) {\n\t\t\t\tthis.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);\n\t\t\t}\n\n\t\t\tif (original[originalCharIndex] === '\\n') {\n\t\t\t\tloc.line += 1;\n\t\t\t\tloc.column = 0;\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\t\t\t\tfirst = true;\n\t\t\t} else {\n\t\t\t\tloc.column += 1;\n\t\t\t\tthis.generatedCodeColumn += 1;\n\t\t\t\tfirst = false;\n\t\t\t}\n\n\t\t\toriginalCharIndex += 1;\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\tadvance(str) {\n\t\tif (!str) return;\n\n\t\tconst lines = str.split('\\n');\n\n\t\tif (lines.length > 1) {\n\t\t\tfor (let i = 0; i < lines.length - 1; i++) {\n\t\t\t\tthis.generatedCodeLine++;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t}\n\t\t\tthis.generatedCodeColumn = 0;\n\t\t}\n\n\t\tthis.generatedCodeColumn += lines[lines.length - 1].length;\n\t}\n}\n","import BitSet from './BitSet.js';\nimport Chunk from './Chunk.js';\nimport SourceMap from './SourceMap.js';\nimport guessIndent from './utils/guessIndent.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\nimport Stats from './utils/Stats.js';\n\nconst n = '\\n';\n\nconst warned = {\n\tinsertLeft: false,\n\tinsertRight: false,\n\tstoreName: false,\n};\n\nexport default class MagicString {\n\tconstructor(string, options = {}) {\n\t\tconst chunk = new Chunk(0, string.length, string);\n\n\t\tObject.defineProperties(this, {\n\t\t\toriginal: { writable: true, value: string },\n\t\t\toutro: { writable: true, value: '' },\n\t\t\tintro: { writable: true, value: '' },\n\t\t\tfirstChunk: { writable: true, value: chunk },\n\t\t\tlastChunk: { writable: true, value: chunk },\n\t\t\tlastSearchedChunk: { writable: true, value: chunk },\n\t\t\tbyStart: { writable: true, value: {} },\n\t\t\tbyEnd: { writable: true, value: {} },\n\t\t\tfilename: { writable: true, value: options.filename },\n\t\t\tindentExclusionRanges: { writable: true, value: options.indentExclusionRanges },\n\t\t\tsourcemapLocations: { writable: true, value: new BitSet() },\n\t\t\tstoredNames: { writable: true, value: {} },\n\t\t\tindentStr: { writable: true, value: guessIndent(string) },\n\t\t});\n\n\t\tif (DEBUG) {\n\t\t\tObject.defineProperty(this, 'stats', { value: new Stats() });\n\t\t}\n\n\t\tthis.byStart[0] = chunk;\n\t\tthis.byEnd[string.length] = chunk;\n\t}\n\n\taddSourcemapLocation(char) {\n\t\tthis.sourcemapLocations.add(char);\n\t}\n\n\tappend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.outro += content;\n\t\treturn this;\n\t}\n\n\tappendLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendLeft');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendLeft(content);\n\t\t} else {\n\t\t\tthis.intro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendLeft');\n\t\treturn this;\n\t}\n\n\tappendRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendRight(content);\n\t\t} else {\n\t\t\tthis.outro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendRight');\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst cloned = new MagicString(this.original, { filename: this.filename });\n\n\t\tlet originalChunk = this.firstChunk;\n\t\tlet clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());\n\n\t\twhile (originalChunk) {\n\t\t\tcloned.byStart[clonedChunk.start] = clonedChunk;\n\t\t\tcloned.byEnd[clonedChunk.end] = clonedChunk;\n\n\t\t\tconst nextOriginalChunk = originalChunk.next;\n\t\t\tconst nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();\n\n\t\t\tif (nextClonedChunk) {\n\t\t\t\tclonedChunk.next = nextClonedChunk;\n\t\t\t\tnextClonedChunk.previous = clonedChunk;\n\n\t\t\t\tclonedChunk = nextClonedChunk;\n\t\t\t}\n\n\t\t\toriginalChunk = nextOriginalChunk;\n\t\t}\n\n\t\tcloned.lastChunk = clonedChunk;\n\n\t\tif (this.indentExclusionRanges) {\n\t\t\tcloned.indentExclusionRanges = this.indentExclusionRanges.slice();\n\t\t}\n\n\t\tcloned.sourcemapLocations = new BitSet(this.sourcemapLocations);\n\n\t\tcloned.intro = this.intro;\n\t\tcloned.outro = this.outro;\n\n\t\treturn cloned;\n\t}\n\n\tgenerateDecodedMap(options) {\n\t\toptions = options || {};\n\n\t\tconst sourceIndex = 0;\n\t\tconst names = Object.keys(this.storedNames);\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tconst locate = getLocator(this.original);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.firstChunk.eachNext((chunk) => {\n\t\t\tconst loc = locate(chunk.start);\n\n\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tmappings.addEdit(\n\t\t\t\t\tsourceIndex,\n\t\t\t\t\tchunk.content,\n\t\t\t\t\tloc,\n\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);\n\t\t\t}\n\n\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : null,\n\t\t\tsources: [options.source ? getRelativePath(options.file || '', options.source) : null],\n\t\t\tsourcesContent: options.includeContent ? [this.original] : [null],\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\treturn this.indentStr === null ? '\\t' : this.indentStr;\n\t}\n\n\tindent(indentStr, options) {\n\t\tconst pattern = /^[^\\r\\n]/gm;\n\n\t\tif (isObject(indentStr)) {\n\t\t\toptions = indentStr;\n\t\t\tindentStr = undefined;\n\t\t}\n\n\t\tindentStr = indentStr !== undefined ? indentStr : this.indentStr || '\\t';\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\toptions = options || {};\n\n\t\t// Process exclusion ranges\n\t\tconst isExcluded = {};\n\n\t\tif (options.exclude) {\n\t\t\tconst exclusions =\n\t\t\t\ttypeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;\n\t\t\texclusions.forEach((exclusion) => {\n\t\t\t\tfor (let i = exclusion[0]; i < exclusion[1]; i += 1) {\n\t\t\t\t\tisExcluded[i] = true;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tlet shouldIndentNextCharacter = options.indentStart !== false;\n\t\tconst replacer = (match) => {\n\t\t\tif (shouldIndentNextCharacter) return `${indentStr}${match}`;\n\t\t\tshouldIndentNextCharacter = true;\n\t\t\treturn match;\n\t\t};\n\n\t\tthis.intro = this.intro.replace(pattern, replacer);\n\n\t\tlet charIndex = 0;\n\t\tlet chunk = this.firstChunk;\n\n\t\twhile (chunk) {\n\t\t\tconst end = chunk.end;\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\tchunk.content = chunk.content.replace(pattern, replacer);\n\n\t\t\t\t\tif (chunk.content.length) {\n\t\t\t\t\t\tshouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\\n';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcharIndex = chunk.start;\n\n\t\t\t\twhile (charIndex < end) {\n\t\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\t\tconst char = this.original[charIndex];\n\n\t\t\t\t\t\tif (char === '\\n') {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = true;\n\t\t\t\t\t\t} else if (char !== '\\r' && shouldIndentNextCharacter) {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = false;\n\n\t\t\t\t\t\t\tif (charIndex === chunk.start) {\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthis._splitChunk(chunk, charIndex);\n\t\t\t\t\t\t\t\tchunk = chunk.next;\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcharIndex += 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcharIndex = chunk.end;\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tthis.outro = this.outro.replace(pattern, replacer);\n\n\t\treturn this;\n\t}\n\n\tinsert() {\n\t\tthrow new Error(\n\t\t\t'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'\n\t\t);\n\t}\n\n\tinsertLeft(index, content) {\n\t\tif (!warned.insertLeft) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertLeft = true;\n\t\t}\n\n\t\treturn this.appendLeft(index, content);\n\t}\n\n\tinsertRight(index, content) {\n\t\tif (!warned.insertRight) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertRight = true;\n\t\t}\n\n\t\treturn this.prependRight(index, content);\n\t}\n\n\tmove(start, end, index) {\n\t\tif (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');\n\n\t\tif (DEBUG) this.stats.time('move');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\t\tthis._split(index);\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tconst oldLeft = first.previous;\n\t\tconst oldRight = last.next;\n\n\t\tconst newRight = this.byStart[index];\n\t\tif (!newRight && last === this.lastChunk) return this;\n\t\tconst newLeft = newRight ? newRight.previous : this.lastChunk;\n\n\t\tif (oldLeft) oldLeft.next = oldRight;\n\t\tif (oldRight) oldRight.previous = oldLeft;\n\n\t\tif (newLeft) newLeft.next = first;\n\t\tif (newRight) newRight.previous = last;\n\n\t\tif (!first.previous) this.firstChunk = last.next;\n\t\tif (!last.next) {\n\t\t\tthis.lastChunk = first.previous;\n\t\t\tthis.lastChunk.next = null;\n\t\t}\n\n\t\tfirst.previous = newLeft;\n\t\tlast.next = newRight || null;\n\n\t\tif (!newLeft) this.firstChunk = first;\n\t\tif (!newRight) this.lastChunk = last;\n\n\t\tif (DEBUG) this.stats.timeEnd('move');\n\t\treturn this;\n\t}\n\n\toverwrite(start, end, content, options) {\n\t\tif (typeof content !== 'string') throw new TypeError('replacement content must be a string');\n\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (end > this.original.length) throw new Error('end is out of bounds');\n\t\tif (start === end)\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'\n\t\t\t);\n\n\t\tif (DEBUG) this.stats.time('overwrite');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tif (options === true) {\n\t\t\tif (!warned.storeName) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'\n\t\t\t\t); // eslint-disable-line no-console\n\t\t\t\twarned.storeName = true;\n\t\t\t}\n\n\t\t\toptions = { storeName: true };\n\t\t}\n\t\tconst storeName = options !== undefined ? options.storeName : false;\n\t\tconst contentOnly = options !== undefined ? options.contentOnly : false;\n\n\t\tif (storeName) {\n\t\t\tconst original = this.original.slice(start, end);\n\t\t\tObject.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true });\n\t\t}\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tif (first) {\n\t\t\tlet chunk = first;\n\t\t\twhile (chunk !== last) {\n\t\t\t\tif (chunk.next !== this.byStart[chunk.end]) {\n\t\t\t\t\tthrow new Error('Cannot overwrite across a split point');\n\t\t\t\t}\n\t\t\t\tchunk = chunk.next;\n\t\t\t\tchunk.edit('', false);\n\t\t\t}\n\n\t\t\tfirst.edit(content, storeName, contentOnly);\n\t\t} else {\n\t\t\t// must be inserting at the end\n\t\t\tconst newChunk = new Chunk(start, end, '').edit(content, storeName);\n\n\t\t\t// TODO last chunk in the array may not be the last chunk, if it's moved...\n\t\t\tlast.next = newChunk;\n\t\t\tnewChunk.previous = last;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('overwrite');\n\t\treturn this;\n\t}\n\n\tprepend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.intro = content + this.intro;\n\t\treturn this;\n\t}\n\n\tprependLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependLeft(content);\n\t\t} else {\n\t\t\tthis.intro = content + this.intro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tprependRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependRight(content);\n\t\t} else {\n\t\t\tthis.outro = content + this.outro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tremove(start, end) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('remove');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.intro = '';\n\t\t\tchunk.outro = '';\n\t\t\tchunk.edit('');\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('remove');\n\t\treturn this;\n\t}\n\n\tlastChar() {\n\t\tif (this.outro.length) return this.outro[this.outro.length - 1];\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];\n\t\t\tif (chunk.content.length) return chunk.content[chunk.content.length - 1];\n\t\t\tif (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];\n\t\t} while ((chunk = chunk.previous));\n\t\tif (this.intro.length) return this.intro[this.intro.length - 1];\n\t\treturn '';\n\t}\n\n\tlastLine() {\n\t\tlet lineIndex = this.outro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.outro.substr(lineIndex + 1);\n\t\tlet lineStr = this.outro;\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length > 0) {\n\t\t\t\tlineIndex = chunk.outro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.outro + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.content.length > 0) {\n\t\t\t\tlineIndex = chunk.content.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.content + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.intro.length > 0) {\n\t\t\t\tlineIndex = chunk.intro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.intro + lineStr;\n\t\t\t}\n\t\t} while ((chunk = chunk.previous));\n\t\tlineIndex = this.intro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;\n\t\treturn this.intro + lineStr;\n\t}\n\n\tslice(start = 0, end = this.original.length) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tlet result = '';\n\n\t\t// find start chunk\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk && (chunk.start > start || chunk.end <= start)) {\n\t\t\t// found end chunk before start\n\t\t\tif (chunk.start < end && chunk.end >= end) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tif (chunk && chunk.edited && chunk.start !== start)\n\t\t\tthrow new Error(`Cannot use replaced character ${start} as slice start anchor.`);\n\n\t\tconst startChunk = chunk;\n\t\twhile (chunk) {\n\t\t\tif (chunk.intro && (startChunk !== chunk || chunk.start === start)) {\n\t\t\t\tresult += chunk.intro;\n\t\t\t}\n\n\t\t\tconst containsEnd = chunk.start < end && chunk.end >= end;\n\t\t\tif (containsEnd && chunk.edited && chunk.end !== end)\n\t\t\t\tthrow new Error(`Cannot use replaced character ${end} as slice end anchor.`);\n\n\t\t\tconst sliceStart = startChunk === chunk ? start - chunk.start : 0;\n\t\t\tconst sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;\n\n\t\t\tresult += chunk.content.slice(sliceStart, sliceEnd);\n\n\t\t\tif (chunk.outro && (!containsEnd || chunk.end === end)) {\n\t\t\t\tresult += chunk.outro;\n\t\t\t}\n\n\t\t\tif (containsEnd) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t// TODO deprecate this? not really very useful\n\tsnip(start, end) {\n\t\tconst clone = this.clone();\n\t\tclone.remove(0, start);\n\t\tclone.remove(end, clone.original.length);\n\n\t\treturn clone;\n\t}\n\n\t_split(index) {\n\t\tif (this.byStart[index] || this.byEnd[index]) return;\n\n\t\tif (DEBUG) this.stats.time('_split');\n\n\t\tlet chunk = this.lastSearchedChunk;\n\t\tconst searchForward = index > chunk.end;\n\n\t\twhile (chunk) {\n\t\t\tif (chunk.contains(index)) return this._splitChunk(chunk, index);\n\n\t\t\tchunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];\n\t\t}\n\t}\n\n\t_splitChunk(chunk, index) {\n\t\tif (chunk.edited && chunk.content.length) {\n\t\t\t// zero-length edited chunks are a special case (overlapping replacements)\n\t\t\tconst loc = getLocator(this.original)(index);\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – \"${chunk.original}\")`\n\t\t\t);\n\t\t}\n\n\t\tconst newChunk = chunk.split(index);\n\n\t\tthis.byEnd[index] = chunk;\n\t\tthis.byStart[index] = newChunk;\n\t\tthis.byEnd[newChunk.end] = newChunk;\n\n\t\tif (chunk === this.lastChunk) this.lastChunk = newChunk;\n\n\t\tthis.lastSearchedChunk = chunk;\n\t\tif (DEBUG) this.stats.timeEnd('_split');\n\t\treturn true;\n\t}\n\n\ttoString() {\n\t\tlet str = this.intro;\n\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk) {\n\t\t\tstr += chunk.toString();\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn str + this.outro;\n\t}\n\n\tisEmpty() {\n\t\tlet chunk = this.firstChunk;\n\t\tdo {\n\t\t\tif (\n\t\t\t\t(chunk.intro.length && chunk.intro.trim()) ||\n\t\t\t\t(chunk.content.length && chunk.content.trim()) ||\n\t\t\t\t(chunk.outro.length && chunk.outro.trim())\n\t\t\t)\n\t\t\t\treturn false;\n\t\t} while ((chunk = chunk.next));\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\tlet chunk = this.firstChunk;\n\t\tlet length = 0;\n\t\tdo {\n\t\t\tlength += chunk.intro.length + chunk.content.length + chunk.outro.length;\n\t\t} while ((chunk = chunk.next));\n\t\treturn length;\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimEndAborted(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tlet chunk = this.lastChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimEnd(rx);\n\n\t\t\t// if chunk was trimmed, we have a new lastChunk\n\t\t\tif (chunk.end !== end) {\n\t\t\t\tif (this.lastChunk === chunk) {\n\t\t\t\t\tthis.lastChunk = chunk.next;\n\t\t\t\t}\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.previous;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimEnd(charType) {\n\t\tthis.trimEndAborted(charType);\n\t\treturn this;\n\t}\n\ttrimStartAborted(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tlet chunk = this.firstChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimStart(rx);\n\n\t\t\tif (chunk.end !== end) {\n\t\t\t\t// special case...\n\t\t\t\tif (chunk === this.lastChunk) this.lastChunk = chunk.next;\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.next;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimStart(charType) {\n\t\tthis.trimStartAborted(charType);\n\t\treturn this;\n\t}\n}\n","import MagicString from './MagicString.js';\nimport SourceMap from './SourceMap.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\n\nconst hasOwnProp = Object.prototype.hasOwnProperty;\n\nexport default class Bundle {\n\tconstructor(options = {}) {\n\t\tthis.intro = options.intro || '';\n\t\tthis.separator = options.separator !== undefined ? options.separator : '\\n';\n\t\tthis.sources = [];\n\t\tthis.uniqueSources = [];\n\t\tthis.uniqueSourceIndexByFilename = {};\n\t}\n\n\taddSource(source) {\n\t\tif (source instanceof MagicString) {\n\t\t\treturn this.addSource({\n\t\t\t\tcontent: source,\n\t\t\t\tfilename: source.filename,\n\t\t\t\tseparator: this.separator,\n\t\t\t});\n\t\t}\n\n\t\tif (!isObject(source) || !source.content) {\n\t\t\tthrow new Error(\n\t\t\t\t'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'\n\t\t\t);\n\t\t}\n\n\t\t['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {\n\t\t\tif (!hasOwnProp.call(source, option)) source[option] = source.content[option];\n\t\t});\n\n\t\tif (source.separator === undefined) {\n\t\t\t// TODO there's a bunch of this sort of thing, needs cleaning up\n\t\t\tsource.separator = this.separator;\n\t\t}\n\n\t\tif (source.filename) {\n\t\t\tif (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {\n\t\t\t\tthis.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;\n\t\t\t\tthis.uniqueSources.push({ filename: source.filename, content: source.content.original });\n\t\t\t} else {\n\t\t\t\tconst uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];\n\t\t\t\tif (source.content.original !== uniqueSource.content) {\n\t\t\t\t\tthrow new Error(`Illegal source: same filename (${source.filename}), different contents`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.sources.push(source);\n\t\treturn this;\n\t}\n\n\tappend(str, options) {\n\t\tthis.addSource({\n\t\t\tcontent: new MagicString(str),\n\t\t\tseparator: (options && options.separator) || '',\n\t\t});\n\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst bundle = new Bundle({\n\t\t\tintro: this.intro,\n\t\t\tseparator: this.separator,\n\t\t});\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tbundle.addSource({\n\t\t\t\tfilename: source.filename,\n\t\t\t\tcontent: source.content.clone(),\n\t\t\t\tseparator: source.separator,\n\t\t\t});\n\t\t});\n\n\t\treturn bundle;\n\t}\n\n\tgenerateDecodedMap(options = {}) {\n\t\tconst names = [];\n\t\tthis.sources.forEach((source) => {\n\t\t\tObject.keys(source.content.storedNames).forEach((name) => {\n\t\t\t\tif (!~names.indexOf(name)) names.push(name);\n\t\t\t});\n\t\t});\n\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tif (i > 0) {\n\t\t\t\tmappings.advance(this.separator);\n\t\t\t}\n\n\t\t\tconst sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;\n\t\t\tconst magicString = source.content;\n\t\t\tconst locate = getLocator(magicString.original);\n\n\t\t\tif (magicString.intro) {\n\t\t\t\tmappings.advance(magicString.intro);\n\t\t\t}\n\n\t\t\tmagicString.firstChunk.eachNext((chunk) => {\n\t\t\t\tconst loc = locate(chunk.start);\n\n\t\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\t\tif (source.filename) {\n\t\t\t\t\tif (chunk.edited) {\n\t\t\t\t\t\tmappings.addEdit(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk.content,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmappings.addUneditedChunk(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk,\n\t\t\t\t\t\t\tmagicString.original,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tmagicString.sourcemapLocations\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmappings.advance(chunk.content);\n\t\t\t\t}\n\n\t\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t\t});\n\n\t\t\tif (magicString.outro) {\n\t\t\t\tmappings.advance(magicString.outro);\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : null,\n\t\t\tsources: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.file ? getRelativePath(options.file, source.filename) : source.filename;\n\t\t\t}),\n\t\t\tsourcesContent: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.includeContent ? source.content : null;\n\t\t\t}),\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\tconst indentStringCounts = {};\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tconst indentStr = source.content.indentStr;\n\n\t\t\tif (indentStr === null) return;\n\n\t\t\tif (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;\n\t\t\tindentStringCounts[indentStr] += 1;\n\t\t});\n\n\t\treturn (\n\t\t\tObject.keys(indentStringCounts).sort((a, b) => {\n\t\t\t\treturn indentStringCounts[a] - indentStringCounts[b];\n\t\t\t})[0] || '\\t'\n\t\t);\n\t}\n\n\tindent(indentStr) {\n\t\tif (!arguments.length) {\n\t\t\tindentStr = this.getIndentString();\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\tlet trailingNewline = !this.intro || this.intro.slice(-1) === '\\n';\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\tconst indentStart = trailingNewline || (i > 0 && /\\r?\\n$/.test(separator));\n\n\t\t\tsource.content.indent(indentStr, {\n\t\t\t\texclude: source.indentExclusionRanges,\n\t\t\t\tindentStart, //: trailingNewline || /\\r?\\n$/.test( separator ) //true///\\r?\\n/.test( separator )\n\t\t\t});\n\n\t\t\ttrailingNewline = source.content.lastChar() === '\\n';\n\t\t});\n\n\t\tif (this.intro) {\n\t\t\tthis.intro =\n\t\t\t\tindentStr +\n\t\t\t\tthis.intro.replace(/^[^\\n]/gm, (match, index) => {\n\t\t\t\t\treturn index > 0 ? indentStr + match : match;\n\t\t\t\t});\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tprepend(str) {\n\t\tthis.intro = str + this.intro;\n\t\treturn this;\n\t}\n\n\ttoString() {\n\t\tconst body = this.sources\n\t\t\t.map((source, i) => {\n\t\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\t\tconst str = (i > 0 ? separator : '') + source.content.toString();\n\n\t\t\t\treturn str;\n\t\t\t})\n\t\t\t.join('');\n\n\t\treturn this.intro + body;\n\t}\n\n\tisEmpty() {\n\t\tif (this.intro.length && this.intro.trim()) return false;\n\t\tif (this.sources.some((source) => !source.content.isEmpty())) return false;\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\treturn this.sources.reduce(\n\t\t\t(length, source) => length + source.content.length(),\n\t\t\tthis.intro.length\n\t\t);\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimStart(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\t\tthis.intro = this.intro.replace(rx, '');\n\n\t\tif (!this.intro) {\n\t\t\tlet source;\n\t\t\tlet i = 0;\n\n\t\t\tdo {\n\t\t\t\tsource = this.sources[i++];\n\t\t\t\tif (!source) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} while (!source.content.trimStartAborted(charType));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\ttrimEnd(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tlet source;\n\t\tlet i = this.sources.length - 1;\n\n\t\tdo {\n\t\t\tsource = this.sources[i--];\n\t\t\tif (!source) {\n\t\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (!source.content.trimEndAborted(charType));\n\n\t\treturn this;\n\t}\n}\n","import MagicString from './MagicString.js';\nimport Bundle from './Bundle.js';\nimport SourceMap from './SourceMap.js';\n\nMagicString.Bundle = Bundle;\nMagicString.SourceMap = SourceMap;\nMagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121\n\nexport default MagicString;\n"],"names":["const","let","encode","this"],"mappings":";;;;AAAe,IAAM,MAAM,GAC1B,eAAW,CAAC,GAAG,EAAE;AAClB,CAAE,IAAI,CAAC,IAAI,GAAG,GAAG,YAAY,MAAM,GAAG,GA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AAM;AACX,IAAK;AACL,GAAI,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE;AACxD,EAAG;AACH;AACA,CAAE,OAAO,IAAI,CAAC;AACb,EAAC;AACF;iBACC,4BAAQ,QAAQ,EAAE;AACnB,CAAED,IAAM,EAAE,GAAG,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC;AACpD;AACA,CAAEC,IAAI,MAAM,CAAC;AACb,CAAEA,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;AAClC;AACA,CAAE,GAAG;AACL,EAAG,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;AAC9B,EAAG,IAAI,CAAC,MAAM,EAAE;AAChB,GAAI,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC5C,GAAI,MAAM;AACV,GAAI;AACJ,EAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE;AACrD;AACA,CAAE,OAAO,IAAI,CAAC;AACb;;AC1RD,WAAW,CAAC,MAAM,GAAG,MAAM,CAAC;AAC5B,WAAW,CAAC,SAAS,GAAG,SAAS,CAAC;AAClC,WAAW,CAAC,OAAO,GAAG,WAAW,CAAC;;;;"} \ No newline at end of file diff --git a/node_modules/magic-string/dist/magic-string.es.js b/node_modules/magic-string/dist/magic-string.es.js new file mode 100644 index 0000000..f6b409a --- /dev/null +++ b/node_modules/magic-string/dist/magic-string.es.js @@ -0,0 +1,1305 @@ +import { encode } from 'sourcemap-codec'; + +var BitSet = function BitSet(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; +}; + +BitSet.prototype.add = function add (n) { + this.bits[n >> 5] |= 1 << (n & 31); +}; + +BitSet.prototype.has = function has (n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); +}; + +var Chunk = function Chunk(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + // we make these non-enumerable, for sanity while debugging + Object.defineProperties(this, { + previous: { writable: true, value: null }, + next: { writable: true, value: null }, + }); +}; + +Chunk.prototype.appendLeft = function appendLeft (content) { + this.outro += content; +}; + +Chunk.prototype.appendRight = function appendRight (content) { + this.intro = this.intro + content; +}; + +Chunk.prototype.clone = function clone () { + var chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; +}; + +Chunk.prototype.contains = function contains (index) { + return this.start < index && index < this.end; +}; + +Chunk.prototype.eachNext = function eachNext (fn) { + var chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } +}; + +Chunk.prototype.eachPrevious = function eachPrevious (fn) { + var chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } +}; + +Chunk.prototype.edit = function edit (content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; +}; + +Chunk.prototype.prependLeft = function prependLeft (content) { + this.outro = content + this.outro; +}; + +Chunk.prototype.prependRight = function prependRight (content) { + this.intro = content + this.intro; +}; + +Chunk.prototype.split = function split (index) { + var sliceIndex = index - this.start; + + var originalBefore = this.original.slice(0, sliceIndex); + var originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + var newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) { newChunk.next.previous = newChunk; } + newChunk.previous = this; + this.next = newChunk; + + return newChunk; +}; + +Chunk.prototype.toString = function toString () { + return this.intro + this.content + this.outro; +}; + +Chunk.prototype.trimEnd = function trimEnd (rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + + var trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + } +}; + +Chunk.prototype.trimStart = function trimStart (rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + + var trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.end - trimmed.length); + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + } +}; + +var btoa = function () { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); +}; +if (typeof window !== 'undefined' && typeof window.btoa === 'function') { + btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); }; +} else if (typeof Buffer === 'function') { + btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); }; +} + +var SourceMap = function SourceMap(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode(properties.mappings); +}; + +SourceMap.prototype.toString = function toString () { + return JSON.stringify(this); +}; + +SourceMap.prototype.toUrl = function toUrl () { + return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); +}; + +function guessIndent(code) { + var lines = code.split('\n'); + + var tabbed = lines.filter(function (line) { return /^\t+/.test(line); }); + var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); }); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + var min = spaced.reduce(function (previous, current) { + var numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + var fromParts = from.split(/[/\\]/); + var toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + var i = fromParts.length; + while (i--) { fromParts[i] = '..'; } + } + + return fromParts.concat(toParts).join('/'); +} + +var toString = Object.prototype.toString; + +function isObject(thing) { + return toString.call(thing) === '[object Object]'; +} + +function getLocator(source) { + var originalLines = source.split('\n'); + var lineOffsets = []; + + for (var i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + var i = 0; + var j = lineOffsets.length; + while (i < j) { + var m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + var line = i - 1; + var column = index - lineOffsets[line]; + return { line: line, column: column }; + }; +} + +var Mappings = function Mappings(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; +}; + +Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) { + if (content.length) { + var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + } else if (this.pending) { + this.rawSegments.push(this.pending); + } + + this.advance(content); + this.pending = null; +}; + +Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) { + var originalCharIndex = chunk.start; + var first = true; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; +}; + +Mappings.prototype.advance = function advance (str) { + if (!str) { return; } + + var lines = str.split('\n'); + + if (lines.length > 1) { + for (var i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; +}; + +var n = '\n'; + +var warned = { + insertLeft: false, + insertRight: false, + storeName: false, +}; + +var MagicString = function MagicString(string, options) { + if ( options === void 0 ) options = {}; + + var chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: guessIndent(string) }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; +}; + +MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) { + this.sourcemapLocations.add(char); +}; + +MagicString.prototype.append = function append (content) { + if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } + + this.outro += content; + return this; +}; + +MagicString.prototype.appendLeft = function appendLeft (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; +}; + +MagicString.prototype.appendRight = function appendRight (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; +}; + +MagicString.prototype.clone = function clone () { + var cloned = new MagicString(this.original, { filename: this.filename }); + + var originalChunk = this.firstChunk; + var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + var nextOriginalChunk = originalChunk.next; + var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; +}; + +MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) { + var this$1$1 = this; + + options = options || {}; + + var sourceIndex = 0; + var names = Object.keys(this.storedNames); + var mappings = new Mappings(options.hires); + + var locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext(function (chunk) { + var loc = locate(chunk.start); + + if (chunk.intro.length) { mappings.advance(chunk.intro); } + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1 + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations); + } + + if (chunk.outro.length) { mappings.advance(chunk.outro); } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : null, + sources: [options.source ? getRelativePath(options.file || '', options.source) : null], + sourcesContent: options.includeContent ? [this.original] : [null], + names: names, + mappings: mappings.raw, + }; +}; + +MagicString.prototype.generateMap = function generateMap (options) { + return new SourceMap(this.generateDecodedMap(options)); +}; + +MagicString.prototype.getIndentString = function getIndentString () { + return this.indentStr === null ? '\t' : this.indentStr; +}; + +MagicString.prototype.indent = function indent (indentStr, options) { + var pattern = /^[^\r\n]/gm; + + if (isObject(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t'; + + if (indentStr === '') { return this; } // noop + + options = options || {}; + + // Process exclusion ranges + var isExcluded = {}; + + if (options.exclude) { + var exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach(function (exclusion) { + for (var i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + var shouldIndentNextCharacter = options.indentStart !== false; + var replacer = function (match) { + if (shouldIndentNextCharacter) { return ("" + indentStr + match); } + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + var charIndex = 0; + var chunk = this.firstChunk; + + while (chunk) { + var end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + var char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; +}; + +MagicString.prototype.insert = function insert () { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' + ); +}; + +MagicString.prototype.insertLeft = function insertLeft (index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); +}; + +MagicString.prototype.insertRight = function insertRight (index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); +}; + +MagicString.prototype.move = function move (start, end, index) { + if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); } + + this._split(start); + this._split(end); + this._split(index); + + var first = this.byStart[start]; + var last = this.byEnd[end]; + + var oldLeft = first.previous; + var oldRight = last.next; + + var newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) { return this; } + var newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) { oldLeft.next = oldRight; } + if (oldRight) { oldRight.previous = oldLeft; } + + if (newLeft) { newLeft.next = first; } + if (newRight) { newRight.previous = last; } + + if (!first.previous) { this.firstChunk = last.next; } + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) { this.firstChunk = first; } + if (!newRight) { this.lastChunk = last; } + return this; +}; + +MagicString.prototype.overwrite = function overwrite (start, end, content, options) { + if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); } + + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + if (end > this.original.length) { throw new Error('end is out of bounds'); } + if (start === end) + { throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' + ); } + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + var storeName = options !== undefined ? options.storeName : false; + var contentOnly = options !== undefined ? options.contentOnly : false; + + if (storeName) { + var original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true }); + } + + var first = this.byStart[start]; + var last = this.byEnd[end]; + + if (first) { + var chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, contentOnly); + } else { + // must be inserting at the end + var newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; +}; + +MagicString.prototype.prepend = function prepend (content) { + if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } + + this.intro = content + this.intro; + return this; +}; + +MagicString.prototype.prependLeft = function prependLeft (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; +}; + +MagicString.prototype.prependRight = function prependRight (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; +}; + +MagicString.prototype.remove = function remove (start, end) { + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + if (start === end) { return this; } + + if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); } + if (start > end) { throw new Error('end must be greater than start'); } + + this._split(start); + this._split(end); + + var chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; +}; + +MagicString.prototype.lastChar = function lastChar () { + if (this.outro.length) { return this.outro[this.outro.length - 1]; } + var chunk = this.lastChunk; + do { + if (chunk.outro.length) { return chunk.outro[chunk.outro.length - 1]; } + if (chunk.content.length) { return chunk.content[chunk.content.length - 1]; } + if (chunk.intro.length) { return chunk.intro[chunk.intro.length - 1]; } + } while ((chunk = chunk.previous)); + if (this.intro.length) { return this.intro[this.intro.length - 1]; } + return ''; +}; + +MagicString.prototype.lastLine = function lastLine () { + var lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) { return this.outro.substr(lineIndex + 1); } + var lineStr = this.outro; + var chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) { return chunk.outro.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) { return chunk.content.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) { return chunk.intro.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) { return this.intro.substr(lineIndex + 1) + lineStr; } + return this.intro + lineStr; +}; + +MagicString.prototype.slice = function slice (start, end) { + if ( start === void 0 ) start = 0; + if ( end === void 0 ) end = this.original.length; + + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + var result = ''; + + // find start chunk + var chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); } + + var startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + var containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); } + + var sliceStart = startChunk === chunk ? start - chunk.start : 0; + var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; +}; + +// TODO deprecate this? not really very useful +MagicString.prototype.snip = function snip (start, end) { + var clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; +}; + +MagicString.prototype._split = function _split (index) { + if (this.byStart[index] || this.byEnd[index]) { return; } + + var chunk = this.lastSearchedChunk; + var searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) { return this._splitChunk(chunk, index); } + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } +}; + +MagicString.prototype._splitChunk = function _splitChunk (chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + var loc = getLocator(this.original)(index); + throw new Error( + ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") + ); + } + + var newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) { this.lastChunk = newChunk; } + + this.lastSearchedChunk = chunk; + return true; +}; + +MagicString.prototype.toString = function toString () { + var str = this.intro; + + var chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; +}; + +MagicString.prototype.isEmpty = function isEmpty () { + var chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + { return false; } + } while ((chunk = chunk.next)); + return true; +}; + +MagicString.prototype.length = function length () { + var chunk = this.firstChunk; + var length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; +}; + +MagicString.prototype.trimLines = function trimLines () { + return this.trim('[\\r\\n]'); +}; + +MagicString.prototype.trim = function trim (charType) { + return this.trimStart(charType).trimEnd(charType); +}; + +MagicString.prototype.trimEndAborted = function trimEndAborted (charType) { + var rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + + var chunk = this.lastChunk; + + do { + var end = chunk.end; + var aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) { return true; } + chunk = chunk.previous; + } while (chunk); + + return false; +}; + +MagicString.prototype.trimEnd = function trimEnd (charType) { + this.trimEndAborted(charType); + return this; +}; +MagicString.prototype.trimStartAborted = function trimStartAborted (charType) { + var rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + + var chunk = this.firstChunk; + + do { + var end = chunk.end; + var aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) { this.lastChunk = chunk.next; } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) { return true; } + chunk = chunk.next; + } while (chunk); + + return false; +}; + +MagicString.prototype.trimStart = function trimStart (charType) { + this.trimStartAborted(charType); + return this; +}; + +var hasOwnProp = Object.prototype.hasOwnProperty; + +var Bundle = function Bundle(options) { + if ( options === void 0 ) options = {}; + + this.intro = options.intro || ''; + this.separator = options.separator !== undefined ? options.separator : '\n'; + this.sources = []; + this.uniqueSources = []; + this.uniqueSourceIndexByFilename = {}; +}; + +Bundle.prototype.addSource = function addSource (source) { + if (source instanceof MagicString) { + return this.addSource({ + content: source, + filename: source.filename, + separator: this.separator, + }); + } + + if (!isObject(source) || !source.content) { + throw new Error( + 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`' + ); + } + + ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) { + if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; } + }); + + if (source.separator === undefined) { + // TODO there's a bunch of this sort of thing, needs cleaning up + source.separator = this.separator; + } + + if (source.filename) { + if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) { + this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length; + this.uniqueSources.push({ filename: source.filename, content: source.content.original }); + } else { + var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]]; + if (source.content.original !== uniqueSource.content) { + throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents")); + } + } + } + + this.sources.push(source); + return this; +}; + +Bundle.prototype.append = function append (str, options) { + this.addSource({ + content: new MagicString(str), + separator: (options && options.separator) || '', + }); + + return this; +}; + +Bundle.prototype.clone = function clone () { + var bundle = new Bundle({ + intro: this.intro, + separator: this.separator, + }); + + this.sources.forEach(function (source) { + bundle.addSource({ + filename: source.filename, + content: source.content.clone(), + separator: source.separator, + }); + }); + + return bundle; +}; + +Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) { + var this$1$1 = this; + if ( options === void 0 ) options = {}; + + var names = []; + this.sources.forEach(function (source) { + Object.keys(source.content.storedNames).forEach(function (name) { + if (!~names.indexOf(name)) { names.push(name); } + }); + }); + + var mappings = new Mappings(options.hires); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.sources.forEach(function (source, i) { + if (i > 0) { + mappings.advance(this$1$1.separator); + } + + var sourceIndex = source.filename ? this$1$1.uniqueSourceIndexByFilename[source.filename] : -1; + var magicString = source.content; + var locate = getLocator(magicString.original); + + if (magicString.intro) { + mappings.advance(magicString.intro); + } + + magicString.firstChunk.eachNext(function (chunk) { + var loc = locate(chunk.start); + + if (chunk.intro.length) { mappings.advance(chunk.intro); } + + if (source.filename) { + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1 + ); + } else { + mappings.addUneditedChunk( + sourceIndex, + chunk, + magicString.original, + loc, + magicString.sourcemapLocations + ); + } + } else { + mappings.advance(chunk.content); + } + + if (chunk.outro.length) { mappings.advance(chunk.outro); } + }); + + if (magicString.outro) { + mappings.advance(magicString.outro); + } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : null, + sources: this.uniqueSources.map(function (source) { + return options.file ? getRelativePath(options.file, source.filename) : source.filename; + }), + sourcesContent: this.uniqueSources.map(function (source) { + return options.includeContent ? source.content : null; + }), + names: names, + mappings: mappings.raw, + }; +}; + +Bundle.prototype.generateMap = function generateMap (options) { + return new SourceMap(this.generateDecodedMap(options)); +}; + +Bundle.prototype.getIndentString = function getIndentString () { + var indentStringCounts = {}; + + this.sources.forEach(function (source) { + var indentStr = source.content.indentStr; + + if (indentStr === null) { return; } + + if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; } + indentStringCounts[indentStr] += 1; + }); + + return ( + Object.keys(indentStringCounts).sort(function (a, b) { + return indentStringCounts[a] - indentStringCounts[b]; + })[0] || '\t' + ); +}; + +Bundle.prototype.indent = function indent (indentStr) { + var this$1$1 = this; + + if (!arguments.length) { + indentStr = this.getIndentString(); + } + + if (indentStr === '') { return this; } // noop + + var trailingNewline = !this.intro || this.intro.slice(-1) === '\n'; + + this.sources.forEach(function (source, i) { + var separator = source.separator !== undefined ? source.separator : this$1$1.separator; + var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator)); + + source.content.indent(indentStr, { + exclude: source.indentExclusionRanges, + indentStart: indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator ) + }); + + trailingNewline = source.content.lastChar() === '\n'; + }); + + if (this.intro) { + this.intro = + indentStr + + this.intro.replace(/^[^\n]/gm, function (match, index) { + return index > 0 ? indentStr + match : match; + }); + } + + return this; +}; + +Bundle.prototype.prepend = function prepend (str) { + this.intro = str + this.intro; + return this; +}; + +Bundle.prototype.toString = function toString () { + var this$1$1 = this; + + var body = this.sources + .map(function (source, i) { + var separator = source.separator !== undefined ? source.separator : this$1$1.separator; + var str = (i > 0 ? separator : '') + source.content.toString(); + + return str; + }) + .join(''); + + return this.intro + body; +}; + +Bundle.prototype.isEmpty = function isEmpty () { + if (this.intro.length && this.intro.trim()) { return false; } + if (this.sources.some(function (source) { return !source.content.isEmpty(); })) { return false; } + return true; +}; + +Bundle.prototype.length = function length () { + return this.sources.reduce( + function (length, source) { return length + source.content.length(); }, + this.intro.length + ); +}; + +Bundle.prototype.trimLines = function trimLines () { + return this.trim('[\\r\\n]'); +}; + +Bundle.prototype.trim = function trim (charType) { + return this.trimStart(charType).trimEnd(charType); +}; + +Bundle.prototype.trimStart = function trimStart (charType) { + var rx = new RegExp('^' + (charType || '\\s') + '+'); + this.intro = this.intro.replace(rx, ''); + + if (!this.intro) { + var source; + var i = 0; + + do { + source = this.sources[i++]; + if (!source) { + break; + } + } while (!source.content.trimStartAborted(charType)); + } + + return this; +}; + +Bundle.prototype.trimEnd = function trimEnd (charType) { + var rx = new RegExp((charType || '\\s') + '+$'); + + var source; + var i = this.sources.length - 1; + + do { + source = this.sources[i--]; + if (!source) { + this.intro = this.intro.replace(rx, ''); + break; + } + } while (!source.content.trimEndAborted(charType)); + + return this; +}; + +export { Bundle, SourceMap, MagicString as default }; +//# sourceMappingURL=magic-string.es.js.map diff --git a/node_modules/magic-string/dist/magic-string.es.js.map b/node_modules/magic-string/dist/magic-string.es.js.map new file mode 100644 index 0000000..4624dd8 --- /dev/null +++ b/node_modules/magic-string/dist/magic-string.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"magic-string.es.js","sources":["../src/BitSet.js","../src/Chunk.js","../src/SourceMap.js","../src/utils/guessIndent.js","../src/utils/getRelativePath.js","../src/utils/isObject.js","../src/utils/getLocator.js","../src/utils/Mappings.js","../src/MagicString.js","../src/Bundle.js"],"sourcesContent":["export default class BitSet {\n\tconstructor(arg) {\n\t\tthis.bits = arg instanceof BitSet ? arg.bits.slice() : [];\n\t}\n\n\tadd(n) {\n\t\tthis.bits[n >> 5] |= 1 << (n & 31);\n\t}\n\n\thas(n) {\n\t\treturn !!(this.bits[n >> 5] & (1 << (n & 31)));\n\t}\n}\n","export default class Chunk {\n\tconstructor(start, end, content) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tthis.original = content;\n\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\n\t\tthis.content = content;\n\t\tthis.storeName = false;\n\t\tthis.edited = false;\n\n\t\t// we make these non-enumerable, for sanity while debugging\n\t\tObject.defineProperties(this, {\n\t\t\tprevious: { writable: true, value: null },\n\t\t\tnext: { writable: true, value: null },\n\t\t});\n\t}\n\n\tappendLeft(content) {\n\t\tthis.outro += content;\n\t}\n\n\tappendRight(content) {\n\t\tthis.intro = this.intro + content;\n\t}\n\n\tclone() {\n\t\tconst chunk = new Chunk(this.start, this.end, this.original);\n\n\t\tchunk.intro = this.intro;\n\t\tchunk.outro = this.outro;\n\t\tchunk.content = this.content;\n\t\tchunk.storeName = this.storeName;\n\t\tchunk.edited = this.edited;\n\n\t\treturn chunk;\n\t}\n\n\tcontains(index) {\n\t\treturn this.start < index && index < this.end;\n\t}\n\n\teachNext(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.next;\n\t\t}\n\t}\n\n\teachPrevious(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.previous;\n\t\t}\n\t}\n\n\tedit(content, storeName, contentOnly) {\n\t\tthis.content = content;\n\t\tif (!contentOnly) {\n\t\t\tthis.intro = '';\n\t\t\tthis.outro = '';\n\t\t}\n\t\tthis.storeName = storeName;\n\n\t\tthis.edited = true;\n\n\t\treturn this;\n\t}\n\n\tprependLeft(content) {\n\t\tthis.outro = content + this.outro;\n\t}\n\n\tprependRight(content) {\n\t\tthis.intro = content + this.intro;\n\t}\n\n\tsplit(index) {\n\t\tconst sliceIndex = index - this.start;\n\n\t\tconst originalBefore = this.original.slice(0, sliceIndex);\n\t\tconst originalAfter = this.original.slice(sliceIndex);\n\n\t\tthis.original = originalBefore;\n\n\t\tconst newChunk = new Chunk(index, this.end, originalAfter);\n\t\tnewChunk.outro = this.outro;\n\t\tthis.outro = '';\n\n\t\tthis.end = index;\n\n\t\tif (this.edited) {\n\t\t\t// TODO is this block necessary?...\n\t\t\tnewChunk.edit('', false);\n\t\t\tthis.content = '';\n\t\t} else {\n\t\t\tthis.content = originalBefore;\n\t\t}\n\n\t\tnewChunk.next = this.next;\n\t\tif (newChunk.next) newChunk.next.previous = newChunk;\n\t\tnewChunk.previous = this;\n\t\tthis.next = newChunk;\n\n\t\treturn newChunk;\n\t}\n\n\ttoString() {\n\t\treturn this.intro + this.content + this.outro;\n\t}\n\n\ttrimEnd(rx) {\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.start + trimmed.length).edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\tif (this.intro.length) return true;\n\t\t}\n\t}\n\n\ttrimStart(rx) {\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.end - trimmed.length);\n\t\t\t\tthis.edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.outro = this.outro.replace(rx, '');\n\t\t\tif (this.outro.length) return true;\n\t\t}\n\t}\n}\n","import { encode } from 'sourcemap-codec';\n\nlet btoa = () => {\n\tthrow new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');\n};\nif (typeof window !== 'undefined' && typeof window.btoa === 'function') {\n\tbtoa = (str) => window.btoa(unescape(encodeURIComponent(str)));\n} else if (typeof Buffer === 'function') {\n\tbtoa = (str) => Buffer.from(str, 'utf-8').toString('base64');\n}\n\nexport default class SourceMap {\n\tconstructor(properties) {\n\t\tthis.version = 3;\n\t\tthis.file = properties.file;\n\t\tthis.sources = properties.sources;\n\t\tthis.sourcesContent = properties.sourcesContent;\n\t\tthis.names = properties.names;\n\t\tthis.mappings = encode(properties.mappings);\n\t}\n\n\ttoString() {\n\t\treturn JSON.stringify(this);\n\t}\n\n\ttoUrl() {\n\t\treturn 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());\n\t}\n}\n","export default function guessIndent(code) {\n\tconst lines = code.split('\\n');\n\n\tconst tabbed = lines.filter((line) => /^\\t+/.test(line));\n\tconst spaced = lines.filter((line) => /^ {2,}/.test(line));\n\n\tif (tabbed.length === 0 && spaced.length === 0) {\n\t\treturn null;\n\t}\n\n\t// More lines tabbed than spaced? Assume tabs, and\n\t// default to tabs in the case of a tie (or nothing\n\t// to go on)\n\tif (tabbed.length >= spaced.length) {\n\t\treturn '\\t';\n\t}\n\n\t// Otherwise, we need to guess the multiple\n\tconst min = spaced.reduce((previous, current) => {\n\t\tconst numSpaces = /^ +/.exec(current)[0].length;\n\t\treturn Math.min(numSpaces, previous);\n\t}, Infinity);\n\n\treturn new Array(min + 1).join(' ');\n}\n","export default function getRelativePath(from, to) {\n\tconst fromParts = from.split(/[/\\\\]/);\n\tconst toParts = to.split(/[/\\\\]/);\n\n\tfromParts.pop(); // get dirname\n\n\twhile (fromParts[0] === toParts[0]) {\n\t\tfromParts.shift();\n\t\ttoParts.shift();\n\t}\n\n\tif (fromParts.length) {\n\t\tlet i = fromParts.length;\n\t\twhile (i--) fromParts[i] = '..';\n\t}\n\n\treturn fromParts.concat(toParts).join('/');\n}\n","const toString = Object.prototype.toString;\n\nexport default function isObject(thing) {\n\treturn toString.call(thing) === '[object Object]';\n}\n","export default function getLocator(source) {\n\tconst originalLines = source.split('\\n');\n\tconst lineOffsets = [];\n\n\tfor (let i = 0, pos = 0; i < originalLines.length; i++) {\n\t\tlineOffsets.push(pos);\n\t\tpos += originalLines[i].length + 1;\n\t}\n\n\treturn function locate(index) {\n\t\tlet i = 0;\n\t\tlet j = lineOffsets.length;\n\t\twhile (i < j) {\n\t\t\tconst m = (i + j) >> 1;\n\t\t\tif (index < lineOffsets[m]) {\n\t\t\t\tj = m;\n\t\t\t} else {\n\t\t\t\ti = m + 1;\n\t\t\t}\n\t\t}\n\t\tconst line = i - 1;\n\t\tconst column = index - lineOffsets[line];\n\t\treturn { line, column };\n\t};\n}\n","export default class Mappings {\n\tconstructor(hires) {\n\t\tthis.hires = hires;\n\t\tthis.generatedCodeLine = 0;\n\t\tthis.generatedCodeColumn = 0;\n\t\tthis.raw = [];\n\t\tthis.rawSegments = this.raw[this.generatedCodeLine] = [];\n\t\tthis.pending = null;\n\t}\n\n\taddEdit(sourceIndex, content, loc, nameIndex) {\n\t\tif (content.length) {\n\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\tif (nameIndex >= 0) {\n\t\t\t\tsegment.push(nameIndex);\n\t\t\t}\n\t\t\tthis.rawSegments.push(segment);\n\t\t} else if (this.pending) {\n\t\t\tthis.rawSegments.push(this.pending);\n\t\t}\n\n\t\tthis.advance(content);\n\t\tthis.pending = null;\n\t}\n\n\taddUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {\n\t\tlet originalCharIndex = chunk.start;\n\t\tlet first = true;\n\n\t\twhile (originalCharIndex < chunk.end) {\n\t\t\tif (this.hires || first || sourcemapLocations.has(originalCharIndex)) {\n\t\t\t\tthis.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);\n\t\t\t}\n\n\t\t\tif (original[originalCharIndex] === '\\n') {\n\t\t\t\tloc.line += 1;\n\t\t\t\tloc.column = 0;\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\t\t\t\tfirst = true;\n\t\t\t} else {\n\t\t\t\tloc.column += 1;\n\t\t\t\tthis.generatedCodeColumn += 1;\n\t\t\t\tfirst = false;\n\t\t\t}\n\n\t\t\toriginalCharIndex += 1;\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\tadvance(str) {\n\t\tif (!str) return;\n\n\t\tconst lines = str.split('\\n');\n\n\t\tif (lines.length > 1) {\n\t\t\tfor (let i = 0; i < lines.length - 1; i++) {\n\t\t\t\tthis.generatedCodeLine++;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t}\n\t\t\tthis.generatedCodeColumn = 0;\n\t\t}\n\n\t\tthis.generatedCodeColumn += lines[lines.length - 1].length;\n\t}\n}\n","import BitSet from './BitSet.js';\nimport Chunk from './Chunk.js';\nimport SourceMap from './SourceMap.js';\nimport guessIndent from './utils/guessIndent.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\nimport Stats from './utils/Stats.js';\n\nconst n = '\\n';\n\nconst warned = {\n\tinsertLeft: false,\n\tinsertRight: false,\n\tstoreName: false,\n};\n\nexport default class MagicString {\n\tconstructor(string, options = {}) {\n\t\tconst chunk = new Chunk(0, string.length, string);\n\n\t\tObject.defineProperties(this, {\n\t\t\toriginal: { writable: true, value: string },\n\t\t\toutro: { writable: true, value: '' },\n\t\t\tintro: { writable: true, value: '' },\n\t\t\tfirstChunk: { writable: true, value: chunk },\n\t\t\tlastChunk: { writable: true, value: chunk },\n\t\t\tlastSearchedChunk: { writable: true, value: chunk },\n\t\t\tbyStart: { writable: true, value: {} },\n\t\t\tbyEnd: { writable: true, value: {} },\n\t\t\tfilename: { writable: true, value: options.filename },\n\t\t\tindentExclusionRanges: { writable: true, value: options.indentExclusionRanges },\n\t\t\tsourcemapLocations: { writable: true, value: new BitSet() },\n\t\t\tstoredNames: { writable: true, value: {} },\n\t\t\tindentStr: { writable: true, value: guessIndent(string) },\n\t\t});\n\n\t\tif (DEBUG) {\n\t\t\tObject.defineProperty(this, 'stats', { value: new Stats() });\n\t\t}\n\n\t\tthis.byStart[0] = chunk;\n\t\tthis.byEnd[string.length] = chunk;\n\t}\n\n\taddSourcemapLocation(char) {\n\t\tthis.sourcemapLocations.add(char);\n\t}\n\n\tappend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.outro += content;\n\t\treturn this;\n\t}\n\n\tappendLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendLeft');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendLeft(content);\n\t\t} else {\n\t\t\tthis.intro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendLeft');\n\t\treturn this;\n\t}\n\n\tappendRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendRight(content);\n\t\t} else {\n\t\t\tthis.outro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendRight');\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst cloned = new MagicString(this.original, { filename: this.filename });\n\n\t\tlet originalChunk = this.firstChunk;\n\t\tlet clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());\n\n\t\twhile (originalChunk) {\n\t\t\tcloned.byStart[clonedChunk.start] = clonedChunk;\n\t\t\tcloned.byEnd[clonedChunk.end] = clonedChunk;\n\n\t\t\tconst nextOriginalChunk = originalChunk.next;\n\t\t\tconst nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();\n\n\t\t\tif (nextClonedChunk) {\n\t\t\t\tclonedChunk.next = nextClonedChunk;\n\t\t\t\tnextClonedChunk.previous = clonedChunk;\n\n\t\t\t\tclonedChunk = nextClonedChunk;\n\t\t\t}\n\n\t\t\toriginalChunk = nextOriginalChunk;\n\t\t}\n\n\t\tcloned.lastChunk = clonedChunk;\n\n\t\tif (this.indentExclusionRanges) {\n\t\t\tcloned.indentExclusionRanges = this.indentExclusionRanges.slice();\n\t\t}\n\n\t\tcloned.sourcemapLocations = new BitSet(this.sourcemapLocations);\n\n\t\tcloned.intro = this.intro;\n\t\tcloned.outro = this.outro;\n\n\t\treturn cloned;\n\t}\n\n\tgenerateDecodedMap(options) {\n\t\toptions = options || {};\n\n\t\tconst sourceIndex = 0;\n\t\tconst names = Object.keys(this.storedNames);\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tconst locate = getLocator(this.original);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.firstChunk.eachNext((chunk) => {\n\t\t\tconst loc = locate(chunk.start);\n\n\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tmappings.addEdit(\n\t\t\t\t\tsourceIndex,\n\t\t\t\t\tchunk.content,\n\t\t\t\t\tloc,\n\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);\n\t\t\t}\n\n\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : null,\n\t\t\tsources: [options.source ? getRelativePath(options.file || '', options.source) : null],\n\t\t\tsourcesContent: options.includeContent ? [this.original] : [null],\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\treturn this.indentStr === null ? '\\t' : this.indentStr;\n\t}\n\n\tindent(indentStr, options) {\n\t\tconst pattern = /^[^\\r\\n]/gm;\n\n\t\tif (isObject(indentStr)) {\n\t\t\toptions = indentStr;\n\t\t\tindentStr = undefined;\n\t\t}\n\n\t\tindentStr = indentStr !== undefined ? indentStr : this.indentStr || '\\t';\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\toptions = options || {};\n\n\t\t// Process exclusion ranges\n\t\tconst isExcluded = {};\n\n\t\tif (options.exclude) {\n\t\t\tconst exclusions =\n\t\t\t\ttypeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;\n\t\t\texclusions.forEach((exclusion) => {\n\t\t\t\tfor (let i = exclusion[0]; i < exclusion[1]; i += 1) {\n\t\t\t\t\tisExcluded[i] = true;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tlet shouldIndentNextCharacter = options.indentStart !== false;\n\t\tconst replacer = (match) => {\n\t\t\tif (shouldIndentNextCharacter) return `${indentStr}${match}`;\n\t\t\tshouldIndentNextCharacter = true;\n\t\t\treturn match;\n\t\t};\n\n\t\tthis.intro = this.intro.replace(pattern, replacer);\n\n\t\tlet charIndex = 0;\n\t\tlet chunk = this.firstChunk;\n\n\t\twhile (chunk) {\n\t\t\tconst end = chunk.end;\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\tchunk.content = chunk.content.replace(pattern, replacer);\n\n\t\t\t\t\tif (chunk.content.length) {\n\t\t\t\t\t\tshouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\\n';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcharIndex = chunk.start;\n\n\t\t\t\twhile (charIndex < end) {\n\t\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\t\tconst char = this.original[charIndex];\n\n\t\t\t\t\t\tif (char === '\\n') {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = true;\n\t\t\t\t\t\t} else if (char !== '\\r' && shouldIndentNextCharacter) {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = false;\n\n\t\t\t\t\t\t\tif (charIndex === chunk.start) {\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthis._splitChunk(chunk, charIndex);\n\t\t\t\t\t\t\t\tchunk = chunk.next;\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcharIndex += 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcharIndex = chunk.end;\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tthis.outro = this.outro.replace(pattern, replacer);\n\n\t\treturn this;\n\t}\n\n\tinsert() {\n\t\tthrow new Error(\n\t\t\t'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'\n\t\t);\n\t}\n\n\tinsertLeft(index, content) {\n\t\tif (!warned.insertLeft) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertLeft = true;\n\t\t}\n\n\t\treturn this.appendLeft(index, content);\n\t}\n\n\tinsertRight(index, content) {\n\t\tif (!warned.insertRight) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertRight = true;\n\t\t}\n\n\t\treturn this.prependRight(index, content);\n\t}\n\n\tmove(start, end, index) {\n\t\tif (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');\n\n\t\tif (DEBUG) this.stats.time('move');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\t\tthis._split(index);\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tconst oldLeft = first.previous;\n\t\tconst oldRight = last.next;\n\n\t\tconst newRight = this.byStart[index];\n\t\tif (!newRight && last === this.lastChunk) return this;\n\t\tconst newLeft = newRight ? newRight.previous : this.lastChunk;\n\n\t\tif (oldLeft) oldLeft.next = oldRight;\n\t\tif (oldRight) oldRight.previous = oldLeft;\n\n\t\tif (newLeft) newLeft.next = first;\n\t\tif (newRight) newRight.previous = last;\n\n\t\tif (!first.previous) this.firstChunk = last.next;\n\t\tif (!last.next) {\n\t\t\tthis.lastChunk = first.previous;\n\t\t\tthis.lastChunk.next = null;\n\t\t}\n\n\t\tfirst.previous = newLeft;\n\t\tlast.next = newRight || null;\n\n\t\tif (!newLeft) this.firstChunk = first;\n\t\tif (!newRight) this.lastChunk = last;\n\n\t\tif (DEBUG) this.stats.timeEnd('move');\n\t\treturn this;\n\t}\n\n\toverwrite(start, end, content, options) {\n\t\tif (typeof content !== 'string') throw new TypeError('replacement content must be a string');\n\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (end > this.original.length) throw new Error('end is out of bounds');\n\t\tif (start === end)\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'\n\t\t\t);\n\n\t\tif (DEBUG) this.stats.time('overwrite');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tif (options === true) {\n\t\t\tif (!warned.storeName) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'\n\t\t\t\t); // eslint-disable-line no-console\n\t\t\t\twarned.storeName = true;\n\t\t\t}\n\n\t\t\toptions = { storeName: true };\n\t\t}\n\t\tconst storeName = options !== undefined ? options.storeName : false;\n\t\tconst contentOnly = options !== undefined ? options.contentOnly : false;\n\n\t\tif (storeName) {\n\t\t\tconst original = this.original.slice(start, end);\n\t\t\tObject.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true });\n\t\t}\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tif (first) {\n\t\t\tlet chunk = first;\n\t\t\twhile (chunk !== last) {\n\t\t\t\tif (chunk.next !== this.byStart[chunk.end]) {\n\t\t\t\t\tthrow new Error('Cannot overwrite across a split point');\n\t\t\t\t}\n\t\t\t\tchunk = chunk.next;\n\t\t\t\tchunk.edit('', false);\n\t\t\t}\n\n\t\t\tfirst.edit(content, storeName, contentOnly);\n\t\t} else {\n\t\t\t// must be inserting at the end\n\t\t\tconst newChunk = new Chunk(start, end, '').edit(content, storeName);\n\n\t\t\t// TODO last chunk in the array may not be the last chunk, if it's moved...\n\t\t\tlast.next = newChunk;\n\t\t\tnewChunk.previous = last;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('overwrite');\n\t\treturn this;\n\t}\n\n\tprepend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.intro = content + this.intro;\n\t\treturn this;\n\t}\n\n\tprependLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependLeft(content);\n\t\t} else {\n\t\t\tthis.intro = content + this.intro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tprependRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependRight(content);\n\t\t} else {\n\t\t\tthis.outro = content + this.outro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tremove(start, end) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('remove');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.intro = '';\n\t\t\tchunk.outro = '';\n\t\t\tchunk.edit('');\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('remove');\n\t\treturn this;\n\t}\n\n\tlastChar() {\n\t\tif (this.outro.length) return this.outro[this.outro.length - 1];\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];\n\t\t\tif (chunk.content.length) return chunk.content[chunk.content.length - 1];\n\t\t\tif (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];\n\t\t} while ((chunk = chunk.previous));\n\t\tif (this.intro.length) return this.intro[this.intro.length - 1];\n\t\treturn '';\n\t}\n\n\tlastLine() {\n\t\tlet lineIndex = this.outro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.outro.substr(lineIndex + 1);\n\t\tlet lineStr = this.outro;\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length > 0) {\n\t\t\t\tlineIndex = chunk.outro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.outro + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.content.length > 0) {\n\t\t\t\tlineIndex = chunk.content.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.content + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.intro.length > 0) {\n\t\t\t\tlineIndex = chunk.intro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.intro + lineStr;\n\t\t\t}\n\t\t} while ((chunk = chunk.previous));\n\t\tlineIndex = this.intro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;\n\t\treturn this.intro + lineStr;\n\t}\n\n\tslice(start = 0, end = this.original.length) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tlet result = '';\n\n\t\t// find start chunk\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk && (chunk.start > start || chunk.end <= start)) {\n\t\t\t// found end chunk before start\n\t\t\tif (chunk.start < end && chunk.end >= end) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tif (chunk && chunk.edited && chunk.start !== start)\n\t\t\tthrow new Error(`Cannot use replaced character ${start} as slice start anchor.`);\n\n\t\tconst startChunk = chunk;\n\t\twhile (chunk) {\n\t\t\tif (chunk.intro && (startChunk !== chunk || chunk.start === start)) {\n\t\t\t\tresult += chunk.intro;\n\t\t\t}\n\n\t\t\tconst containsEnd = chunk.start < end && chunk.end >= end;\n\t\t\tif (containsEnd && chunk.edited && chunk.end !== end)\n\t\t\t\tthrow new Error(`Cannot use replaced character ${end} as slice end anchor.`);\n\n\t\t\tconst sliceStart = startChunk === chunk ? start - chunk.start : 0;\n\t\t\tconst sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;\n\n\t\t\tresult += chunk.content.slice(sliceStart, sliceEnd);\n\n\t\t\tif (chunk.outro && (!containsEnd || chunk.end === end)) {\n\t\t\t\tresult += chunk.outro;\n\t\t\t}\n\n\t\t\tif (containsEnd) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t// TODO deprecate this? not really very useful\n\tsnip(start, end) {\n\t\tconst clone = this.clone();\n\t\tclone.remove(0, start);\n\t\tclone.remove(end, clone.original.length);\n\n\t\treturn clone;\n\t}\n\n\t_split(index) {\n\t\tif (this.byStart[index] || this.byEnd[index]) return;\n\n\t\tif (DEBUG) this.stats.time('_split');\n\n\t\tlet chunk = this.lastSearchedChunk;\n\t\tconst searchForward = index > chunk.end;\n\n\t\twhile (chunk) {\n\t\t\tif (chunk.contains(index)) return this._splitChunk(chunk, index);\n\n\t\t\tchunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];\n\t\t}\n\t}\n\n\t_splitChunk(chunk, index) {\n\t\tif (chunk.edited && chunk.content.length) {\n\t\t\t// zero-length edited chunks are a special case (overlapping replacements)\n\t\t\tconst loc = getLocator(this.original)(index);\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – \"${chunk.original}\")`\n\t\t\t);\n\t\t}\n\n\t\tconst newChunk = chunk.split(index);\n\n\t\tthis.byEnd[index] = chunk;\n\t\tthis.byStart[index] = newChunk;\n\t\tthis.byEnd[newChunk.end] = newChunk;\n\n\t\tif (chunk === this.lastChunk) this.lastChunk = newChunk;\n\n\t\tthis.lastSearchedChunk = chunk;\n\t\tif (DEBUG) this.stats.timeEnd('_split');\n\t\treturn true;\n\t}\n\n\ttoString() {\n\t\tlet str = this.intro;\n\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk) {\n\t\t\tstr += chunk.toString();\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn str + this.outro;\n\t}\n\n\tisEmpty() {\n\t\tlet chunk = this.firstChunk;\n\t\tdo {\n\t\t\tif (\n\t\t\t\t(chunk.intro.length && chunk.intro.trim()) ||\n\t\t\t\t(chunk.content.length && chunk.content.trim()) ||\n\t\t\t\t(chunk.outro.length && chunk.outro.trim())\n\t\t\t)\n\t\t\t\treturn false;\n\t\t} while ((chunk = chunk.next));\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\tlet chunk = this.firstChunk;\n\t\tlet length = 0;\n\t\tdo {\n\t\t\tlength += chunk.intro.length + chunk.content.length + chunk.outro.length;\n\t\t} while ((chunk = chunk.next));\n\t\treturn length;\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimEndAborted(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tlet chunk = this.lastChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimEnd(rx);\n\n\t\t\t// if chunk was trimmed, we have a new lastChunk\n\t\t\tif (chunk.end !== end) {\n\t\t\t\tif (this.lastChunk === chunk) {\n\t\t\t\t\tthis.lastChunk = chunk.next;\n\t\t\t\t}\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.previous;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimEnd(charType) {\n\t\tthis.trimEndAborted(charType);\n\t\treturn this;\n\t}\n\ttrimStartAborted(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tlet chunk = this.firstChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimStart(rx);\n\n\t\t\tif (chunk.end !== end) {\n\t\t\t\t// special case...\n\t\t\t\tif (chunk === this.lastChunk) this.lastChunk = chunk.next;\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.next;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimStart(charType) {\n\t\tthis.trimStartAborted(charType);\n\t\treturn this;\n\t}\n}\n","import MagicString from './MagicString.js';\nimport SourceMap from './SourceMap.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\n\nconst hasOwnProp = Object.prototype.hasOwnProperty;\n\nexport default class Bundle {\n\tconstructor(options = {}) {\n\t\tthis.intro = options.intro || '';\n\t\tthis.separator = options.separator !== undefined ? options.separator : '\\n';\n\t\tthis.sources = [];\n\t\tthis.uniqueSources = [];\n\t\tthis.uniqueSourceIndexByFilename = {};\n\t}\n\n\taddSource(source) {\n\t\tif (source instanceof MagicString) {\n\t\t\treturn this.addSource({\n\t\t\t\tcontent: source,\n\t\t\t\tfilename: source.filename,\n\t\t\t\tseparator: this.separator,\n\t\t\t});\n\t\t}\n\n\t\tif (!isObject(source) || !source.content) {\n\t\t\tthrow new Error(\n\t\t\t\t'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'\n\t\t\t);\n\t\t}\n\n\t\t['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {\n\t\t\tif (!hasOwnProp.call(source, option)) source[option] = source.content[option];\n\t\t});\n\n\t\tif (source.separator === undefined) {\n\t\t\t// TODO there's a bunch of this sort of thing, needs cleaning up\n\t\t\tsource.separator = this.separator;\n\t\t}\n\n\t\tif (source.filename) {\n\t\t\tif (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {\n\t\t\t\tthis.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;\n\t\t\t\tthis.uniqueSources.push({ filename: source.filename, content: source.content.original });\n\t\t\t} else {\n\t\t\t\tconst uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];\n\t\t\t\tif (source.content.original !== uniqueSource.content) {\n\t\t\t\t\tthrow new Error(`Illegal source: same filename (${source.filename}), different contents`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.sources.push(source);\n\t\treturn this;\n\t}\n\n\tappend(str, options) {\n\t\tthis.addSource({\n\t\t\tcontent: new MagicString(str),\n\t\t\tseparator: (options && options.separator) || '',\n\t\t});\n\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst bundle = new Bundle({\n\t\t\tintro: this.intro,\n\t\t\tseparator: this.separator,\n\t\t});\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tbundle.addSource({\n\t\t\t\tfilename: source.filename,\n\t\t\t\tcontent: source.content.clone(),\n\t\t\t\tseparator: source.separator,\n\t\t\t});\n\t\t});\n\n\t\treturn bundle;\n\t}\n\n\tgenerateDecodedMap(options = {}) {\n\t\tconst names = [];\n\t\tthis.sources.forEach((source) => {\n\t\t\tObject.keys(source.content.storedNames).forEach((name) => {\n\t\t\t\tif (!~names.indexOf(name)) names.push(name);\n\t\t\t});\n\t\t});\n\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tif (i > 0) {\n\t\t\t\tmappings.advance(this.separator);\n\t\t\t}\n\n\t\t\tconst sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;\n\t\t\tconst magicString = source.content;\n\t\t\tconst locate = getLocator(magicString.original);\n\n\t\t\tif (magicString.intro) {\n\t\t\t\tmappings.advance(magicString.intro);\n\t\t\t}\n\n\t\t\tmagicString.firstChunk.eachNext((chunk) => {\n\t\t\t\tconst loc = locate(chunk.start);\n\n\t\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\t\tif (source.filename) {\n\t\t\t\t\tif (chunk.edited) {\n\t\t\t\t\t\tmappings.addEdit(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk.content,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmappings.addUneditedChunk(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk,\n\t\t\t\t\t\t\tmagicString.original,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tmagicString.sourcemapLocations\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmappings.advance(chunk.content);\n\t\t\t\t}\n\n\t\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t\t});\n\n\t\t\tif (magicString.outro) {\n\t\t\t\tmappings.advance(magicString.outro);\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : null,\n\t\t\tsources: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.file ? getRelativePath(options.file, source.filename) : source.filename;\n\t\t\t}),\n\t\t\tsourcesContent: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.includeContent ? source.content : null;\n\t\t\t}),\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\tconst indentStringCounts = {};\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tconst indentStr = source.content.indentStr;\n\n\t\t\tif (indentStr === null) return;\n\n\t\t\tif (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;\n\t\t\tindentStringCounts[indentStr] += 1;\n\t\t});\n\n\t\treturn (\n\t\t\tObject.keys(indentStringCounts).sort((a, b) => {\n\t\t\t\treturn indentStringCounts[a] - indentStringCounts[b];\n\t\t\t})[0] || '\\t'\n\t\t);\n\t}\n\n\tindent(indentStr) {\n\t\tif (!arguments.length) {\n\t\t\tindentStr = this.getIndentString();\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\tlet trailingNewline = !this.intro || this.intro.slice(-1) === '\\n';\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\tconst indentStart = trailingNewline || (i > 0 && /\\r?\\n$/.test(separator));\n\n\t\t\tsource.content.indent(indentStr, {\n\t\t\t\texclude: source.indentExclusionRanges,\n\t\t\t\tindentStart, //: trailingNewline || /\\r?\\n$/.test( separator ) //true///\\r?\\n/.test( separator )\n\t\t\t});\n\n\t\t\ttrailingNewline = source.content.lastChar() === '\\n';\n\t\t});\n\n\t\tif (this.intro) {\n\t\t\tthis.intro =\n\t\t\t\tindentStr +\n\t\t\t\tthis.intro.replace(/^[^\\n]/gm, (match, index) => {\n\t\t\t\t\treturn index > 0 ? indentStr + match : match;\n\t\t\t\t});\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tprepend(str) {\n\t\tthis.intro = str + this.intro;\n\t\treturn this;\n\t}\n\n\ttoString() {\n\t\tconst body = this.sources\n\t\t\t.map((source, i) => {\n\t\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\t\tconst str = (i > 0 ? separator : '') + source.content.toString();\n\n\t\t\t\treturn str;\n\t\t\t})\n\t\t\t.join('');\n\n\t\treturn this.intro + body;\n\t}\n\n\tisEmpty() {\n\t\tif (this.intro.length && this.intro.trim()) return false;\n\t\tif (this.sources.some((source) => !source.content.isEmpty())) return false;\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\treturn this.sources.reduce(\n\t\t\t(length, source) => length + source.content.length(),\n\t\t\tthis.intro.length\n\t\t);\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimStart(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\t\tthis.intro = this.intro.replace(rx, '');\n\n\t\tif (!this.intro) {\n\t\t\tlet source;\n\t\t\tlet i = 0;\n\n\t\t\tdo {\n\t\t\t\tsource = this.sources[i++];\n\t\t\t\tif (!source) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} while (!source.content.trimStartAborted(charType));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\ttrimEnd(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tlet source;\n\t\tlet i = this.sources.length - 1;\n\n\t\tdo {\n\t\t\tsource = this.sources[i--];\n\t\t\tif (!source) {\n\t\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (!source.content.trimEndAborted(charType));\n\n\t\treturn this;\n\t}\n}\n"],"names":["const","let","this"],"mappings":";;AAAe,IAAM,MAAM,GAC1B,eAAW,CAAC,GAAG,EAAE;AAClB,CAAE,IAAI,CAAC,IAAI,GAAG,GAAG,YAAY,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC;AAC3D,EAAC;AACF;iBACC,oBAAI,CAAC,EAAE;AACR,CAAE,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC;AACpC,EAAC;AACF;iBACC,oBAAI,CAAC,EAAE;AACR,CAAE,OAAO,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC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CAAC;AAClC;AACA,CAAE,GAAG;AACL,EAAG,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;AAC9B,EAAG,IAAI,CAAC,MAAM,EAAE;AAChB,GAAI,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC5C,GAAI,MAAM;AACV,GAAI;AACJ,EAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE;AACrD;AACA,CAAE,OAAO,IAAI,CAAC;AACb;;;;"} \ No newline at end of file diff --git a/node_modules/magic-string/dist/magic-string.umd.js b/node_modules/magic-string/dist/magic-string.umd.js new file mode 100644 index 0000000..573a4e1 --- /dev/null +++ b/node_modules/magic-string/dist/magic-string.umd.js @@ -0,0 +1,1371 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.MagicString = factory()); +})(this, (function () { 'use strict'; + + var BitSet = function BitSet(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; + }; + + BitSet.prototype.add = function add (n) { + this.bits[n >> 5] |= 1 << (n & 31); + }; + + BitSet.prototype.has = function has (n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); + }; + + var Chunk = function Chunk(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + // we make these non-enumerable, for sanity while debugging + Object.defineProperties(this, { + previous: { writable: true, value: null }, + next: { writable: true, value: null }, + }); + }; + + Chunk.prototype.appendLeft = function appendLeft (content) { + this.outro += content; + }; + + Chunk.prototype.appendRight = function appendRight (content) { + this.intro = this.intro + content; + }; + + Chunk.prototype.clone = function clone () { + var chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; + }; + + Chunk.prototype.contains = function contains (index) { + return this.start < index && index < this.end; + }; + + Chunk.prototype.eachNext = function eachNext (fn) { + var chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + }; + + Chunk.prototype.eachPrevious = function eachPrevious (fn) { + var chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + }; + + Chunk.prototype.edit = function edit (content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; + }; + + Chunk.prototype.prependLeft = function prependLeft (content) { + this.outro = content + this.outro; + }; + + Chunk.prototype.prependRight = function prependRight (content) { + this.intro = content + this.intro; + }; + + Chunk.prototype.split = function split (index) { + var sliceIndex = index - this.start; + + var originalBefore = this.original.slice(0, sliceIndex); + var originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + var newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) { newChunk.next.previous = newChunk; } + newChunk.previous = this; + this.next = newChunk; + + return newChunk; + }; + + Chunk.prototype.toString = function toString () { + return this.intro + this.content + this.outro; + }; + + Chunk.prototype.trimEnd = function trimEnd (rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + + var trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + } + }; + + Chunk.prototype.trimStart = function trimStart (rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + + var trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.end - trimmed.length); + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + } + }; + + var charToInteger = {}; + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + for (var i = 0; i < chars.length; i++) { + charToInteger[chars.charCodeAt(i)] = i; + } + function encode(decoded) { + var sourceFileIndex = 0; // second field + var sourceCodeLine = 0; // third field + var sourceCodeColumn = 0; // fourth field + var nameIndex = 0; // fifth field + var mappings = ''; + for (var i = 0; i < decoded.length; i++) { + var line = decoded[i]; + if (i > 0) + mappings += ';'; + if (line.length === 0) + continue; + var generatedCodeColumn = 0; // first field + var lineMappings = []; + for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { + var segment = line_1[_i]; + var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn); + generatedCodeColumn = segment[0]; + if (segment.length > 1) { + segmentMappings += + encodeInteger(segment[1] - sourceFileIndex) + + encodeInteger(segment[2] - sourceCodeLine) + + encodeInteger(segment[3] - sourceCodeColumn); + sourceFileIndex = segment[1]; + sourceCodeLine = segment[2]; + sourceCodeColumn = segment[3]; + } + if (segment.length === 5) { + segmentMappings += encodeInteger(segment[4] - nameIndex); + nameIndex = segment[4]; + } + lineMappings.push(segmentMappings); + } + mappings += lineMappings.join(','); + } + return mappings; + } + function encodeInteger(num) { + var result = ''; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + var clamped = num & 31; + num >>>= 5; + if (num > 0) { + clamped |= 32; + } + result += chars[clamped]; + } while (num > 0); + return result; + } + + var btoa = function () { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); + }; + if (typeof window !== 'undefined' && typeof window.btoa === 'function') { + btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); }; + } else if (typeof Buffer === 'function') { + btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); }; + } + + var SourceMap = function SourceMap(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode(properties.mappings); + }; + + SourceMap.prototype.toString = function toString () { + return JSON.stringify(this); + }; + + SourceMap.prototype.toUrl = function toUrl () { + return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); + }; + + function guessIndent(code) { + var lines = code.split('\n'); + + var tabbed = lines.filter(function (line) { return /^\t+/.test(line); }); + var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); }); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + var min = spaced.reduce(function (previous, current) { + var numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); + } + + function getRelativePath(from, to) { + var fromParts = from.split(/[/\\]/); + var toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + var i = fromParts.length; + while (i--) { fromParts[i] = '..'; } + } + + return fromParts.concat(toParts).join('/'); + } + + var toString = Object.prototype.toString; + + function isObject(thing) { + return toString.call(thing) === '[object Object]'; + } + + function getLocator(source) { + var originalLines = source.split('\n'); + var lineOffsets = []; + + for (var i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + var i = 0; + var j = lineOffsets.length; + while (i < j) { + var m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + var line = i - 1; + var column = index - lineOffsets[line]; + return { line: line, column: column }; + }; + } + + var Mappings = function Mappings(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + }; + + Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) { + if (content.length) { + var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + } else if (this.pending) { + this.rawSegments.push(this.pending); + } + + this.advance(content); + this.pending = null; + }; + + Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) { + var originalCharIndex = chunk.start; + var first = true; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; + }; + + Mappings.prototype.advance = function advance (str) { + if (!str) { return; } + + var lines = str.split('\n'); + + if (lines.length > 1) { + for (var i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; + }; + + var n = '\n'; + + var warned = { + insertLeft: false, + insertRight: false, + storeName: false, + }; + + var MagicString = function MagicString(string, options) { + if ( options === void 0 ) options = {}; + + var chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: guessIndent(string) }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; + }; + + MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) { + this.sourcemapLocations.add(char); + }; + + MagicString.prototype.append = function append (content) { + if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } + + this.outro += content; + return this; + }; + + MagicString.prototype.appendLeft = function appendLeft (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + }; + + MagicString.prototype.appendRight = function appendRight (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + }; + + MagicString.prototype.clone = function clone () { + var cloned = new MagicString(this.original, { filename: this.filename }); + + var originalChunk = this.firstChunk; + var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + var nextOriginalChunk = originalChunk.next; + var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; + }; + + MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) { + var this$1$1 = this; + + options = options || {}; + + var sourceIndex = 0; + var names = Object.keys(this.storedNames); + var mappings = new Mappings(options.hires); + + var locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext(function (chunk) { + var loc = locate(chunk.start); + + if (chunk.intro.length) { mappings.advance(chunk.intro); } + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1 + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations); + } + + if (chunk.outro.length) { mappings.advance(chunk.outro); } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : null, + sources: [options.source ? getRelativePath(options.file || '', options.source) : null], + sourcesContent: options.includeContent ? [this.original] : [null], + names: names, + mappings: mappings.raw, + }; + }; + + MagicString.prototype.generateMap = function generateMap (options) { + return new SourceMap(this.generateDecodedMap(options)); + }; + + MagicString.prototype.getIndentString = function getIndentString () { + return this.indentStr === null ? '\t' : this.indentStr; + }; + + MagicString.prototype.indent = function indent (indentStr, options) { + var pattern = /^[^\r\n]/gm; + + if (isObject(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t'; + + if (indentStr === '') { return this; } // noop + + options = options || {}; + + // Process exclusion ranges + var isExcluded = {}; + + if (options.exclude) { + var exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach(function (exclusion) { + for (var i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + var shouldIndentNextCharacter = options.indentStart !== false; + var replacer = function (match) { + if (shouldIndentNextCharacter) { return ("" + indentStr + match); } + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + var charIndex = 0; + var chunk = this.firstChunk; + + while (chunk) { + var end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + var char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; + }; + + MagicString.prototype.insert = function insert () { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' + ); + }; + + MagicString.prototype.insertLeft = function insertLeft (index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); + }; + + MagicString.prototype.insertRight = function insertRight (index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); + }; + + MagicString.prototype.move = function move (start, end, index) { + if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); } + + this._split(start); + this._split(end); + this._split(index); + + var first = this.byStart[start]; + var last = this.byEnd[end]; + + var oldLeft = first.previous; + var oldRight = last.next; + + var newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) { return this; } + var newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) { oldLeft.next = oldRight; } + if (oldRight) { oldRight.previous = oldLeft; } + + if (newLeft) { newLeft.next = first; } + if (newRight) { newRight.previous = last; } + + if (!first.previous) { this.firstChunk = last.next; } + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) { this.firstChunk = first; } + if (!newRight) { this.lastChunk = last; } + return this; + }; + + MagicString.prototype.overwrite = function overwrite (start, end, content, options) { + if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); } + + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + if (end > this.original.length) { throw new Error('end is out of bounds'); } + if (start === end) + { throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' + ); } + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + var storeName = options !== undefined ? options.storeName : false; + var contentOnly = options !== undefined ? options.contentOnly : false; + + if (storeName) { + var original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true }); + } + + var first = this.byStart[start]; + var last = this.byEnd[end]; + + if (first) { + var chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, contentOnly); + } else { + // must be inserting at the end + var newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; + }; + + MagicString.prototype.prepend = function prepend (content) { + if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } + + this.intro = content + this.intro; + return this; + }; + + MagicString.prototype.prependLeft = function prependLeft (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + }; + + MagicString.prototype.prependRight = function prependRight (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + }; + + MagicString.prototype.remove = function remove (start, end) { + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + if (start === end) { return this; } + + if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); } + if (start > end) { throw new Error('end must be greater than start'); } + + this._split(start); + this._split(end); + + var chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + }; + + MagicString.prototype.lastChar = function lastChar () { + if (this.outro.length) { return this.outro[this.outro.length - 1]; } + var chunk = this.lastChunk; + do { + if (chunk.outro.length) { return chunk.outro[chunk.outro.length - 1]; } + if (chunk.content.length) { return chunk.content[chunk.content.length - 1]; } + if (chunk.intro.length) { return chunk.intro[chunk.intro.length - 1]; } + } while ((chunk = chunk.previous)); + if (this.intro.length) { return this.intro[this.intro.length - 1]; } + return ''; + }; + + MagicString.prototype.lastLine = function lastLine () { + var lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) { return this.outro.substr(lineIndex + 1); } + var lineStr = this.outro; + var chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) { return chunk.outro.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) { return chunk.content.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) { return chunk.intro.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) { return this.intro.substr(lineIndex + 1) + lineStr; } + return this.intro + lineStr; + }; + + MagicString.prototype.slice = function slice (start, end) { + if ( start === void 0 ) start = 0; + if ( end === void 0 ) end = this.original.length; + + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + var result = ''; + + // find start chunk + var chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); } + + var startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + var containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); } + + var sliceStart = startChunk === chunk ? start - chunk.start : 0; + var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; + }; + + // TODO deprecate this? not really very useful + MagicString.prototype.snip = function snip (start, end) { + var clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; + }; + + MagicString.prototype._split = function _split (index) { + if (this.byStart[index] || this.byEnd[index]) { return; } + + var chunk = this.lastSearchedChunk; + var searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) { return this._splitChunk(chunk, index); } + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + }; + + MagicString.prototype._splitChunk = function _splitChunk (chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + var loc = getLocator(this.original)(index); + throw new Error( + ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") + ); + } + + var newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) { this.lastChunk = newChunk; } + + this.lastSearchedChunk = chunk; + return true; + }; + + MagicString.prototype.toString = function toString () { + var str = this.intro; + + var chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; + }; + + MagicString.prototype.isEmpty = function isEmpty () { + var chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + { return false; } + } while ((chunk = chunk.next)); + return true; + }; + + MagicString.prototype.length = function length () { + var chunk = this.firstChunk; + var length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; + }; + + MagicString.prototype.trimLines = function trimLines () { + return this.trim('[\\r\\n]'); + }; + + MagicString.prototype.trim = function trim (charType) { + return this.trimStart(charType).trimEnd(charType); + }; + + MagicString.prototype.trimEndAborted = function trimEndAborted (charType) { + var rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + + var chunk = this.lastChunk; + + do { + var end = chunk.end; + var aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) { return true; } + chunk = chunk.previous; + } while (chunk); + + return false; + }; + + MagicString.prototype.trimEnd = function trimEnd (charType) { + this.trimEndAborted(charType); + return this; + }; + MagicString.prototype.trimStartAborted = function trimStartAborted (charType) { + var rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + + var chunk = this.firstChunk; + + do { + var end = chunk.end; + var aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) { this.lastChunk = chunk.next; } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) { return true; } + chunk = chunk.next; + } while (chunk); + + return false; + }; + + MagicString.prototype.trimStart = function trimStart (charType) { + this.trimStartAborted(charType); + return this; + }; + + var hasOwnProp = Object.prototype.hasOwnProperty; + + var Bundle = function Bundle(options) { + if ( options === void 0 ) options = {}; + + this.intro = options.intro || ''; + this.separator = options.separator !== undefined ? options.separator : '\n'; + this.sources = []; + this.uniqueSources = []; + this.uniqueSourceIndexByFilename = {}; + }; + + Bundle.prototype.addSource = function addSource (source) { + if (source instanceof MagicString) { + return this.addSource({ + content: source, + filename: source.filename, + separator: this.separator, + }); + } + + if (!isObject(source) || !source.content) { + throw new Error( + 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`' + ); + } + + ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) { + if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; } + }); + + if (source.separator === undefined) { + // TODO there's a bunch of this sort of thing, needs cleaning up + source.separator = this.separator; + } + + if (source.filename) { + if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) { + this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length; + this.uniqueSources.push({ filename: source.filename, content: source.content.original }); + } else { + var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]]; + if (source.content.original !== uniqueSource.content) { + throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents")); + } + } + } + + this.sources.push(source); + return this; + }; + + Bundle.prototype.append = function append (str, options) { + this.addSource({ + content: new MagicString(str), + separator: (options && options.separator) || '', + }); + + return this; + }; + + Bundle.prototype.clone = function clone () { + var bundle = new Bundle({ + intro: this.intro, + separator: this.separator, + }); + + this.sources.forEach(function (source) { + bundle.addSource({ + filename: source.filename, + content: source.content.clone(), + separator: source.separator, + }); + }); + + return bundle; + }; + + Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) { + var this$1$1 = this; + if ( options === void 0 ) options = {}; + + var names = []; + this.sources.forEach(function (source) { + Object.keys(source.content.storedNames).forEach(function (name) { + if (!~names.indexOf(name)) { names.push(name); } + }); + }); + + var mappings = new Mappings(options.hires); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.sources.forEach(function (source, i) { + if (i > 0) { + mappings.advance(this$1$1.separator); + } + + var sourceIndex = source.filename ? this$1$1.uniqueSourceIndexByFilename[source.filename] : -1; + var magicString = source.content; + var locate = getLocator(magicString.original); + + if (magicString.intro) { + mappings.advance(magicString.intro); + } + + magicString.firstChunk.eachNext(function (chunk) { + var loc = locate(chunk.start); + + if (chunk.intro.length) { mappings.advance(chunk.intro); } + + if (source.filename) { + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1 + ); + } else { + mappings.addUneditedChunk( + sourceIndex, + chunk, + magicString.original, + loc, + magicString.sourcemapLocations + ); + } + } else { + mappings.advance(chunk.content); + } + + if (chunk.outro.length) { mappings.advance(chunk.outro); } + }); + + if (magicString.outro) { + mappings.advance(magicString.outro); + } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : null, + sources: this.uniqueSources.map(function (source) { + return options.file ? getRelativePath(options.file, source.filename) : source.filename; + }), + sourcesContent: this.uniqueSources.map(function (source) { + return options.includeContent ? source.content : null; + }), + names: names, + mappings: mappings.raw, + }; + }; + + Bundle.prototype.generateMap = function generateMap (options) { + return new SourceMap(this.generateDecodedMap(options)); + }; + + Bundle.prototype.getIndentString = function getIndentString () { + var indentStringCounts = {}; + + this.sources.forEach(function (source) { + var indentStr = source.content.indentStr; + + if (indentStr === null) { return; } + + if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; } + indentStringCounts[indentStr] += 1; + }); + + return ( + Object.keys(indentStringCounts).sort(function (a, b) { + return indentStringCounts[a] - indentStringCounts[b]; + })[0] || '\t' + ); + }; + + Bundle.prototype.indent = function indent (indentStr) { + var this$1$1 = this; + + if (!arguments.length) { + indentStr = this.getIndentString(); + } + + if (indentStr === '') { return this; } // noop + + var trailingNewline = !this.intro || this.intro.slice(-1) === '\n'; + + this.sources.forEach(function (source, i) { + var separator = source.separator !== undefined ? source.separator : this$1$1.separator; + var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator)); + + source.content.indent(indentStr, { + exclude: source.indentExclusionRanges, + indentStart: indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator ) + }); + + trailingNewline = source.content.lastChar() === '\n'; + }); + + if (this.intro) { + this.intro = + indentStr + + this.intro.replace(/^[^\n]/gm, function (match, index) { + return index > 0 ? indentStr + match : match; + }); + } + + return this; + }; + + Bundle.prototype.prepend = function prepend (str) { + this.intro = str + this.intro; + return this; + }; + + Bundle.prototype.toString = function toString () { + var this$1$1 = this; + + var body = this.sources + .map(function (source, i) { + var separator = source.separator !== undefined ? source.separator : this$1$1.separator; + var str = (i > 0 ? separator : '') + source.content.toString(); + + return str; + }) + .join(''); + + return this.intro + body; + }; + + Bundle.prototype.isEmpty = function isEmpty () { + if (this.intro.length && this.intro.trim()) { return false; } + if (this.sources.some(function (source) { return !source.content.isEmpty(); })) { return false; } + return true; + }; + + Bundle.prototype.length = function length () { + return this.sources.reduce( + function (length, source) { return length + source.content.length(); }, + this.intro.length + ); + }; + + Bundle.prototype.trimLines = function trimLines () { + return this.trim('[\\r\\n]'); + }; + + Bundle.prototype.trim = function trim (charType) { + return this.trimStart(charType).trimEnd(charType); + }; + + Bundle.prototype.trimStart = function trimStart (charType) { + var rx = new RegExp('^' + (charType || '\\s') + '+'); + this.intro = this.intro.replace(rx, ''); + + if (!this.intro) { + var source; + var i = 0; + + do { + source = this.sources[i++]; + if (!source) { + break; + } + } while (!source.content.trimStartAborted(charType)); + } + + return this; + }; + + Bundle.prototype.trimEnd = function trimEnd (charType) { + var rx = new RegExp((charType || '\\s') + '+$'); + + var source; + var i = this.sources.length - 1; + + do { + source = this.sources[i--]; + if (!source) { + this.intro = this.intro.replace(rx, ''); + break; + } + } while (!source.content.trimEndAborted(charType)); + + return this; + }; + + MagicString.Bundle = Bundle; + MagicString.SourceMap = SourceMap; + MagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121 + + return MagicString; + +})); +//# sourceMappingURL=magic-string.umd.js.map diff --git a/node_modules/magic-string/dist/magic-string.umd.js.map b/node_modules/magic-string/dist/magic-string.umd.js.map new file mode 100644 index 0000000..70607d0 --- /dev/null +++ b/node_modules/magic-string/dist/magic-string.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"magic-string.umd.js","sources":["../src/BitSet.js","../src/Chunk.js","../node_modules/sourcemap-codec/dist/sourcemap-codec.es.js","../src/SourceMap.js","../src/utils/guessIndent.js","../src/utils/getRelativePath.js","../src/utils/isObject.js","../src/utils/getLocator.js","../src/utils/Mappings.js","../src/MagicString.js","../src/Bundle.js","../src/index-legacy.js"],"sourcesContent":["export default class BitSet {\n\tconstructor(arg) {\n\t\tthis.bits = arg instanceof BitSet ? arg.bits.slice() : [];\n\t}\n\n\tadd(n) {\n\t\tthis.bits[n >> 5] |= 1 << (n & 31);\n\t}\n\n\thas(n) {\n\t\treturn !!(this.bits[n >> 5] & (1 << (n & 31)));\n\t}\n}\n","export default class Chunk {\n\tconstructor(start, end, content) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tthis.original = content;\n\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\n\t\tthis.content = content;\n\t\tthis.storeName = false;\n\t\tthis.edited = false;\n\n\t\t// we make these non-enumerable, for sanity while debugging\n\t\tObject.defineProperties(this, {\n\t\t\tprevious: { writable: true, value: null },\n\t\t\tnext: { writable: true, value: null },\n\t\t});\n\t}\n\n\tappendLeft(content) {\n\t\tthis.outro += content;\n\t}\n\n\tappendRight(content) {\n\t\tthis.intro = this.intro + content;\n\t}\n\n\tclone() {\n\t\tconst chunk = new Chunk(this.start, this.end, this.original);\n\n\t\tchunk.intro = this.intro;\n\t\tchunk.outro = this.outro;\n\t\tchunk.content = this.content;\n\t\tchunk.storeName = this.storeName;\n\t\tchunk.edited = this.edited;\n\n\t\treturn chunk;\n\t}\n\n\tcontains(index) {\n\t\treturn this.start < index && index < this.end;\n\t}\n\n\teachNext(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.next;\n\t\t}\n\t}\n\n\teachPrevious(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.previous;\n\t\t}\n\t}\n\n\tedit(content, storeName, contentOnly) {\n\t\tthis.content = content;\n\t\tif (!contentOnly) {\n\t\t\tthis.intro = '';\n\t\t\tthis.outro = '';\n\t\t}\n\t\tthis.storeName = storeName;\n\n\t\tthis.edited = true;\n\n\t\treturn this;\n\t}\n\n\tprependLeft(content) {\n\t\tthis.outro = content + this.outro;\n\t}\n\n\tprependRight(content) {\n\t\tthis.intro = content + this.intro;\n\t}\n\n\tsplit(index) {\n\t\tconst sliceIndex = index - this.start;\n\n\t\tconst originalBefore = this.original.slice(0, sliceIndex);\n\t\tconst originalAfter = this.original.slice(sliceIndex);\n\n\t\tthis.original = originalBefore;\n\n\t\tconst newChunk = new Chunk(index, this.end, originalAfter);\n\t\tnewChunk.outro = this.outro;\n\t\tthis.outro = '';\n\n\t\tthis.end = index;\n\n\t\tif (this.edited) {\n\t\t\t// TODO is this block necessary?...\n\t\t\tnewChunk.edit('', false);\n\t\t\tthis.content = '';\n\t\t} else {\n\t\t\tthis.content = originalBefore;\n\t\t}\n\n\t\tnewChunk.next = this.next;\n\t\tif (newChunk.next) newChunk.next.previous = newChunk;\n\t\tnewChunk.previous = this;\n\t\tthis.next = newChunk;\n\n\t\treturn newChunk;\n\t}\n\n\ttoString() {\n\t\treturn this.intro + this.content + this.outro;\n\t}\n\n\ttrimEnd(rx) {\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.start + trimmed.length).edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\tif (this.intro.length) return true;\n\t\t}\n\t}\n\n\ttrimStart(rx) {\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.end - trimmed.length);\n\t\t\t\tthis.edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.outro = this.outro.replace(rx, '');\n\t\t\tif (this.outro.length) return true;\n\t\t}\n\t}\n}\n","var charToInteger = {};\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nfor (var i = 0; i < chars.length; i++) {\n charToInteger[chars.charCodeAt(i)] = i;\n}\nfunction decode(mappings) {\n var decoded = [];\n var line = [];\n var segment = [\n 0,\n 0,\n 0,\n 0,\n 0,\n ];\n var j = 0;\n for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {\n var c = mappings.charCodeAt(i);\n if (c === 44) { // \",\"\n segmentify(line, segment, j);\n j = 0;\n }\n else if (c === 59) { // \";\"\n segmentify(line, segment, j);\n j = 0;\n decoded.push(line);\n line = [];\n segment[0] = 0;\n }\n else {\n var integer = charToInteger[c];\n if (integer === undefined) {\n throw new Error('Invalid character (' + String.fromCharCode(c) + ')');\n }\n var hasContinuationBit = integer & 32;\n integer &= 31;\n value += integer << shift;\n if (hasContinuationBit) {\n shift += 5;\n }\n else {\n var shouldNegate = value & 1;\n value >>>= 1;\n if (shouldNegate) {\n value = value === 0 ? -0x80000000 : -value;\n }\n segment[j] += value;\n j++;\n value = shift = 0; // reset\n }\n }\n }\n segmentify(line, segment, j);\n decoded.push(line);\n return decoded;\n}\nfunction segmentify(line, segment, j) {\n // This looks ugly, but we're creating specialized arrays with a specific\n // length. This is much faster than creating a new array (which v8 expands to\n // a capacity of 17 after pushing the first item), or slicing out a subarray\n // (which is slow). Length 4 is assumed to be the most frequent, followed by\n // length 5 (since not everything will have an associated name), followed by\n // length 1 (it's probably rare for a source substring to not have an\n // associated segment data).\n if (j === 4)\n line.push([segment[0], segment[1], segment[2], segment[3]]);\n else if (j === 5)\n line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);\n else if (j === 1)\n line.push([segment[0]]);\n}\nfunction encode(decoded) {\n var sourceFileIndex = 0; // second field\n var sourceCodeLine = 0; // third field\n var sourceCodeColumn = 0; // fourth field\n var nameIndex = 0; // fifth field\n var mappings = '';\n for (var i = 0; i < decoded.length; i++) {\n var line = decoded[i];\n if (i > 0)\n mappings += ';';\n if (line.length === 0)\n continue;\n var generatedCodeColumn = 0; // first field\n var lineMappings = [];\n for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {\n var segment = line_1[_i];\n var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);\n generatedCodeColumn = segment[0];\n if (segment.length > 1) {\n segmentMappings +=\n encodeInteger(segment[1] - sourceFileIndex) +\n encodeInteger(segment[2] - sourceCodeLine) +\n encodeInteger(segment[3] - sourceCodeColumn);\n sourceFileIndex = segment[1];\n sourceCodeLine = segment[2];\n sourceCodeColumn = segment[3];\n }\n if (segment.length === 5) {\n segmentMappings += encodeInteger(segment[4] - nameIndex);\n nameIndex = segment[4];\n }\n lineMappings.push(segmentMappings);\n }\n mappings += lineMappings.join(',');\n }\n return mappings;\n}\nfunction encodeInteger(num) {\n var result = '';\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n var clamped = num & 31;\n num >>>= 5;\n if (num > 0) {\n clamped |= 32;\n }\n result += chars[clamped];\n } while (num > 0);\n return result;\n}\n\nexport { decode, encode };\n//# sourceMappingURL=sourcemap-codec.es.js.map\n","import { encode } from 'sourcemap-codec';\n\nlet btoa = () => {\n\tthrow new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');\n};\nif (typeof window !== 'undefined' && typeof window.btoa === 'function') {\n\tbtoa = (str) => window.btoa(unescape(encodeURIComponent(str)));\n} else if (typeof Buffer === 'function') {\n\tbtoa = (str) => Buffer.from(str, 'utf-8').toString('base64');\n}\n\nexport default class SourceMap {\n\tconstructor(properties) {\n\t\tthis.version = 3;\n\t\tthis.file = properties.file;\n\t\tthis.sources = properties.sources;\n\t\tthis.sourcesContent = properties.sourcesContent;\n\t\tthis.names = properties.names;\n\t\tthis.mappings = encode(properties.mappings);\n\t}\n\n\ttoString() {\n\t\treturn JSON.stringify(this);\n\t}\n\n\ttoUrl() {\n\t\treturn 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());\n\t}\n}\n","export default function guessIndent(code) {\n\tconst lines = code.split('\\n');\n\n\tconst tabbed = lines.filter((line) => /^\\t+/.test(line));\n\tconst spaced = lines.filter((line) => /^ {2,}/.test(line));\n\n\tif (tabbed.length === 0 && spaced.length === 0) {\n\t\treturn null;\n\t}\n\n\t// More lines tabbed than spaced? Assume tabs, and\n\t// default to tabs in the case of a tie (or nothing\n\t// to go on)\n\tif (tabbed.length >= spaced.length) {\n\t\treturn '\\t';\n\t}\n\n\t// Otherwise, we need to guess the multiple\n\tconst min = spaced.reduce((previous, current) => {\n\t\tconst numSpaces = /^ +/.exec(current)[0].length;\n\t\treturn Math.min(numSpaces, previous);\n\t}, Infinity);\n\n\treturn new Array(min + 1).join(' ');\n}\n","export default function getRelativePath(from, to) {\n\tconst fromParts = from.split(/[/\\\\]/);\n\tconst toParts = to.split(/[/\\\\]/);\n\n\tfromParts.pop(); // get dirname\n\n\twhile (fromParts[0] === toParts[0]) {\n\t\tfromParts.shift();\n\t\ttoParts.shift();\n\t}\n\n\tif (fromParts.length) {\n\t\tlet i = fromParts.length;\n\t\twhile (i--) fromParts[i] = '..';\n\t}\n\n\treturn fromParts.concat(toParts).join('/');\n}\n","const toString = Object.prototype.toString;\n\nexport default function isObject(thing) {\n\treturn toString.call(thing) === '[object Object]';\n}\n","export default function getLocator(source) {\n\tconst originalLines = source.split('\\n');\n\tconst lineOffsets = [];\n\n\tfor (let i = 0, pos = 0; i < originalLines.length; i++) {\n\t\tlineOffsets.push(pos);\n\t\tpos += originalLines[i].length + 1;\n\t}\n\n\treturn function locate(index) {\n\t\tlet i = 0;\n\t\tlet j = lineOffsets.length;\n\t\twhile (i < j) {\n\t\t\tconst m = (i + j) >> 1;\n\t\t\tif (index < lineOffsets[m]) {\n\t\t\t\tj = m;\n\t\t\t} else {\n\t\t\t\ti = m + 1;\n\t\t\t}\n\t\t}\n\t\tconst line = i - 1;\n\t\tconst column = index - lineOffsets[line];\n\t\treturn { line, column };\n\t};\n}\n","export default class Mappings {\n\tconstructor(hires) {\n\t\tthis.hires = hires;\n\t\tthis.generatedCodeLine = 0;\n\t\tthis.generatedCodeColumn = 0;\n\t\tthis.raw = [];\n\t\tthis.rawSegments = this.raw[this.generatedCodeLine] = [];\n\t\tthis.pending = null;\n\t}\n\n\taddEdit(sourceIndex, content, loc, nameIndex) {\n\t\tif (content.length) {\n\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\tif (nameIndex >= 0) {\n\t\t\t\tsegment.push(nameIndex);\n\t\t\t}\n\t\t\tthis.rawSegments.push(segment);\n\t\t} else if (this.pending) {\n\t\t\tthis.rawSegments.push(this.pending);\n\t\t}\n\n\t\tthis.advance(content);\n\t\tthis.pending = null;\n\t}\n\n\taddUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {\n\t\tlet originalCharIndex = chunk.start;\n\t\tlet first = true;\n\n\t\twhile (originalCharIndex < chunk.end) {\n\t\t\tif (this.hires || first || sourcemapLocations.has(originalCharIndex)) {\n\t\t\t\tthis.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);\n\t\t\t}\n\n\t\t\tif (original[originalCharIndex] === '\\n') {\n\t\t\t\tloc.line += 1;\n\t\t\t\tloc.column = 0;\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\t\t\t\tfirst = true;\n\t\t\t} else {\n\t\t\t\tloc.column += 1;\n\t\t\t\tthis.generatedCodeColumn += 1;\n\t\t\t\tfirst = false;\n\t\t\t}\n\n\t\t\toriginalCharIndex += 1;\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\tadvance(str) {\n\t\tif (!str) return;\n\n\t\tconst lines = str.split('\\n');\n\n\t\tif (lines.length > 1) {\n\t\t\tfor (let i = 0; i < lines.length - 1; i++) {\n\t\t\t\tthis.generatedCodeLine++;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t}\n\t\t\tthis.generatedCodeColumn = 0;\n\t\t}\n\n\t\tthis.generatedCodeColumn += lines[lines.length - 1].length;\n\t}\n}\n","import BitSet from './BitSet.js';\nimport Chunk from './Chunk.js';\nimport SourceMap from './SourceMap.js';\nimport guessIndent from './utils/guessIndent.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\nimport Stats from './utils/Stats.js';\n\nconst n = '\\n';\n\nconst warned = {\n\tinsertLeft: false,\n\tinsertRight: false,\n\tstoreName: false,\n};\n\nexport default class MagicString {\n\tconstructor(string, options = {}) {\n\t\tconst chunk = new Chunk(0, string.length, string);\n\n\t\tObject.defineProperties(this, {\n\t\t\toriginal: { writable: true, value: string },\n\t\t\toutro: { writable: true, value: '' },\n\t\t\tintro: { writable: true, value: '' },\n\t\t\tfirstChunk: { writable: true, value: chunk },\n\t\t\tlastChunk: { writable: true, value: chunk },\n\t\t\tlastSearchedChunk: { writable: true, value: chunk },\n\t\t\tbyStart: { writable: true, value: {} },\n\t\t\tbyEnd: { writable: true, value: {} },\n\t\t\tfilename: { writable: true, value: options.filename },\n\t\t\tindentExclusionRanges: { writable: true, value: options.indentExclusionRanges },\n\t\t\tsourcemapLocations: { writable: true, value: new BitSet() },\n\t\t\tstoredNames: { writable: true, value: {} },\n\t\t\tindentStr: { writable: true, value: guessIndent(string) },\n\t\t});\n\n\t\tif (DEBUG) {\n\t\t\tObject.defineProperty(this, 'stats', { value: new Stats() });\n\t\t}\n\n\t\tthis.byStart[0] = chunk;\n\t\tthis.byEnd[string.length] = chunk;\n\t}\n\n\taddSourcemapLocation(char) {\n\t\tthis.sourcemapLocations.add(char);\n\t}\n\n\tappend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.outro += content;\n\t\treturn this;\n\t}\n\n\tappendLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendLeft');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendLeft(content);\n\t\t} else {\n\t\t\tthis.intro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendLeft');\n\t\treturn this;\n\t}\n\n\tappendRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendRight(content);\n\t\t} else {\n\t\t\tthis.outro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendRight');\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst cloned = new MagicString(this.original, { filename: this.filename });\n\n\t\tlet originalChunk = this.firstChunk;\n\t\tlet clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());\n\n\t\twhile (originalChunk) {\n\t\t\tcloned.byStart[clonedChunk.start] = clonedChunk;\n\t\t\tcloned.byEnd[clonedChunk.end] = clonedChunk;\n\n\t\t\tconst nextOriginalChunk = originalChunk.next;\n\t\t\tconst nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();\n\n\t\t\tif (nextClonedChunk) {\n\t\t\t\tclonedChunk.next = nextClonedChunk;\n\t\t\t\tnextClonedChunk.previous = clonedChunk;\n\n\t\t\t\tclonedChunk = nextClonedChunk;\n\t\t\t}\n\n\t\t\toriginalChunk = nextOriginalChunk;\n\t\t}\n\n\t\tcloned.lastChunk = clonedChunk;\n\n\t\tif (this.indentExclusionRanges) {\n\t\t\tcloned.indentExclusionRanges = this.indentExclusionRanges.slice();\n\t\t}\n\n\t\tcloned.sourcemapLocations = new BitSet(this.sourcemapLocations);\n\n\t\tcloned.intro = this.intro;\n\t\tcloned.outro = this.outro;\n\n\t\treturn cloned;\n\t}\n\n\tgenerateDecodedMap(options) {\n\t\toptions = options || {};\n\n\t\tconst sourceIndex = 0;\n\t\tconst names = Object.keys(this.storedNames);\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tconst locate = getLocator(this.original);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.firstChunk.eachNext((chunk) => {\n\t\t\tconst loc = locate(chunk.start);\n\n\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tmappings.addEdit(\n\t\t\t\t\tsourceIndex,\n\t\t\t\t\tchunk.content,\n\t\t\t\t\tloc,\n\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);\n\t\t\t}\n\n\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : null,\n\t\t\tsources: [options.source ? getRelativePath(options.file || '', options.source) : null],\n\t\t\tsourcesContent: options.includeContent ? [this.original] : [null],\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\treturn this.indentStr === null ? '\\t' : this.indentStr;\n\t}\n\n\tindent(indentStr, options) {\n\t\tconst pattern = /^[^\\r\\n]/gm;\n\n\t\tif (isObject(indentStr)) {\n\t\t\toptions = indentStr;\n\t\t\tindentStr = undefined;\n\t\t}\n\n\t\tindentStr = indentStr !== undefined ? indentStr : this.indentStr || '\\t';\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\toptions = options || {};\n\n\t\t// Process exclusion ranges\n\t\tconst isExcluded = {};\n\n\t\tif (options.exclude) {\n\t\t\tconst exclusions =\n\t\t\t\ttypeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;\n\t\t\texclusions.forEach((exclusion) => {\n\t\t\t\tfor (let i = exclusion[0]; i < exclusion[1]; i += 1) {\n\t\t\t\t\tisExcluded[i] = true;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tlet shouldIndentNextCharacter = options.indentStart !== false;\n\t\tconst replacer = (match) => {\n\t\t\tif (shouldIndentNextCharacter) return `${indentStr}${match}`;\n\t\t\tshouldIndentNextCharacter = true;\n\t\t\treturn match;\n\t\t};\n\n\t\tthis.intro = this.intro.replace(pattern, replacer);\n\n\t\tlet charIndex = 0;\n\t\tlet chunk = this.firstChunk;\n\n\t\twhile (chunk) {\n\t\t\tconst end = chunk.end;\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\tchunk.content = chunk.content.replace(pattern, replacer);\n\n\t\t\t\t\tif (chunk.content.length) {\n\t\t\t\t\t\tshouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\\n';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcharIndex = chunk.start;\n\n\t\t\t\twhile (charIndex < end) {\n\t\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\t\tconst char = this.original[charIndex];\n\n\t\t\t\t\t\tif (char === '\\n') {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = true;\n\t\t\t\t\t\t} else if (char !== '\\r' && shouldIndentNextCharacter) {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = false;\n\n\t\t\t\t\t\t\tif (charIndex === chunk.start) {\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthis._splitChunk(chunk, charIndex);\n\t\t\t\t\t\t\t\tchunk = chunk.next;\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcharIndex += 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcharIndex = chunk.end;\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tthis.outro = this.outro.replace(pattern, replacer);\n\n\t\treturn this;\n\t}\n\n\tinsert() {\n\t\tthrow new Error(\n\t\t\t'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'\n\t\t);\n\t}\n\n\tinsertLeft(index, content) {\n\t\tif (!warned.insertLeft) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertLeft = true;\n\t\t}\n\n\t\treturn this.appendLeft(index, content);\n\t}\n\n\tinsertRight(index, content) {\n\t\tif (!warned.insertRight) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertRight = true;\n\t\t}\n\n\t\treturn this.prependRight(index, content);\n\t}\n\n\tmove(start, end, index) {\n\t\tif (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');\n\n\t\tif (DEBUG) this.stats.time('move');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\t\tthis._split(index);\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tconst oldLeft = first.previous;\n\t\tconst oldRight = last.next;\n\n\t\tconst newRight = this.byStart[index];\n\t\tif (!newRight && last === this.lastChunk) return this;\n\t\tconst newLeft = newRight ? newRight.previous : this.lastChunk;\n\n\t\tif (oldLeft) oldLeft.next = oldRight;\n\t\tif (oldRight) oldRight.previous = oldLeft;\n\n\t\tif (newLeft) newLeft.next = first;\n\t\tif (newRight) newRight.previous = last;\n\n\t\tif (!first.previous) this.firstChunk = last.next;\n\t\tif (!last.next) {\n\t\t\tthis.lastChunk = first.previous;\n\t\t\tthis.lastChunk.next = null;\n\t\t}\n\n\t\tfirst.previous = newLeft;\n\t\tlast.next = newRight || null;\n\n\t\tif (!newLeft) this.firstChunk = first;\n\t\tif (!newRight) this.lastChunk = last;\n\n\t\tif (DEBUG) this.stats.timeEnd('move');\n\t\treturn this;\n\t}\n\n\toverwrite(start, end, content, options) {\n\t\tif (typeof content !== 'string') throw new TypeError('replacement content must be a string');\n\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (end > this.original.length) throw new Error('end is out of bounds');\n\t\tif (start === end)\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'\n\t\t\t);\n\n\t\tif (DEBUG) this.stats.time('overwrite');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tif (options === true) {\n\t\t\tif (!warned.storeName) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'\n\t\t\t\t); // eslint-disable-line no-console\n\t\t\t\twarned.storeName = true;\n\t\t\t}\n\n\t\t\toptions = { storeName: true };\n\t\t}\n\t\tconst storeName = options !== undefined ? options.storeName : false;\n\t\tconst contentOnly = options !== undefined ? options.contentOnly : false;\n\n\t\tif (storeName) {\n\t\t\tconst original = this.original.slice(start, end);\n\t\t\tObject.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true });\n\t\t}\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tif (first) {\n\t\t\tlet chunk = first;\n\t\t\twhile (chunk !== last) {\n\t\t\t\tif (chunk.next !== this.byStart[chunk.end]) {\n\t\t\t\t\tthrow new Error('Cannot overwrite across a split point');\n\t\t\t\t}\n\t\t\t\tchunk = chunk.next;\n\t\t\t\tchunk.edit('', false);\n\t\t\t}\n\n\t\t\tfirst.edit(content, storeName, contentOnly);\n\t\t} else {\n\t\t\t// must be inserting at the end\n\t\t\tconst newChunk = new Chunk(start, end, '').edit(content, storeName);\n\n\t\t\t// TODO last chunk in the array may not be the last chunk, if it's moved...\n\t\t\tlast.next = newChunk;\n\t\t\tnewChunk.previous = last;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('overwrite');\n\t\treturn this;\n\t}\n\n\tprepend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.intro = content + this.intro;\n\t\treturn this;\n\t}\n\n\tprependLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependLeft(content);\n\t\t} else {\n\t\t\tthis.intro = content + this.intro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tprependRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependRight(content);\n\t\t} else {\n\t\t\tthis.outro = content + this.outro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tremove(start, end) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('remove');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.intro = '';\n\t\t\tchunk.outro = '';\n\t\t\tchunk.edit('');\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('remove');\n\t\treturn this;\n\t}\n\n\tlastChar() {\n\t\tif (this.outro.length) return this.outro[this.outro.length - 1];\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];\n\t\t\tif (chunk.content.length) return chunk.content[chunk.content.length - 1];\n\t\t\tif (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];\n\t\t} while ((chunk = chunk.previous));\n\t\tif (this.intro.length) return this.intro[this.intro.length - 1];\n\t\treturn '';\n\t}\n\n\tlastLine() {\n\t\tlet lineIndex = this.outro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.outro.substr(lineIndex + 1);\n\t\tlet lineStr = this.outro;\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length > 0) {\n\t\t\t\tlineIndex = chunk.outro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.outro + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.content.length > 0) {\n\t\t\t\tlineIndex = chunk.content.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.content + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.intro.length > 0) {\n\t\t\t\tlineIndex = chunk.intro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.intro + lineStr;\n\t\t\t}\n\t\t} while ((chunk = chunk.previous));\n\t\tlineIndex = this.intro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;\n\t\treturn this.intro + lineStr;\n\t}\n\n\tslice(start = 0, end = this.original.length) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tlet result = '';\n\n\t\t// find start chunk\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk && (chunk.start > start || chunk.end <= start)) {\n\t\t\t// found end chunk before start\n\t\t\tif (chunk.start < end && chunk.end >= end) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tif (chunk && chunk.edited && chunk.start !== start)\n\t\t\tthrow new Error(`Cannot use replaced character ${start} as slice start anchor.`);\n\n\t\tconst startChunk = chunk;\n\t\twhile (chunk) {\n\t\t\tif (chunk.intro && (startChunk !== chunk || chunk.start === start)) {\n\t\t\t\tresult += chunk.intro;\n\t\t\t}\n\n\t\t\tconst containsEnd = chunk.start < end && chunk.end >= end;\n\t\t\tif (containsEnd && chunk.edited && chunk.end !== end)\n\t\t\t\tthrow new Error(`Cannot use replaced character ${end} as slice end anchor.`);\n\n\t\t\tconst sliceStart = startChunk === chunk ? start - chunk.start : 0;\n\t\t\tconst sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;\n\n\t\t\tresult += chunk.content.slice(sliceStart, sliceEnd);\n\n\t\t\tif (chunk.outro && (!containsEnd || chunk.end === end)) {\n\t\t\t\tresult += chunk.outro;\n\t\t\t}\n\n\t\t\tif (containsEnd) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t// TODO deprecate this? not really very useful\n\tsnip(start, end) {\n\t\tconst clone = this.clone();\n\t\tclone.remove(0, start);\n\t\tclone.remove(end, clone.original.length);\n\n\t\treturn clone;\n\t}\n\n\t_split(index) {\n\t\tif (this.byStart[index] || this.byEnd[index]) return;\n\n\t\tif (DEBUG) this.stats.time('_split');\n\n\t\tlet chunk = this.lastSearchedChunk;\n\t\tconst searchForward = index > chunk.end;\n\n\t\twhile (chunk) {\n\t\t\tif (chunk.contains(index)) return this._splitChunk(chunk, index);\n\n\t\t\tchunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];\n\t\t}\n\t}\n\n\t_splitChunk(chunk, index) {\n\t\tif (chunk.edited && chunk.content.length) {\n\t\t\t// zero-length edited chunks are a special case (overlapping replacements)\n\t\t\tconst loc = getLocator(this.original)(index);\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – \"${chunk.original}\")`\n\t\t\t);\n\t\t}\n\n\t\tconst newChunk = chunk.split(index);\n\n\t\tthis.byEnd[index] = chunk;\n\t\tthis.byStart[index] = newChunk;\n\t\tthis.byEnd[newChunk.end] = newChunk;\n\n\t\tif (chunk === this.lastChunk) this.lastChunk = newChunk;\n\n\t\tthis.lastSearchedChunk = chunk;\n\t\tif (DEBUG) this.stats.timeEnd('_split');\n\t\treturn true;\n\t}\n\n\ttoString() {\n\t\tlet str = this.intro;\n\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk) {\n\t\t\tstr += chunk.toString();\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn str + this.outro;\n\t}\n\n\tisEmpty() {\n\t\tlet chunk = this.firstChunk;\n\t\tdo {\n\t\t\tif (\n\t\t\t\t(chunk.intro.length && chunk.intro.trim()) ||\n\t\t\t\t(chunk.content.length && chunk.content.trim()) ||\n\t\t\t\t(chunk.outro.length && chunk.outro.trim())\n\t\t\t)\n\t\t\t\treturn false;\n\t\t} while ((chunk = chunk.next));\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\tlet chunk = this.firstChunk;\n\t\tlet length = 0;\n\t\tdo {\n\t\t\tlength += chunk.intro.length + chunk.content.length + chunk.outro.length;\n\t\t} while ((chunk = chunk.next));\n\t\treturn length;\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimEndAborted(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tlet chunk = this.lastChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimEnd(rx);\n\n\t\t\t// if chunk was trimmed, we have a new lastChunk\n\t\t\tif (chunk.end !== end) {\n\t\t\t\tif (this.lastChunk === chunk) {\n\t\t\t\t\tthis.lastChunk = chunk.next;\n\t\t\t\t}\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.previous;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimEnd(charType) {\n\t\tthis.trimEndAborted(charType);\n\t\treturn this;\n\t}\n\ttrimStartAborted(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tlet chunk = this.firstChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimStart(rx);\n\n\t\t\tif (chunk.end !== end) {\n\t\t\t\t// special case...\n\t\t\t\tif (chunk === this.lastChunk) this.lastChunk = chunk.next;\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.next;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimStart(charType) {\n\t\tthis.trimStartAborted(charType);\n\t\treturn this;\n\t}\n}\n","import MagicString from './MagicString.js';\nimport SourceMap from './SourceMap.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\n\nconst hasOwnProp = Object.prototype.hasOwnProperty;\n\nexport default class Bundle {\n\tconstructor(options = {}) {\n\t\tthis.intro = options.intro || '';\n\t\tthis.separator = options.separator !== undefined ? options.separator : '\\n';\n\t\tthis.sources = [];\n\t\tthis.uniqueSources = [];\n\t\tthis.uniqueSourceIndexByFilename = {};\n\t}\n\n\taddSource(source) {\n\t\tif (source instanceof MagicString) {\n\t\t\treturn this.addSource({\n\t\t\t\tcontent: source,\n\t\t\t\tfilename: source.filename,\n\t\t\t\tseparator: this.separator,\n\t\t\t});\n\t\t}\n\n\t\tif (!isObject(source) || !source.content) {\n\t\t\tthrow new Error(\n\t\t\t\t'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'\n\t\t\t);\n\t\t}\n\n\t\t['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {\n\t\t\tif (!hasOwnProp.call(source, option)) source[option] = source.content[option];\n\t\t});\n\n\t\tif (source.separator === undefined) {\n\t\t\t// TODO there's a bunch of this sort of thing, needs cleaning up\n\t\t\tsource.separator = this.separator;\n\t\t}\n\n\t\tif (source.filename) {\n\t\t\tif (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {\n\t\t\t\tthis.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;\n\t\t\t\tthis.uniqueSources.push({ filename: source.filename, content: source.content.original });\n\t\t\t} else {\n\t\t\t\tconst uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];\n\t\t\t\tif (source.content.original !== uniqueSource.content) {\n\t\t\t\t\tthrow new Error(`Illegal source: same filename (${source.filename}), different contents`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.sources.push(source);\n\t\treturn this;\n\t}\n\n\tappend(str, options) {\n\t\tthis.addSource({\n\t\t\tcontent: new MagicString(str),\n\t\t\tseparator: (options && options.separator) || '',\n\t\t});\n\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst bundle = new Bundle({\n\t\t\tintro: this.intro,\n\t\t\tseparator: this.separator,\n\t\t});\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tbundle.addSource({\n\t\t\t\tfilename: source.filename,\n\t\t\t\tcontent: source.content.clone(),\n\t\t\t\tseparator: source.separator,\n\t\t\t});\n\t\t});\n\n\t\treturn bundle;\n\t}\n\n\tgenerateDecodedMap(options = {}) {\n\t\tconst names = [];\n\t\tthis.sources.forEach((source) => {\n\t\t\tObject.keys(source.content.storedNames).forEach((name) => {\n\t\t\t\tif (!~names.indexOf(name)) names.push(name);\n\t\t\t});\n\t\t});\n\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tif (i > 0) {\n\t\t\t\tmappings.advance(this.separator);\n\t\t\t}\n\n\t\t\tconst sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;\n\t\t\tconst magicString = source.content;\n\t\t\tconst locate = getLocator(magicString.original);\n\n\t\t\tif (magicString.intro) {\n\t\t\t\tmappings.advance(magicString.intro);\n\t\t\t}\n\n\t\t\tmagicString.firstChunk.eachNext((chunk) => {\n\t\t\t\tconst loc = locate(chunk.start);\n\n\t\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\t\tif (source.filename) {\n\t\t\t\t\tif (chunk.edited) {\n\t\t\t\t\t\tmappings.addEdit(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk.content,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmappings.addUneditedChunk(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk,\n\t\t\t\t\t\t\tmagicString.original,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tmagicString.sourcemapLocations\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmappings.advance(chunk.content);\n\t\t\t\t}\n\n\t\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t\t});\n\n\t\t\tif (magicString.outro) {\n\t\t\t\tmappings.advance(magicString.outro);\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : null,\n\t\t\tsources: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.file ? getRelativePath(options.file, source.filename) : source.filename;\n\t\t\t}),\n\t\t\tsourcesContent: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.includeContent ? source.content : null;\n\t\t\t}),\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\tconst indentStringCounts = {};\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tconst indentStr = source.content.indentStr;\n\n\t\t\tif (indentStr === null) return;\n\n\t\t\tif (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;\n\t\t\tindentStringCounts[indentStr] += 1;\n\t\t});\n\n\t\treturn (\n\t\t\tObject.keys(indentStringCounts).sort((a, b) => {\n\t\t\t\treturn indentStringCounts[a] - indentStringCounts[b];\n\t\t\t})[0] || '\\t'\n\t\t);\n\t}\n\n\tindent(indentStr) {\n\t\tif (!arguments.length) {\n\t\t\tindentStr = this.getIndentString();\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\tlet trailingNewline = !this.intro || this.intro.slice(-1) === '\\n';\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\tconst indentStart = trailingNewline || (i > 0 && /\\r?\\n$/.test(separator));\n\n\t\t\tsource.content.indent(indentStr, {\n\t\t\t\texclude: source.indentExclusionRanges,\n\t\t\t\tindentStart, //: trailingNewline || /\\r?\\n$/.test( separator ) //true///\\r?\\n/.test( separator )\n\t\t\t});\n\n\t\t\ttrailingNewline = source.content.lastChar() === '\\n';\n\t\t});\n\n\t\tif (this.intro) {\n\t\t\tthis.intro =\n\t\t\t\tindentStr +\n\t\t\t\tthis.intro.replace(/^[^\\n]/gm, (match, index) => {\n\t\t\t\t\treturn index > 0 ? indentStr + match : match;\n\t\t\t\t});\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tprepend(str) {\n\t\tthis.intro = str + this.intro;\n\t\treturn this;\n\t}\n\n\ttoString() {\n\t\tconst body = this.sources\n\t\t\t.map((source, i) => {\n\t\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\t\tconst str = (i > 0 ? separator : '') + source.content.toString();\n\n\t\t\t\treturn str;\n\t\t\t})\n\t\t\t.join('');\n\n\t\treturn this.intro + body;\n\t}\n\n\tisEmpty() {\n\t\tif (this.intro.length && this.intro.trim()) return false;\n\t\tif (this.sources.some((source) => !source.content.isEmpty())) return false;\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\treturn this.sources.reduce(\n\t\t\t(length, source) => length + source.content.length(),\n\t\t\tthis.intro.length\n\t\t);\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimStart(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\t\tthis.intro = this.intro.replace(rx, '');\n\n\t\tif (!this.intro) {\n\t\t\tlet source;\n\t\t\tlet i = 0;\n\n\t\t\tdo {\n\t\t\t\tsource = this.sources[i++];\n\t\t\t\tif (!source) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} while (!source.content.trimStartAborted(charType));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\ttrimEnd(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tlet source;\n\t\tlet i = this.sources.length - 1;\n\n\t\tdo {\n\t\t\tsource = this.sources[i--];\n\t\t\tif (!source) {\n\t\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (!source.content.trimEndAborted(charType));\n\n\t\treturn this;\n\t}\n}\n","import MagicString from './MagicString.js';\nimport Bundle from './Bundle.js';\nimport SourceMap from './SourceMap.js';\n\nMagicString.Bundle = Bundle;\nMagicString.SourceMap = SourceMap;\nMagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121\n\nexport default MagicString;\n"],"names":["const","let","this"],"mappings":";;;;;;CAAe,IAAM,MAAM,GAC1B,eAAW,CAAC,GAAG,EAAE;CAClB,CAAE,IAAI,CAAC,IAAI,GAAG,GAAG,YAAY,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC;CAC3D,EAAC;AACF;kB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ACA,EAAG,GAAG;CACN,GAAI,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;CAC/B,GAAI,IAAI,CAAC,MAAM,EAAE;CACjB,IAAK,MAAM;CACX,IAAK;CACL,GAAI,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE;CACxD,EAAG;AACH;CACA,CAAE,OAAO,IAAI,CAAC;CACb,EAAC;AACF;kBACC,4BAAQ,QAAQ,EAAE;CACnB,CAAED,IAAM,EAAE,GAAG,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC;AACpD;CACA,CAAEC,IAAI,MAAM,CAAC;CACb,CAAEA,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;AAClC;CACA,CAAE,GAAG;CACL,EAAG,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;CAC9B,EAAG,IAAI,CAAC,MAAM,EAAE;CAChB,GAAI,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;CAC5C,GAAI,MAAM;CACV,GAAI;CACJ,EAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE;AACrD;CACA,CAAE,OAAO,IAAI,CAAC;CACb;;CC1RD,WAAW,CAAC,MAAM,GAAG,MAAM,CAAC;CAC5B,WAAW,CAAC,SAAS,GAAG,SAAS,CAAC;CAClC,WAAW,CAAC,OAAO,GAAG,WAAW,CAAC;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/magic-string/index.d.ts b/node_modules/magic-string/index.d.ts new file mode 100644 index 0000000..343c49d --- /dev/null +++ b/node_modules/magic-string/index.d.ts @@ -0,0 +1,221 @@ +export interface BundleOptions { + intro?: string; + separator?: string; +} + +export interface SourceMapOptions { + /** + * Whether the mapping should be high-resolution. + * Hi-res mappings map every single character, meaning (for example) your devtools will always + * be able to pinpoint the exact location of function calls and so on. + * With lo-res mappings, devtools may only be able to identify the correct + * line - but they're quicker to generate and less bulky. + * If sourcemap locations have been specified with s.addSourceMapLocation(), they will be used here. + */ + hires?: boolean; + /** + * The filename where you plan to write the sourcemap. + */ + file?: string; + /** + * The filename of the file containing the original source. + */ + source?: string; + /** + * Whether to include the original content in the map's sourcesContent array. + */ + includeContent?: boolean; +} + +export type SourceMapSegment = + | [number] + | [number, number, number, number] + | [number, number, number, number, number]; + +export interface DecodedSourceMap { + file: string; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: SourceMapSegment[][]; +} + +export class SourceMap { + constructor(properties: DecodedSourceMap); + + version: number; + file: string; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + + /** + * Returns the equivalent of `JSON.stringify(map)` + */ + toString(): string; + /** + * Returns a DataURI containing the sourcemap. Useful for doing this sort of thing: + * `generateMap(options?: SourceMapOptions): SourceMap;` + */ + toUrl(): string; +} + +export class Bundle { + constructor(options?: BundleOptions); + addSource(source: MagicString | { filename?: string, content: MagicString }): Bundle; + append(str: string, options?: BundleOptions): Bundle; + clone(): Bundle; + generateMap(options?: SourceMapOptions): SourceMap; + generateDecodedMap(options?: SourceMapOptions): DecodedSourceMap; + getIndentString(): string; + indent(indentStr?: string): Bundle; + indentExclusionRanges: ExclusionRange | Array; + prepend(str: string): Bundle; + toString(): string; + trimLines(): Bundle; + trim(charType?: string): Bundle; + trimStart(charType?: string): Bundle; + trimEnd(charType?: string): Bundle; + isEmpty(): boolean; + length(): number; +} + +export type ExclusionRange = [ number, number ]; + +export interface MagicStringOptions { + filename?: string, + indentExclusionRanges?: ExclusionRange | Array; +} + +export interface IndentOptions { + exclude?: ExclusionRange | Array; + indentStart?: boolean; +} + +export interface OverwriteOptions { + storeName?: boolean; + contentOnly?: boolean; +} + +export default class MagicString { + constructor(str: string, options?: MagicStringOptions); + /** + * Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false. + */ + addSourcemapLocation(char: number): void; + /** + * Appends the specified content to the end of the string. + */ + append(content: string): MagicString; + /** + * Appends the specified content at the index in the original string. + * If a range *ending* with index is subsequently moved, the insert will be moved with it. + * See also `s.prependLeft(...)`. + */ + appendLeft(index: number, content: string): MagicString; + /** + * Appends the specified content at the index in the original string. + * If a range *starting* with index is subsequently moved, the insert will be moved with it. + * See also `s.prependRight(...)`. + */ + appendRight(index: number, content: string): MagicString; + /** + * Does what you'd expect. + */ + clone(): MagicString; + /** + * Generates a version 3 sourcemap. + */ + generateMap(options?: SourceMapOptions): SourceMap; + /** + * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. + * Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead. + */ + generateDecodedMap(options?: SourceMapOptions): DecodedSourceMap; + getIndentString(): string; + + /** + * Prefixes each line of the string with prefix. + * If prefix is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. + */ + indent(options?: IndentOptions): MagicString; + /** + * Prefixes each line of the string with prefix. + * If prefix is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. + * + * The options argument can have an exclude property, which is an array of [start, end] character ranges. + * These ranges will be excluded from the indentation - useful for (e.g.) multiline strings. + */ + indent(indentStr?: string, options?: IndentOptions): MagicString; + indentExclusionRanges: ExclusionRange | Array; + + /** + * Moves the characters from `start and `end` to `index`. + */ + move(start: number, end: number, index: number): MagicString; + /** + * Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. + * + * The fourth argument is optional. It can have a storeName property — if true, the original name will be stored + * for later inclusion in a sourcemap's names array — and a contentOnly property which determines whether only + * the content is overwritten, or anything that was appended/prepended to the range as well. + */ + overwrite(start: number, end: number, content: string, options?: boolean | OverwriteOptions): MagicString; + /** + * Prepends the string with the specified content. + */ + prepend(content: string): MagicString; + /** + * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index + */ + prependLeft(index: number, content: string): MagicString; + /** + * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index` + */ + prependRight(index: number, content: string): MagicString; + /** + * Removes the characters from `start` to `end` (of the original string, **not** the generated string). + * Removing the same content twice, or making removals that partially overlap, will cause an error. + */ + remove(start: number, end: number): MagicString; + /** + * Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. + * Throws error if the indices are for characters that were already removed. + */ + slice(start: number, end: number): string; + /** + * Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed. + */ + snip(start: number, end: number): MagicString; + /** + * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. + */ + trim(charType?: string): MagicString; + /** + * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. + */ + trimStart(charType?: string): MagicString; + /** + * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. + */ + trimEnd(charType?: string): MagicString; + /** + * Removes empty lines from the start and end. + */ + trimLines(): MagicString; + + lastChar(): string; + lastLine(): string; + /** + * Returns true if the resulting source is empty (disregarding white space). + */ + isEmpty(): boolean; + length(): number; + + original: string; + /** + * Returns the generated string. + */ + toString(): string; +} diff --git a/node_modules/magic-string/package.json b/node_modules/magic-string/package.json new file mode 100644 index 0000000..b37e177 --- /dev/null +++ b/node_modules/magic-string/package.json @@ -0,0 +1,52 @@ +{ + "name": "magic-string", + "version": "0.25.9", + "description": "Modify strings, generate sourcemaps", + "keywords": [ + "string", + "string manipulation", + "sourcemap", + "templating", + "transpilation" + ], + "repository": "https://github.com/rich-harris/magic-string", + "license": "MIT", + "author": "Rich Harris", + "main": "dist/magic-string.cjs.js", + "module": "dist/magic-string.es.js", + "jsnext:main": "dist/magic-string.es.js", + "typings": "index.d.ts", + "files": [ + "dist/*", + "index.d.ts", + "README.md" + ], + "scripts": { + "build": "rollup -c", + "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s", + "format": "prettier --single-quote --print-width 100 --use-tabs --write src/*.js src/**/*.js", + "lint": "eslint src test", + "prepare": "npm run build", + "prepublishOnly": "rm -rf dist && npm test", + "release": "bumpp -x \"npm run changelog\" --all --commit --tag --push && npm publish", + "pretest": "npm run lint && npm run build", + "test": "mocha", + "watch": "rollup -cw" + }, + "dependencies": { + "sourcemap-codec": "^1.4.8" + }, + "devDependencies": { + "@rollup/plugin-buble": "^0.21.3", + "@rollup/plugin-node-resolve": "^13.1.3", + "@rollup/plugin-replace": "^4.0.0", + "bumpp": "^7.1.1", + "conventional-changelog-cli": "^2.2.2", + "eslint": "^7.32.0", + "mocha": "^9.2.1", + "prettier": "^2.5.1", + "rollup": "^2.69.0", + "source-map": "^0.6.1", + "source-map-support": "^0.5.21" + } +} diff --git a/node_modules/mime/CHANGELOG.md b/node_modules/mime/CHANGELOG.md new file mode 100644 index 0000000..cdf9be5 --- /dev/null +++ b/node_modules/mime/CHANGELOG.md @@ -0,0 +1,312 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [3.0.0](https://github.com/broofa/mime/compare/v2.6.0...v3.0.0) (2021-11-03) + + +### ⚠ BREAKING CHANGES + +* drop support for node < 10.x + +### Bug Fixes + +* skypack.dev for direct browser import, fixes [#263](https://github.com/broofa/mime/issues/263) ([41db4c0](https://github.com/broofa/mime/commit/41db4c042ccf50ea7baf3d2160ea37dcca37998d)) + + +### update + +* drop support for node < 10.x ([8857363](https://github.com/broofa/mime/commit/8857363ae0446ed0229b17291cf4483cf801f0d0)) + +## [2.6.0](https://github.com/broofa/mime/compare/v2.5.2...v2.6.0) (2021-11-02) + + +### Features + +* mime-db@1.50.0 ([cef0cc4](https://github.com/broofa/mime/commit/cef0cc484ff6d05ff1e12b54ca3e8b856fbc14d8)) + +### [2.5.2](https://github.com/broofa/mime/compare/v2.5.0...v2.5.2) (2021-02-17) + + +### Bug Fixes + +* update to mime-db@1.46.0, fixes [#253](https://github.com/broofa/mime/issues/253) ([f10e6aa](https://github.com/broofa/mime/commit/f10e6aa62e1356de7e2491d7fb4374c8dac65800)) + +## [2.5.0](https://github.com/broofa/mime/compare/v2.4.7...v2.5.0) (2021-01-16) + + +### Features + +* improved CLI ([#244](https://github.com/broofa/mime/issues/244)) ([c8a8356](https://github.com/broofa/mime/commit/c8a8356e3b27f3ef46b64b89b428fdb547b14d5f)) + +### [2.4.7](https://github.com/broofa/mime/compare/v2.4.6...v2.4.7) (2020-12-16) + + +### Bug Fixes + +* update to latest mime-db ([43b09ef](https://github.com/broofa/mime/commit/43b09eff0233eacc449af2b1f99a19ba9e104a44)) + +### [2.4.6](https://github.com/broofa/mime/compare/v2.4.5...v2.4.6) (2020-05-27) + + +### Bug Fixes + +* add cli.js to package.json files ([#237](https://github.com/broofa/mime/issues/237)) ([6c070bc](https://github.com/broofa/mime/commit/6c070bc298fa12a48e2ed126fbb9de641a1e7ebc)) + +### [2.4.5](https://github.com/broofa/mime/compare/v2.4.4...v2.4.5) (2020-05-01) + + +### Bug Fixes + +* fix [#236](https://github.com/broofa/mime/issues/236) ([7f4ecd0](https://github.com/broofa/mime/commit/7f4ecd0d850ed22c9e3bfda2c11fc74e4dde12a7)) +* update to latest mime-db ([c5cb3f2](https://github.com/broofa/mime/commit/c5cb3f2ab8b07642a066efbde1142af1b90c927b)) + +### [2.4.4](https://github.com/broofa/mime/compare/v2.4.3...v2.4.4) (2019-06-07) + + + +### [2.4.3](https://github.com/broofa/mime/compare/v2.4.2...v2.4.3) (2019-05-15) + + + +### [2.4.2](https://github.com/broofa/mime/compare/v2.4.1...v2.4.2) (2019-04-07) + + +### Bug Fixes + +* don't use arrow function introduced in 2.4.1 ([2e00b5c](https://github.com/broofa/mime/commit/2e00b5c)) + + + +### [2.4.1](https://github.com/broofa/mime/compare/v2.4.0...v2.4.1) (2019-04-03) + + +### Bug Fixes + +* update MDN and mime-db types ([3e567a9](https://github.com/broofa/mime/commit/3e567a9)) + + + +# [2.4.0](https://github.com/broofa/mime/compare/v2.3.1...v2.4.0) (2018-11-26) + + +### Features + +* Bind exported methods ([9d2a7b8](https://github.com/broofa/mime/commit/9d2a7b8)) +* update to mime-db@1.37.0 ([49e6e41](https://github.com/broofa/mime/commit/49e6e41)) + + + +### [2.3.1](https://github.com/broofa/mime/compare/v2.3.0...v2.3.1) (2018-04-11) + + +### Bug Fixes + +* fix [#198](https://github.com/broofa/mime/issues/198) ([25ca180](https://github.com/broofa/mime/commit/25ca180)) + + + +# [2.3.0](https://github.com/broofa/mime/compare/v2.2.2...v2.3.0) (2018-04-11) + + +### Bug Fixes + +* fix [#192](https://github.com/broofa/mime/issues/192) ([5c35df6](https://github.com/broofa/mime/commit/5c35df6)) + + +### Features + +* add travis-ci testing ([d64160f](https://github.com/broofa/mime/commit/d64160f)) + + + +### [2.2.2](https://github.com/broofa/mime/compare/v2.2.1...v2.2.2) (2018-03-30) + + +### Bug Fixes + +* update types files to mime-db@1.32.0 ([85aac16](https://github.com/broofa/mime/commit/85aac16)) + + +### [2.2.1](https://github.com/broofa/mime/compare/v2.2.0...v2.2.1) (2018-03-30) + + +### Bug Fixes + +* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/mime/issues/180) ([b5c83fb](https://github.com/broofa/mime/commit/b5c83fb)) + + + +# [2.2.0](https://github.com/broofa/mime/compare/v2.1.0...v2.2.0) (2018-01-04) + + +### Features + +* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/mime/issues/180) ([10f82ac](https://github.com/broofa/mime/commit/10f82ac)) + + + +# [2.1.0](https://github.com/broofa/mime/compare/v2.0.5...v2.1.0) (2017-12-22) + + +### Features + +* Upgrade to mime-db@1.32.0. Fixes [#185](https://github.com/broofa/mime/issues/185) ([3f775ba](https://github.com/broofa/mime/commit/3f775ba)) + + + +### [2.0.5](https://github.com/broofa/mime/compare/v2.0.1...v2.0.5) (2017-12-22) + + +### Bug Fixes + +* ES5 support (back to node v0.4) ([f14ccb6](https://github.com/broofa/mime/commit/f14ccb6)) + + + +# Changelog + +### v2.0.4 (24/11/2017) +- [**closed**] Switch to mime-score module for resolving extension contention issues. [#182](https://github.com/broofa/mime/issues/182) +- [**closed**] Update mime-db to 1.31.0 in v1.x branch [#181](https://github.com/broofa/mime/issues/181) + +--- + +## v1.5.0 (22/11/2017) +- [**closed**] need ES5 version ready in npm package [#179](https://github.com/broofa/mime/issues/179) +- [**closed**] mime-db no trace of iWork - pages / numbers / etc. [#178](https://github.com/broofa/mime/issues/178) +- [**closed**] How it works in brownser ? [#176](https://github.com/broofa/mime/issues/176) +- [**closed**] Missing `./Mime` [#175](https://github.com/broofa/mime/issues/175) +- [**closed**] Vulnerable Regular Expression [#167](https://github.com/broofa/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/mime/issues/172) + +--- + +### v2.0.2 (15/09/2017) +- [**V2**] fs.readFileSync is not a function [#165](https://github.com/broofa/mime/issues/165) +- [**closed**] The extension for video/quicktime should map to .mov, not .qt [#164](https://github.com/broofa/mime/issues/164) +- [**V2**] [v2 Feedback request] Mime class API [#163](https://github.com/broofa/mime/issues/163) +- [**V2**] [v2 Feedback request] Resolving conflicts over extensions [#162](https://github.com/broofa/mime/issues/162) +- [**V2**] Allow callers to load module with official, full, or no defined types. [#161](https://github.com/broofa/mime/issues/161) +- [**V2**] Use "facets" to resolve extension conflicts [#160](https://github.com/broofa/mime/issues/160) +- [**V2**] Remove fs and path dependencies [#152](https://github.com/broofa/mime/issues/152) +- [**V2**] Default content-type should not be application/octet-stream [#139](https://github.com/broofa/mime/issues/139) +- [**V2**] reset mime-types [#124](https://github.com/broofa/mime/issues/124) +- [**V2**] Extensionless paths should return null or false [#113](https://github.com/broofa/mime/issues/113) + +--- + +### v2.0.1 (14/09/2017) +- [**closed**] Changelog for v2.0 does not mention breaking changes [#171](https://github.com/broofa/mime/issues/171) +- [**closed**] MIME breaking with 'class' declaration as it is without 'use strict mode' [#170](https://github.com/broofa/mime/issues/170) + +--- + +## v2.0.0 (12/09/2017) +- [**closed**] woff and woff2 [#168](https://github.com/broofa/mime/issues/168) + +--- + +## v1.4.0 (28/08/2017) +- [**closed**] support for ac3 voc files [#159](https://github.com/broofa/mime/issues/159) +- [**closed**] Help understanding change from application/xml to text/xml [#158](https://github.com/broofa/mime/issues/158) +- [**closed**] no longer able to override mimetype [#157](https://github.com/broofa/mime/issues/157) +- [**closed**] application/vnd.adobe.photoshop [#147](https://github.com/broofa/mime/issues/147) +- [**closed**] Directories should appear as something other than application/octet-stream [#135](https://github.com/broofa/mime/issues/135) +- [**closed**] requested features [#131](https://github.com/broofa/mime/issues/131) +- [**closed**] Make types.json loading optional? [#129](https://github.com/broofa/mime/issues/129) +- [**closed**] Cannot find module './types.json' [#120](https://github.com/broofa/mime/issues/120) +- [**V2**] .wav files show up as "audio/x-wav" instead of "audio/x-wave" [#118](https://github.com/broofa/mime/issues/118) +- [**closed**] Don't be a pain in the ass for node community [#108](https://github.com/broofa/mime/issues/108) +- [**closed**] don't make default_type global [#78](https://github.com/broofa/mime/issues/78) +- [**closed**] mime.extension() fails if the content-type is parameterized [#74](https://github.com/broofa/mime/issues/74) + +--- + +### v1.3.6 (11/05/2017) +- [**closed**] .md should be text/markdown as of March 2016 [#154](https://github.com/broofa/mime/issues/154) +- [**closed**] Error while installing mime [#153](https://github.com/broofa/mime/issues/153) +- [**closed**] application/manifest+json [#149](https://github.com/broofa/mime/issues/149) +- [**closed**] Dynamic adaptive streaming over HTTP (DASH) file extension typo [#141](https://github.com/broofa/mime/issues/141) +- [**closed**] charsets image/png undefined [#140](https://github.com/broofa/mime/issues/140) +- [**closed**] Mime-db dependency out of date [#130](https://github.com/broofa/mime/issues/130) +- [**closed**] how to support plist? [#126](https://github.com/broofa/mime/issues/126) +- [**closed**] how does .types file format look like? [#123](https://github.com/broofa/mime/issues/123) +- [**closed**] Feature: support for expanding MIME patterns [#121](https://github.com/broofa/mime/issues/121) +- [**closed**] DEBUG_MIME doesn't work [#117](https://github.com/broofa/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/mime/issues/111) +- [**closed**] Consider adding support for hjson. [#110](https://github.com/broofa/mime/issues/110) +- [**closed**] Add mime type for Opus audio files [#94](https://github.com/broofa/mime/issues/94) +- [**closed**] Consider making the `Requesting New Types` information more visible [#77](https://github.com/broofa/mime/issues/77) + +--- + +## v1.3.0 (05/02/2015) +- [**closed**] Add common name? [#114](https://github.com/broofa/mime/issues/114) +- [**closed**] application/x-yaml [#104](https://github.com/broofa/mime/issues/104) +- [**closed**] Add mime type for WOFF file format 2.0 [#102](https://github.com/broofa/mime/issues/102) +- [**closed**] application/x-msi for .msi [#99](https://github.com/broofa/mime/issues/99) +- [**closed**] Add mimetype for gettext translation files [#98](https://github.com/broofa/mime/issues/98) +- [**closed**] collaborators [#88](https://github.com/broofa/mime/issues/88) +- [**closed**] getting errot in installation of mime module...any1 can help? [#87](https://github.com/broofa/mime/issues/87) +- [**closed**] should application/json's charset be utf8? [#86](https://github.com/broofa/mime/issues/86) +- [**closed**] Add "license" and "licenses" to package.json [#81](https://github.com/broofa/mime/issues/81) +- [**closed**] lookup with extension-less file on Windows returns wrong type [#68](https://github.com/broofa/mime/issues/68) + +--- + +### v1.2.11 (15/08/2013) +- [**closed**] Update mime.types [#65](https://github.com/broofa/mime/issues/65) +- [**closed**] Publish a new version [#63](https://github.com/broofa/mime/issues/63) +- [**closed**] README should state upfront that "application/octet-stream" is default for unknown extension [#55](https://github.com/broofa/mime/issues/55) +- [**closed**] Suggested improvement to the charset API [#52](https://github.com/broofa/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/mime/issues/62) +- [**closed**] node.types in conflict with mime.types [#51](https://github.com/broofa/mime/issues/51) + +--- + +### v1.2.9 (17/01/2013) +- [**closed**] Please update "mime" NPM [#49](https://github.com/broofa/mime/issues/49) +- [**closed**] Please add semicolon [#46](https://github.com/broofa/mime/issues/46) +- [**closed**] parse full mime types [#43](https://github.com/broofa/mime/issues/43) + +--- + +### v1.2.8 (10/01/2013) +- [**closed**] /js directory mime is application/javascript. Is it correct? [#47](https://github.com/broofa/mime/issues/47) +- [**closed**] Add mime types for lua code. [#45](https://github.com/broofa/mime/issues/45) + +--- + +### v1.2.7 (19/10/2012) +- [**closed**] cannot install 1.2.7 via npm [#41](https://github.com/broofa/mime/issues/41) +- [**closed**] Transfer ownership to @broofa [#36](https://github.com/broofa/mime/issues/36) +- [**closed**] it's wrong to set charset to UTF-8 for text [#30](https://github.com/broofa/mime/issues/30) +- [**closed**] Allow multiple instances of MIME types container [#27](https://github.com/broofa/mime/issues/27) diff --git a/node_modules/mime/LICENSE b/node_modules/mime/LICENSE new file mode 100644 index 0000000..d3f46f7 --- /dev/null +++ b/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/node_modules/mime/Mime.js b/node_modules/mime/Mime.js new file mode 100644 index 0000000..969a66e --- /dev/null +++ b/node_modules/mime/Mime.js @@ -0,0 +1,97 @@ +'use strict'; + +/** + * @param typeMap [Object] Map of MIME type -> Array[extensions] + * @param ... + */ +function Mime() { + this._types = Object.create(null); + this._extensions = Object.create(null); + + for (let i = 0; i < arguments.length; i++) { + this.define(arguments[i]); + } + + this.define = this.define.bind(this); + this.getType = this.getType.bind(this); + this.getExtension = this.getExtension.bind(this); +} + +/** + * 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']}); + * + * If a type declares an extension that has already been defined, an error will + * be thrown. To suppress this error and force the extension to be associated + * with the new type, pass `force`=true. Alternatively, you may prefix the + * extension with "*" to map the type to extension, without mapping the + * extension to the type. + * + * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']}); + * + * + * @param map (Object) type definitions + * @param force (Boolean) if true, force overriding of existing definitions + */ +Mime.prototype.define = function(typeMap, force) { + for (let type in typeMap) { + let extensions = typeMap[type].map(function(t) { + return t.toLowerCase(); + }); + type = type.toLowerCase(); + + for (let i = 0; i < extensions.length; i++) { + const ext = extensions[i]; + + // '*' prefix = not the preferred type for this extension. So fixup the + // extension, and skip it. + if (ext[0] === '*') { + continue; + } + + if (!force && (ext in this._types)) { + throw new Error( + 'Attempt to change mapping for "' + ext + + '" extension from "' + this._types[ext] + '" to "' + type + + '". Pass `force=true` to allow this, otherwise remove "' + ext + + '" from the list of extensions for "' + type + '".' + ); + } + + this._types[ext] = type; + } + + // Use first extension as default + if (force || !this._extensions[type]) { + const ext = extensions[0]; + this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1); + } + } +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.getType = function(path) { + path = String(path); + let last = path.replace(/^.*[/\\]/, '').toLowerCase(); + let ext = last.replace(/^.*\./, '').toLowerCase(); + + let hasPath = last.length < path.length; + let hasDot = ext.length < last.length - 1; + + return (hasDot || !hasPath) && this._types[ext] || null; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.getExtension = function(type) { + type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; + return type && this._extensions[type.toLowerCase()] || null; +}; + +module.exports = Mime; diff --git a/node_modules/mime/README.md b/node_modules/mime/README.md new file mode 100644 index 0000000..fc816cb --- /dev/null +++ b/node_modules/mime/README.md @@ -0,0 +1,178 @@ + +# Mime + +A comprehensive, compact MIME type module. + +[![Build Status](https://travis-ci.org/broofa/mime.svg?branch=master)](https://travis-ci.org/broofa/mime) + +## Install + +### NPM +``` +npm install mime +``` + +### Browser + +It is recommended that you use a bundler such as +[webpack](https://webpack.github.io/) or [browserify](http://browserify.org/) to +package your code. However, browser-ready versions are available via +skypack.dev as follows: +``` +// Full version + +``` + +``` +// "lite" version + +``` + +## Quick Start + +For the full version (800+ MIME types, 1,000+ extensions): + +```javascript +const mime = require('mime'); + +mime.getType('txt'); // ⇨ 'text/plain' +mime.getExtension('text/plain'); // ⇨ 'txt' +``` + +See [Mime API](#mime-api) below for API details. + +## Lite Version + +The "lite" version of this module omits vendor-specific (`*/vnd.*`) and +experimental (`*/x-*`) types. It weighs in at ~2.5KB, compared to 8KB for the +full version. To load the lite version: + +```javascript +const mime = require('mime/lite'); +``` + +## Mime .vs. mime-types .vs. mime-db modules + +For those of you wondering about the difference between these [popular] NPM modules, +here's a brief rundown ... + +[`mime-db`](https://github.com/jshttp/mime-db) is "the source of +truth" for MIME type information. It is not an API. Rather, it is a canonical +dataset of mime type definitions pulled from IANA, Apache, NGINX, and custom mappings +submitted by the Node.js community. + +[`mime-types`](https://github.com/jshttp/mime-types) is a thin +wrapper around mime-db that provides an API drop-in compatible(ish) with `mime @ < v1.3.6` API. + +`mime` is, as of v2, a self-contained module bundled with a pre-optimized version +of the `mime-db` dataset. It provides a simplified API with the following characteristics: + +* Intelligently resolved type conflicts (See [mime-score](https://github.com/broofa/mime-score) for details) +* Method naming consistent with industry best-practices +* Compact footprint. E.g. The minified+compressed sizes of the various modules: + +Module | Size +--- | --- +`mime-db` | 18 KB +`mime-types` | same as mime-db +`mime` | 8 KB +`mime/lite` | 2 KB + +## Mime API + +Both `require('mime')` and `require('mime/lite')` return instances of the MIME +class, documented below. + +Note: Inputs to this API are case-insensitive. Outputs (returned values) will +be lowercase. + +### new Mime(typeMap, ... more maps) + +Most users of this module will not need to create Mime instances directly. +However if you would like to create custom mappings, you may do so as follows +... + +```javascript +// Require Mime class +const Mime = require('mime/Mime'); + +// Define mime type -> extensions map +const typeMap = { + 'text/abc': ['abc', 'alpha', 'bet'], + 'text/def': ['leppard'] +}; + +// Create and use Mime instance +const myMime = new Mime(typeMap); +myMime.getType('abc'); // ⇨ 'text/abc' +myMime.getExtension('text/def'); // ⇨ 'leppard' +``` + +If more than one map argument is provided, each map is `define()`ed (see below), in order. + +### mime.getType(pathOrExtension) + +Get mime type for the given path or extension. E.g. + +```javascript +mime.getType('js'); // ⇨ 'application/javascript' +mime.getType('json'); // ⇨ 'application/json' + +mime.getType('txt'); // ⇨ 'text/plain' +mime.getType('dir/text.txt'); // ⇨ 'text/plain' +mime.getType('dir\\text.txt'); // ⇨ 'text/plain' +mime.getType('.text.txt'); // ⇨ 'text/plain' +mime.getType('.txt'); // ⇨ 'text/plain' +``` + +`null` is returned in cases where an extension is not detected or recognized + +```javascript +mime.getType('foo/txt'); // ⇨ null +mime.getType('bogus_type'); // ⇨ null +``` + +### mime.getExtension(type) +Get extension for the given mime type. Charset options (often included in +Content-Type headers) are ignored. + +```javascript +mime.getExtension('text/plain'); // ⇨ 'txt' +mime.getExtension('application/json'); // ⇨ 'json' +mime.getExtension('text/html; charset=utf8'); // ⇨ 'html' +``` + +### mime.define(typeMap[, force = false]) + +Define [more] type mappings. + +`typeMap` is a map of type -> extensions, as documented in `new Mime`, above. + +By default this method will throw an error if you try to map a type to an +extension that is already assigned to another type. Passing `true` for the +`force` argument will suppress this behavior (overriding any previous mapping). + +```javascript +mime.define({'text/x-abc': ['abc', 'abcd']}); + +mime.getType('abcd'); // ⇨ 'text/x-abc' +mime.getExtension('text/x-abc') // ⇨ 'abc' +``` + +## Command Line + + mime [path_or_extension] + +E.g. + + > mime scripts/jquery.js + application/javascript + +---- +Markdown generated from [src/README_js.md](src/README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) \ No newline at end of file diff --git a/node_modules/mime/cli.js b/node_modules/mime/cli.js new file mode 100755 index 0000000..ab70a49 --- /dev/null +++ b/node_modules/mime/cli.js @@ -0,0 +1,46 @@ +#!/usr/bin/env node + +'use strict'; + +process.title = 'mime'; +let mime = require('.'); +let pkg = require('./package.json'); +let args = process.argv.splice(2); + +if (args.includes('--version') || args.includes('-v') || args.includes('--v')) { + console.log(pkg.version); + process.exit(0); +} else if (args.includes('--name') || args.includes('-n') || args.includes('--n')) { + console.log(pkg.name); + process.exit(0); +} else if (args.includes('--help') || args.includes('-h') || args.includes('--h')) { + console.log(pkg.name + ' - ' + pkg.description + '\n'); + console.log(`Usage: + + mime [flags] [path_or_extension] + + Flags: + --help, -h Show this message + --version, -v Display the version + --name, -n Print the name of the program + + Note: the command will exit after it executes if a command is specified + The path_or_extension is the path to the file or the extension of the file. + + Examples: + mime --help + mime --version + mime --name + mime -v + mime src/log.js + mime new.py + mime foo.sh + `); + process.exit(0); +} + +let file = args[0]; +let type = mime.getType(file); + +process.stdout.write(type + '\n'); + diff --git a/node_modules/mime/index.js b/node_modules/mime/index.js new file mode 100644 index 0000000..fadcf8d --- /dev/null +++ b/node_modules/mime/index.js @@ -0,0 +1,4 @@ +'use strict'; + +let Mime = require('./Mime'); +module.exports = new Mime(require('./types/standard'), require('./types/other')); diff --git a/node_modules/mime/lite.js b/node_modules/mime/lite.js new file mode 100644 index 0000000..835cffb --- /dev/null +++ b/node_modules/mime/lite.js @@ -0,0 +1,4 @@ +'use strict'; + +let Mime = require('./Mime'); +module.exports = new Mime(require('./types/standard')); diff --git a/node_modules/mime/package.json b/node_modules/mime/package.json new file mode 100644 index 0000000..84f5132 --- /dev/null +++ b/node_modules/mime/package.json @@ -0,0 +1,52 @@ +{ + "author": { + "name": "Robert Kieffer", + "url": "http://github.com/broofa", + "email": "robert@broofa.com" + }, + "engines": { + "node": ">=10.0.0" + }, + "bin": { + "mime": "cli.js" + }, + "contributors": [], + "description": "A comprehensive library for mime-type mapping", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "benchmark": "*", + "chalk": "4.1.2", + "eslint": "8.1.0", + "mime-db": "1.50.0", + "mime-score": "1.2.0", + "mime-types": "2.1.33", + "mocha": "9.1.3", + "runmd": "*", + "standard-version": "9.3.2" + }, + "files": [ + "index.js", + "lite.js", + "Mime.js", + "cli.js", + "/types" + ], + "scripts": { + "prepare": "node src/build.js && runmd --output README.md src/README_js.md", + "release": "standard-version", + "benchmark": "node src/benchmark.js", + "md": "runmd --watch --output README.md src/README_js.md", + "test": "mocha src/test.js" + }, + "keywords": [ + "util", + "mime" + ], + "name": "mime", + "repository": { + "url": "https://github.com/broofa/mime", + "type": "git" + }, + "version": "3.0.0" +} diff --git a/node_modules/mime/types/other.js b/node_modules/mime/types/other.js new file mode 100644 index 0000000..bb6a035 --- /dev/null +++ b/node_modules/mime/types/other.js @@ -0,0 +1 @@ +module.exports = {"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"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.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"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.citationstyles.style+xml":["csl"],"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.dbf":["dbf"],"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.mapbox-vector-tile":["mvt"],"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.ac+xml":["*ac"],"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.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"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.rar":["rar"],"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.software602.filler.form+xml":["fo"],"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.syncml.dmddf+xml":["ddf"],"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/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"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":["*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":["*deb","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":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"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":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*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":["*prc","*pdb"],"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"],"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/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*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":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"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.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"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":["*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/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"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/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":["*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"],"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/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/node_modules/mime/types/standard.js b/node_modules/mime/types/standard.js new file mode 100644 index 0000000..5ee9937 --- /dev/null +++ b/node_modules/mime/types/standard.js @@ -0,0 +1 @@ +module.exports = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"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":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"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/lgr+xml":["lgr"],"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/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"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/p2p-overlay+xml":["relo"],"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/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"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/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"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/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"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/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"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/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*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/webm":["webm"]}; \ No newline at end of file diff --git a/node_modules/miniflare/README.md b/node_modules/miniflare/README.md new file mode 100644 index 0000000..821fc25 --- /dev/null +++ b/node_modules/miniflare/README.md @@ -0,0 +1,825 @@ +# 🔥 Miniflare + +**Miniflare 3** is a simulator for developing and testing +[**Cloudflare Workers**](https://workers.cloudflare.com/), powered by +[`workerd`](https://github.com/cloudflare/workerd). + +> :warning: Miniflare 3 is API-only, and does not expose a CLI. Use Wrangler +> with `wrangler dev` to develop your Workers locally with Miniflare 3. + +## Quick Start + +```shell +$ npm install miniflare --save-dev +``` + +```js +import { Miniflare } from "miniflare"; + +// Create a new Miniflare instance, starting a workerd server +const mf = new Miniflare({ + script: `addEventListener("fetch", (event) => { + event.respondWith(new Response("Hello Miniflare!")); + })`, +}); + +// Send a request to the workerd server, the host is ignored +const response = await mf.dispatchFetch("http://localhost:8787/"); +console.log(await response.text()); // Hello Miniflare! + +// Cleanup Miniflare, shutting down the workerd server +await mf.dispose(); +``` + +## API + +### `type Awaitable` + +`T | Promise` + +Represents a value that can be `await`ed. Used in callback types to allow +`Promise`s to be returned if necessary. + +### `type Json` + +`string | number | boolean | null | Record | Json[]` + +Represents a JSON-serialisable value. + +### `type ModuleRuleType` + +`"ESModule" | "CommonJS" | "Text" | "Data" | "CompiledWasm"` + +Represents how a module's contents should be interpreted. + +- `"ESModule"`: interpret as + [ECMAScript module](https://tc39.es/ecma262/#sec-modules) +- `"CommonJS"`: interpret as + [CommonJS module](https://nodejs.org/api/modules.html#modules-commonjs-modules) +- `"Text"`: interpret as UTF8-encoded data, expose in runtime with + `string`-typed `default` export +- `"Data"`: interpret as arbitrary binary data, expose in runtime with + `ArrayBuffer`-typed `default` export +- `"CompiledWasm"`: interpret as binary WebAssembly module data, expose in + runtime with `WebAssembly.Module`-typed `default` export + +### `interface ModuleDefinition` + +Represents a manually defined module. + +- `type: ModuleRuleType` + + How this module's contents should be interpreted. + +- `path: string` + + Path of this module. The module's "name" will be obtained by converting this + to a relative path. The original path will be used to read `contents` if it's + omitted. + +- `contents?: string | Uint8Array` + + Contents override for this module. Binary data should be passed as + `Uint8Array`s. If omitted, will be read from `path`. + +### `interface ModuleRule` + +Represents a rule for identifying the `ModuleRuleType` of automatically located +modules. + +- `type: ModuleRuleType` + + How to interpret modules that match the `include` patterns. + +- `include: string[]` + + Glob patterns to match located module paths against (e.g. `["**/*.txt"]`). + +- `fallthrough?: boolean` + + If `true`, ignore any further rules of this `type`. This is useful for + disabling the built-in `ESModule` and `CommonJS` rules that match `*.mjs` and + `*.js`/`*.cjs` files respectively. + +### `type Persistence` + +`boolean | string | undefined` + +Represents where data should be persisted, if anywhere. + +- If this is `undefined` or `false`, data will be stored in-memory and only + persist between `Miniflare#setOptions()` calls, not restarts nor + `new Miniflare` instances. +- If this is `true`, data will be stored on the file-system, in the `$PWD/.mf` + directory. +- If this looks like a URL, then: + - If the protocol is `memory:`, data will be stored in-memory as above. + - If the protocol is `file:`, data will be stored on the file-system, in the + specified directory (e.g. `file:///path/to/directory`). +- Otherwise, if this is just a regular `string`, data will be stored on the + file-system, using the value as the directory path. + +### `enum LogLevel` + +`NONE, ERROR, WARN, INFO, DEBUG, VERBOSE` + +Controls which messages Miniflare logs. All messages at or below the selected +level will be logged. + +### `interface LogOptions` + +- `prefix?: string` + + String to add before the level prefix when logging messages. Defaults to `mf`. + +- `suffix?: string` + + String to add after the level prefix when logging messages. + +### `class Log` + +- `constructor(level?: LogLevel, opts?: LogOptions)` + + Creates a new logger that logs all messages at or below the specified level to + the `console`. + +- `error(message: Error)` + + Logs a message at the `ERROR` level. If the constructed log `level` is less + than `ERROR`, `throw`s the `message` instead. + +- `warn(message: string)` + + Logs a message at the `WARN` level. + +- `info(message: string)` + + Logs a message at the `INFO` level. + +- `debug(message: string)` + + Logs a message at the `DEBUG` level. + +- `verbose(message: string)` + + Logs a message at the `VERBOSE` level. + +### `class NoOpLog extends Log` + +- `constructor()` + + Creates a new logger that logs nothing to the `console`, and always `throw`s + `message`s logged at the `ERROR` level. + +### `interface QueueProducerOptions` + +- `queueName: string` + + The name of the queue where messages will be sent by the producer. + +- `deliveryDelay?: number` + + Default number of seconds to delay the delivery of messages to consumers. + Value between `0` (no delay) and `42300` (12 hours). + +### `interface QueueConsumerOptions` + +- `maxBatchSize?: number` + + Maximum number of messages allowed in each batch. Defaults to `5`. + +- `maxBatchTimeout?: number` + + Maximum number of seconds to wait for a full batch. If a message is sent, and + this timeout elapses, a partial batch will be dispatched. Defaults to `1`. + +- `maxRetries?: number` + + Maximum number of times to retry dispatching a message, if handling it throws, + or it is explicitly retried. Defaults to `2`. + +- `deadLetterQueue?: string` + + Name of another Queue to send a message on if it fails processing after + `maxRetries`. If this isn't specified, failed messages will be discarded. + +- `retryDelay?: number` + + Number of seconds to delay the (re-)delivery of messages by default. Value + between `0` (no delay) and `42300` (12 hours). + +### `interface WorkerOptions` + +Options for an individual Worker/"nanoservice". All bindings are accessible on +the global scope in service-worker format Workers, or via the 2nd `env` +parameter in module format Workers. + +#### Core + +- `name?: string` + + Unique name for this worker. Only required if multiple `workers` are + specified. + +- `rootPath?: string` + + Path against which all other path options for this Worker are resolved + relative to. This path is itself resolved relative to the `rootPath` from + `SharedOptions` if multiple workers are specified. Defaults to the current + working directory. + +- `script?: string` + + JavaScript code for this worker. If this is a service worker format Worker, it + must not have any imports. If this is a modules format Worker, it must not + have any _npm_ imports, and `modules: true` must be set. If it does have + imports, `scriptPath` must also be set so Miniflare knows where to resolve + them relative to. + +- `scriptPath?: string` + + Path of JavaScript entrypoint. If this is a service worker format Worker, it + must not have any imports. If this is a modules format Worker, it must not + have any _npm_ imports, and `modules: true` must be set. + +- `modules?: boolean | ModuleDefinition[]` + + - If `true`, Miniflare will treat `script`/`scriptPath` as an ES Module and + automatically locate transitive module dependencies according to + `modulesRules`. Note that automatic location is not perfect: if the + specifier to a dynamic `import()` or `require()` is not a string literal, an + exception will be thrown. + + - If set to an array, modules can be defined manually. Transitive dependencies + must also be defined. Note the first module must be the entrypoint and have + type `"ESModule"`. + +- `modulesRoot?: string` + + If `modules` is set to `true` or an array, modules' "name"s will be their + `path`s relative to this value. This ensures file paths in stack traces are + correct. + + + + +- `modulesRules?: ModuleRule[]` + + Rules for identifying the `ModuleRuleType` of automatically located modules + when `modules: true` is set. Note the following default rules are always + included at the end: + + ```js + [ + { type: "ESModule", include: ["**/*.mjs"] }, + { type: "CommonJS", include: ["**/*.js", "**/*.cjs"] }, + ] + ``` + + > If `script` and `scriptPath` are set, and `modules` is set to an array, + > `modules` takes priority for a Worker's code, followed by `script`, then + > `scriptPath`. + + + +- `compatibilityDate?: string` + + [Compatibility date](https://developers.cloudflare.com/workers/platform/compatibility-dates/) + to use for this Worker. Defaults to a date far in the past. + +- `compatibilityFlags?: string[]` + + [Compatibility flags](https://developers.cloudflare.com/workers/platform/compatibility-dates/) + to use for this Worker. + +- `bindings?: Record` + + Record mapping binding name to arbitrary JSON-serialisable values to inject as + bindings into this Worker. + +- `wasmBindings?: Record` + + Record mapping binding name to paths containing binary WebAssembly module data + to inject as `WebAssembly.Module` bindings into this Worker. + +- `textBlobBindings?: Record` + + Record mapping binding name to paths containing UTF8-encoded data to inject as + `string` bindings into this Worker. + +- `dataBlobBindings?: Record` + + Record mapping binding name to paths containing arbitrary binary data to + inject as `ArrayBuffer` bindings into this Worker. + +- `serviceBindings?: Record Awaitable>` + + Record mapping binding name to service designators to inject as + `{ fetch: typeof fetch }` + [service bindings](https://developers.cloudflare.com/workers/platform/bindings/about-service-bindings/) + into this Worker. + + - If the designator is a `string`, requests will be dispatched to the Worker + with that `name`. + - If the designator is `(await import("miniflare")).kCurrentWorker`, requests + will be dispatched to the Worker defining the binding. + - If the designator is an object of the form `{ name: ..., entrypoint: ... }`, + requests will be dispatched to the entrypoint named `entrypoint` in the + Worker named `name`. The `entrypoint` defaults to `default`, meaning + `{ name: "a" }` is the same as `"a"`. If `name` is + `(await import("miniflare")).kCurrentWorker`, requests will be dispatched to + the Worker defining the binding. + - If the designator is an object of the form `{ network: { ... } }`, where + `network` is a + [`workerd` `Network` struct](https://github.com/cloudflare/workerd/blob/bdbd6075c7c53948050c52d22f2dfa37bf376253/src/workerd/server/workerd.capnp#L555-L598), + requests will be dispatched according to the `fetch`ed URL. + - If the designator is an object of the form `{ external: { ... } }` where + `external` is a + [`workerd` `ExternalServer` struct](https://github.com/cloudflare/workerd/blob/bdbd6075c7c53948050c52d22f2dfa37bf376253/src/workerd/server/workerd.capnp#L504-L553), + requests will be dispatched to the specified remote server. + - If the designator is an object of the form `{ disk: { ... } }` where `disk` + is a + [`workerd` `DiskDirectory` struct](https://github.com/cloudflare/workerd/blob/bdbd6075c7c53948050c52d22f2dfa37bf376253/src/workerd/server/workerd.capnp#L600-L643), + requests will be dispatched to an HTTP service backed by an on-disk + directory. + - If the designator is a function, requests will be dispatched to your custom + handler. This allows you to access data and functions defined in Node.js + from your Worker. Note `instance` will be the `Miniflare` instance + dispatching the request. + + + +- `wrappedBindings?: Record }>` + + Record mapping binding name to designators to inject as + [wrapped bindings](https://github.com/cloudflare/workerd/blob/bfcef2d850514c569c039cb84c43bc046af4ffb9/src/workerd/server/workerd.capnp#L469-L487) into this Worker. + Wrapped bindings allow custom bindings to be written as JavaScript functions + accepting an `env` parameter of "inner bindings" and returning the value to + bind. A `string` designator is equivalent to `{ scriptName: }`. + `scriptName`'s bindings will be used as "inner bindings". JSON `bindings` in + the `designator` also become "inner bindings" and will override any of + `scriptName` bindings with the same name. The Worker named `scriptName`... + + - Must define a single `ESModule` as its source, using + `{ modules: true, script: "..." }`, `{ modules: true, scriptPath: "..." }`, + or `{ modules: [...] }` + - Must provide the function to use for the wrapped binding as an `entrypoint` + named export or a default export if `entrypoint` is omitted + - Must not be the first/entrypoint worker + - Must not be bound to with service or Durable Object bindings + - Must not define `compatibilityDate` or `compatibilityFlags` + - Must not define `outboundService` + - Must not directly or indirectly have a wrapped binding to itself + - Must not be used as an argument to `Miniflare#getWorker()` + +
+ Wrapped Bindings Example + + ```ts + import { Miniflare } from "miniflare"; + const store = new Map(); + const mf = new Miniflare({ + workers: [ + { + wrappedBindings: { + MINI_KV: { + scriptName: "mini-kv", // Use Worker named `mini-kv` for implementation + bindings: { NAMESPACE: "ns" }, // Override `NAMESPACE` inner binding + }, + }, + modules: true, + script: `export default { + async fetch(request, env, ctx) { + // Example usage of wrapped binding + await env.MINI_KV.set("key", "value"); + return new Response(await env.MINI_KV.get("key")); + } + }`, + }, + { + name: "mini-kv", + serviceBindings: { + // Function-valued service binding for accessing Node.js state + async STORE(request) { + const { pathname } = new URL(request.url); + const key = pathname.substring(1); + if (request.method === "GET") { + const value = store.get(key); + const status = value === undefined ? 404 : 200; + return new Response(value ?? null, { status }); + } else if (request.method === "PUT") { + const value = await request.text(); + store.set(key, value); + return new Response(null, { status: 204 }); + } else if (request.method === "DELETE") { + store.delete(key); + return new Response(null, { status: 204 }); + } else { + return new Response(null, { status: 405 }); + } + }, + }, + modules: true, + script: ` + // Implementation of binding + class MiniKV { + constructor(env) { + this.STORE = env.STORE; + this.baseURL = "http://x/" + (env.NAMESPACE ?? "") + ":"; + } + async get(key) { + const res = await this.STORE.fetch(this.baseURL + key); + return res.status === 404 ? null : await res.text(); + } + async set(key, body) { + await this.STORE.fetch(this.baseURL + key, { method: "PUT", body }); + } + async delete(key) { + await this.STORE.fetch(this.baseURL + key, { method: "DELETE" }); + } + } + + // env has the type { STORE: Fetcher, NAMESPACE?: string } + export default function (env) { + return new MiniKV(env); + } + `, + }, + ], + }); + ``` + +
+ + > :warning: `wrappedBindings` are only supported in modules format Workers. + + + +- `outboundService?: string | { network: Network } | { external: ExternalServer } | { disk: DiskDirectory } | (request: Request) => Awaitable` + + Dispatch this Worker's global `fetch()` and `connect()` requests to the + configured service. Service designators follow the same rules above for + `serviceBindings`. + +- `fetchMock?: import("undici").MockAgent` + + An [`undici` `MockAgent`](https://undici.nodejs.org/#/docs/api/MockAgent) to + dispatch this Worker's global `fetch()` requests through. + + > :warning: `outboundService` and `fetchMock` are mutually exclusive options. + > At most one of them may be specified per Worker. + +- `routes?: string[]` + + Array of route patterns for this Worker. These follow the same + [routing rules](https://developers.cloudflare.com/workers/platform/triggers/routes/#matching-behavior) + as deployed Workers. If no routes match, Miniflare will fallback to the Worker + defined first. + +#### Cache + +- `cache?: boolean` + + If `false`, default and named caches will be disabled. The Cache API will + still be available, it just won't cache anything. + +- `cacheWarnUsage?: boolean` + + If `true`, the first use of the Cache API will log a warning stating that the + Cache API is unsupported on `workers.dev` subdomains. + +#### Durable Objects + +- `durableObjects?: Record` + + Record mapping binding name to Durable Object class designators to inject as + `DurableObjectNamespace` bindings into this Worker. + + - If the designator is a `string`, it should be the name of a `class` exported + by this Worker. + - If the designator is an object, and `scriptName` is `undefined`, `className` + should be the name of a `class` exported by this Worker. + - Otherwise, `className` should be the name of a `class` exported by the + Worker with a `name` of `scriptName`. + +#### KV + +- `kvNamespaces?: Record | string[]` + + Record mapping binding name to KV namespace IDs to inject as `KVNamespace` + bindings into this Worker. Different Workers may bind to the same namespace ID + with different binding names. If a `string[]` of binding names is specified, + the binding name and KV namespace ID are assumed to be the same. + +- `sitePath?: string` + + Path to serve Workers Sites files from. If set, `__STATIC_CONTENT` and + `__STATIC_CONTENT_MANIFEST` bindings will be injected into this Worker. In + modules mode, `__STATIC_CONTENT_MANIFEST` will also be exposed as a module + with a `string`-typed `default` export, containing the JSON-stringified + manifest. Note Workers Sites files are never cached in Miniflare. + +- `siteInclude?: string[]` + + If set, only files with paths matching these glob patterns will be served. + +- `siteExclude?: string[]` + + If set, only files with paths _not_ matching these glob patterns will be + served. + +#### R2 + +- `r2Buckets?: Record | string[]` + + Record mapping binding name to R2 bucket names to inject as `R2Bucket` + bindings into this Worker. Different Workers may bind to the same bucket name + with different binding names. If a `string[]` of binding names is specified, + the binding name and bucket name are assumed to be the same. + +#### D1 + +- `d1Databases?: Record | string[]` + + Record mapping binding name to D1 database IDs to inject as `D1Database` + bindings into this Worker. Note binding names starting with `__D1_BETA__` are + injected as `Fetcher` bindings instead, and must be wrapped with a facade to + provide the expected `D1Database` API. Different Workers may bind to the same + database ID with different binding names. If a `string[]` of binding names is + specified, the binding name and database ID are assumed to be the same. + +#### Queues + +- `queueProducers?: Record | string[]` + + Record mapping binding name to queue options to inject as `WorkerQueue` bindings + into this Worker. Different Workers may bind to the same queue name with + different binding names. If a `string[]` of binding names is specified, the + binding name and queue name (part of the queue options) are assumed to be the same. + +- `queueConsumers?: Record | string[]` + + Record mapping queue name to consumer options. Messages enqueued on the + corresponding queues will be dispatched to this Worker. Note each queue can + have at most one consumer. If a `string[]` of queue names is specified, + default consumer options will be used. + +#### Analytics Engine, Sending Email, Vectorize and Workers for Platforms + +_Not yet supported_ + +If you need support for these locally, consider using the `wrappedBindings` +option to mock them out. + +#### Browser Rendering and Workers AI + +_Not yet supported_ + +If you need support for these locally, consider using the `serviceBindings` +option to mock them out. + +### `interface SharedOptions` + +Options shared between all Workers/"nanoservices". + +#### Core + +- `rootPath?: string` + + Path against which all other path options for this instance are resolved + relative to. Defaults to the current working directory. + +- `host?: string` + + Hostname that the `workerd` server should listen on. Defaults to `127.0.0.1`. + +- `port?: number` + + Port that the `workerd` server should listen on. Tries to default to `8787`, + but falls back to a random free port if this is in use. Note if a manually + specified port is in use, Miniflare throws an error, rather than attempting to + find a free port. + +- `https?: boolean` + + If `true`, start an HTTPS server using a pre-generated self-signed certificate + for `localhost`. Note this certificate is not valid for any other hostnames or + IP addresses. If you need to access the HTTPS server from another device, + you'll need to generate your own certificate and use the other `https*` + options below. + + ```shell + $ openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out cert.pem + ``` + + ```js + new Miniflare({ + httpsKeyPath: "key.pem", + httpsCertPath: "cert.pem", + }); + ``` + +- `httpsKey?: string` + + When one of `httpsCert` or `httpCertPath` is also specified, starts an HTTPS + server using the value of this option as the PEM encoded private key. + +- `httpsKeyPath?: string` + + When one of `httpsCert` or `httpCertPath` is also specified, starts an HTTPS + server using the PEM encoded private key stored at this file path. + +- `httpsCert?: string` + + When one of `httpsKey` or `httpsKeyPath` is also specified, starts an HTTPS + server using the value of this option as the PEM encoded certificate chain. + +- `httpsCertPath?: string` + + When one of `httpsKey` or `httpsKeyPath` is also specified, starts an HTTPS + server using the PEM encoded certificate chain stored at this file path. + +- `inspectorPort?: number` + + Port that `workerd` should start a DevTools inspector server on. Visit + `chrome://inspect` in a Chromium-based browser to connect to this. This can be + used to see detailed `console.log`s, profile CPU usage, and will eventually + allow step-through debugging. + +- `verbose?: boolean` + + Enable `workerd`'s `--verbose` flag for verbose logging. This can be used to + see simplified `console.log`s. + +- `log?: Log` + + Logger implementation for Miniflare's errors, warnings and informative + messages. + +- `upstream?: string` + + URL to use as the origin for incoming requests. If specified, all incoming + `request.url`s will be rewritten to start with this string. This is especially + useful when testing Workers that act as a proxy, and not as origins + themselves. + +- `cf?: boolean | string | Record` + + Controls the object returned from incoming `Request`'s `cf` property. + + - If set to a falsy value, an object with default placeholder values will be + used + - If set to an object, that object will be used + - If set to `true`, a real `cf` object will be fetched from a trusted + Cloudflare endpoint and cached in `node_modules/.mf` for 30 days + - If set to a `string`, a real `cf` object will be fetched and cached at the + provided path for 30 days + +- `liveReload?: boolean` + + If `true`, Miniflare will inject a script into HTML responses that + automatically reloads the page in-browser whenever the Miniflare instance's + options are updated. + +#### Cache, Durable Objects, KV, R2 and D1 + +- `cachePersist?: Persistence` + + Where to persist data cached in default or named caches. See docs for + `Persistence`. + +- `durableObjectsPersist?: Persistence` + + Where to persist data stored in Durable Objects. See docs for `Persistence`. + +- `kvPersist?: Persistence` + + Where to persist data stored in KV namespaces. See docs for `Persistence`. + +- `r2Persist?: Persistence` + + Where to persist data stored in R2 buckets. See docs for `Persistence`. + +- `d1Persist?: Persistence` + + Where to persist data stored in D1 databases. See docs for `Persistence`. + +#### Analytics Engine, Browser Rendering, Sending Email, Vectorize, Workers AI and Workers for Platforms + +_Not yet supported_ + +### `type MiniflareOptions` + +`SharedOptions & (WorkerOptions | { workers: WorkerOptions[] })` + +Miniflare accepts either a single Worker configuration or multiple Worker +configurations in the `workers` array. When specifying an array of Workers, the +first Worker is designated the entrypoint and will receive all incoming HTTP +requests. Some options are shared between all workers and should always be +defined at the top-level. + +### `class Miniflare` + +- `constructor(opts: MiniflareOptions)` + + Creates a Miniflare instance and starts a new `workerd` server. Note unlike + Miniflare 2, Miniflare 3 _always_ starts a HTTP server listening on the + configured `host` and `port`: there are no `createServer`/`startServer` + functions. + +- `setOptions(opts: MiniflareOptions)` + + Updates the configuration for this Miniflare instance and restarts the + `workerd` server. Note unlike Miniflare 2, this does _not_ merge the new + configuration with the old configuration. Note that calling this function will + invalidate any existing values returned by the `Miniflare#get*()` methods, + preventing them from being used. + +- `ready: Promise` + + Returns a `Promise` that resolves with a `http` `URL` to the `workerd` server + once it has started and is able to accept requests. + +- `dispatchFetch(input: RequestInfo, init?: RequestInit): Promise` + + Sends a HTTP request to the `workerd` server, dispatching a `fetch` event in + the entrypoint Worker. Returns a `Promise` that resolves with the response. + Note that this implicitly waits for the `ready` `Promise` to resolve, there's + no need to do that yourself first. Additionally, the host of the request's URL + is always ignored and replaced with the `workerd` server's. + +- `getBindings = Record>(workerName?: string): Promise` + + Returns a `Promise` that resolves with a record mapping binding names to + bindings, for all bindings in the Worker with the specified `workerName`. If + `workerName` is not specified, defaults to the entrypoint Worker. + +- `getWorker(workerName?: string): Promise` + + Returns a `Promise` that resolves with a + [`Fetcher`](https://workers-types.pages.dev/experimental/#Fetcher) pointing to + the specified `workerName`. If `workerName` is not specified, defaults to the + entrypoint Worker. Note this `Fetcher` uses the experimental + [`service_binding_extra_handlers`](https://github.com/cloudflare/workerd/blob/1d9158af7ca1389474982c76ace9e248320bec77/src/workerd/io/compatibility-date.capnp#L290-L297) + compatibility flag to expose + [`scheduled()`](https://workers-types.pages.dev/experimental/#Fetcher.scheduled) + and [`queue()`](https://workers-types.pages.dev/experimental/#Fetcher.queue) + methods for dispatching `scheduled` and `queue` events. + +- `getCaches(): Promise` + + Returns a `Promise` that resolves with the + [`CacheStorage`](https://developers.cloudflare.com/workers/runtime-apis/cache/) + instance of the entrypoint Worker. This means if `cache: false` is set on the + entrypoint, calling methods on the resolved value won't do anything. + +- `getD1Database(bindingName: string, workerName?: string): Promise` + + Returns a `Promise` that resolves with the + [`D1Database`](https://developers.cloudflare.com/d1/platform/client-api/) + instance corresponding to the specified `bindingName` of `workerName`. Note + `bindingName` must not begin with `__D1_BETA__`. If `workerName` is not + specified, defaults to the entrypoint Worker. + +- `getDurableObjectNamespace(bindingName: string, workerName?: string): Promise` + + Returns a `Promise` that resolves with the + [`DurableObjectNamespace`](https://developers.cloudflare.com/workers/runtime-apis/durable-objects/#access-a-durable-object-from-a-worker) + instance corresponding to the specified `bindingName` of `workerName`. If + `workerName` is not specified, defaults to the entrypoint Worker. + +- `getKVNamespace(bindingName: string, workerName?: string): Promise` + + Returns a `Promise` that resolves with the + [`KVNamespace`](https://developers.cloudflare.com/workers/runtime-apis/kv/) + instance corresponding to the specified `bindingName` of `workerName`. If + `workerName` is not specified, defaults to the entrypoint Worker. + +- `getQueueProducer(bindingName: string, workerName?: string): Promise>` + + Returns a `Promise` that resolves with the + [`Queue`](https://developers.cloudflare.com/queues/platform/javascript-apis/) + producer instance corresponding to the specified `bindingName` of + `workerName`. If `workerName` is not specified, defaults to the entrypoint + Worker. + +- `getR2Bucket(bindingName: string, workerName?: string): Promise` + + Returns a `Promise` that resolves with the + [`R2Bucket`](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/) + producer instance corresponding to the specified `bindingName` of + `workerName`. If `workerName` is not specified, defaults to the entrypoint + Worker. + +- `dispose(): Promise` + + Cleans up the Miniflare instance, and shuts down the `workerd` server. Note + that after this is called, `Miniflare#setOptions()` and + `Miniflare#dispatchFetch()` cannot be called. Additionally, calling this + function will invalidate any values returned by the `Miniflare#get*()` + methods, preventing them from being used. + +- `getCf(): Promise>` + + Returns the same object returned from incoming `Request`'s `cf` property. This + object depends on the `cf` property from `SharedOptions`. diff --git a/node_modules/miniflare/bootstrap.js b/node_modules/miniflare/bootstrap.js new file mode 100755 index 0000000..a5e8826 --- /dev/null +++ b/node_modules/miniflare/bootstrap.js @@ -0,0 +1,11 @@ +#!/usr/bin/env node +const { Log } = require("."); + +const log = new Log(); +log.error( + [ + "`miniflare@3` no longer includes a CLI. Please use `npx wrangler dev` instead.", + "As of `wrangler@3`, this will use Miniflare by default.", + "See https://miniflare.dev/get-started/migrating for more details.", + ].join("\n") +); diff --git a/node_modules/miniflare/dist/src/index.d.ts b/node_modules/miniflare/dist/src/index.d.ts new file mode 100644 index 0000000..79ea991 --- /dev/null +++ b/node_modules/miniflare/dist/src/index.d.ts @@ -0,0 +1,5276 @@ +/// +/// + +import { Abortable } from 'events'; +import type { AbortSignal as AbortSignal_2 } from '@cloudflare/workers-types/experimental'; +import type { Blob as Blob_2 } from '@cloudflare/workers-types/experimental'; +import { Blob as Blob_3 } from 'buffer'; +import { BodyInit } from 'undici'; +import type { CacheStorage } from '@cloudflare/workers-types/experimental'; +import { cspotcodeSourceMapSupport } from '@cspotcode/source-map-support'; +import type { D1Database } from '@cloudflare/workers-types/experimental'; +import { Dispatcher } from 'undici'; +import type { DurableObjectNamespace } from '@cloudflare/workers-types/experimental'; +import type { Fetcher } from '@cloudflare/workers-types/experimental'; +import { File } from 'undici'; +import type { File as File_2 } from '@cloudflare/workers-types/experimental'; +import { FormData } from 'undici'; +import { Headers } from 'undici'; +import type { Headers as Headers_2 } from '@cloudflare/workers-types/experimental'; +import { HeadersInit } from 'undici'; +import http from 'http'; +import { IncomingRequestCfProperties } from '@cloudflare/workers-types/experimental'; +import type { KVNamespace } from '@cloudflare/workers-types/experimental'; +import { MockAgent } from 'undici'; +import NodeWebSocket from 'ws'; +import { ParseParams } from 'zod'; +import type { Queue } from '@cloudflare/workers-types/experimental'; +import type { R2Bucket } from '@cloudflare/workers-types/experimental'; +import { Readable } from 'stream'; +import type { ReadableStream } from '@cloudflare/workers-types/experimental'; +import { ReadableStream as ReadableStream_2 } from 'stream/web'; +import { ReferrerPolicy } from 'undici'; +import { Request as Request_2 } from 'undici'; +import type { Request as Request_3 } from '@cloudflare/workers-types/experimental'; +import { RequestCache } from 'undici'; +import { RequestCredentials } from 'undici'; +import { RequestDestination } from 'undici'; +import { RequestDuplex } from 'undici'; +import { RequestInfo as RequestInfo_2 } from 'undici'; +import { RequestInit as RequestInit_2 } from 'undici'; +import type { RequestInit as RequestInit_3 } from '@cloudflare/workers-types/experimental'; +import type { RequestInitCfProperties } from '@cloudflare/workers-types/experimental'; +import { RequestMode } from 'undici'; +import { RequestRedirect } from 'undici'; +import { Response as Response_2 } from 'undici'; +import type { Response as Response_3 } from '@cloudflare/workers-types/experimental'; +import { ResponseInit as ResponseInit_2 } from 'undici'; +import { ResponseRedirectStatus } from 'undici'; +import { ResponseType } from 'undici'; +import type { ServiceWorkerGlobalScope } from '@cloudflare/workers-types/experimental'; +import { compatibilityDate as supportedCompatibilityDate } from 'workerd'; +import { Transform } from 'stream'; +import { URL as URL_2 } from 'url'; +import { z } from 'zod'; + +export declare type AnyHeaders = http.IncomingHttpHeaders | string[]; + +export declare type Awaitable = T | Promise; + +export declare function base64Decode(encoded: string): string; + +export declare function base64Encode(value: string): string; + +export { BodyInit } + +export declare const CACHE_PLUGIN: Plugin; + +export declare const CACHE_PLUGIN_NAME = "cache"; + +export declare const CacheBindings: { + readonly MAYBE_JSON_CACHE_WARN_USAGE: "MINIFLARE_CACHE_WARN_USAGE"; +}; + +export declare const CacheHeaders: { + readonly NAMESPACE: "cf-cache-namespace"; + readonly STATUS: "cf-cache-status"; +}; + +export declare interface CacheObjectCf { + miniflare?: { + cacheWarnUsage?: boolean; + }; +} + +export declare const CacheOptionsSchema: z.ZodObject<{ + cache: z.ZodOptional; + cacheWarnUsage: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; +}, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; +}>; + +export declare const CacheSharedOptionsSchema: z.ZodObject<{ + cachePersist: z.ZodOptional]>>; +}, "strip", z.ZodTypeAny, { + cachePersist?: string | boolean | undefined; +}, { + cachePersist?: string | boolean | undefined; +}>; + +export declare class CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + constructor(type: "close", init?: { + code?: number; + reason?: string; + wasClean?: boolean; + }); +} + +export declare interface CompiledModuleRule { + type: ModuleRuleType; + include: MatcherRegExps; +} + +export declare function compileModuleRules(rules: ModuleRule[]): CompiledModuleRule[]; + +export declare interface Config { + services?: Service[]; + sockets?: Socket[]; + v8Flags?: string[]; + extensions?: Extension[]; + autogates?: string[]; +} + +export declare const CORE_PLUGIN: Plugin; + +export declare const CORE_PLUGIN_NAME = "core"; + +export declare const CoreBindings: { + readonly SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK"; + readonly SERVICE_USER_ROUTE_PREFIX: "MINIFLARE_USER_ROUTE_"; + readonly SERVICE_USER_FALLBACK: "MINIFLARE_USER_FALLBACK"; + readonly TEXT_CUSTOM_SERVICE: "MINIFLARE_CUSTOM_SERVICE"; + readonly TEXT_UPSTREAM_URL: "MINIFLARE_UPSTREAM_URL"; + readonly JSON_CF_BLOB: "CF_BLOB"; + readonly JSON_ROUTES: "MINIFLARE_ROUTES"; + readonly JSON_LOG_LEVEL: "MINIFLARE_LOG_LEVEL"; + readonly DATA_LIVE_RELOAD_SCRIPT: "MINIFLARE_LIVE_RELOAD_SCRIPT"; + readonly DURABLE_OBJECT_NAMESPACE_PROXY: "MINIFLARE_PROXY"; + readonly DATA_PROXY_SECRET: "MINIFLARE_PROXY_SECRET"; + readonly DATA_PROXY_SHARED_SECRET: "MINIFLARE_PROXY_SHARED_SECRET"; +}; + +export declare const CoreHeaders: { + readonly CUSTOM_SERVICE: "MF-Custom-Service"; + readonly ORIGINAL_URL: "MF-Original-URL"; + readonly PROXY_SHARED_SECRET: "MF-Proxy-Shared-Secret"; + readonly DISABLE_PRETTY_ERROR: "MF-Disable-Pretty-Error"; + readonly ERROR_STACK: "MF-Experimental-Error-Stack"; + readonly ROUTE_OVERRIDE: "MF-Route-Override"; + readonly CF_BLOB: "MF-CF-Blob"; + readonly OP_SECRET: "MF-Op-Secret"; + readonly OP: "MF-Op"; + readonly OP_TARGET: "MF-Op-Target"; + readonly OP_KEY: "MF-Op-Key"; + readonly OP_SYNC: "MF-Op-Sync"; + readonly OP_STRINGIFIED_SIZE: "MF-Op-Stringified-Size"; + readonly OP_RESULT_TYPE: "MF-Op-Result-Type"; +}; + +export declare const CoreOptionsSchema: z.ZodEffects; + path: z.ZodEffects; + contents: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }>, "many">; + modulesRoot: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; +}, { + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; +}>, z.ZodObject<{ + script: z.ZodString; + scriptPath: z.ZodOptional>; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }>, "many">>; + modulesRoot: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +}, { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +}>, z.ZodObject<{ + scriptPath: z.ZodEffects; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }>, "many">>; + modulesRoot: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +}, { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +}>]>, z.ZodObject<{ + name: z.ZodOptional; + rootPath: z.ZodOptional>; + compatibilityDate: z.ZodOptional; + compatibilityFlags: z.ZodOptional>; + routes: z.ZodOptional>; + bindings: z.ZodOptional>>; + wasmBindings: z.ZodOptional>>; + textBlobBindings: z.ZodOptional>>; + dataBlobBindings: z.ZodOptional>>; + serviceBindings: z.ZodOptional, z.ZodObject<{ + name: z.ZodUnion<[z.ZodString, z.ZodLiteral]>; + entrypoint: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name: string | typeof kCurrentWorker; + entrypoint?: string | undefined; + }, { + name: string | typeof kCurrentWorker; + entrypoint?: string | undefined; + }>, z.ZodObject<{ + network: z.ZodObject<{ + allow: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer & (ExternalServer | undefined); + }, { + external: ExternalServer & (ExternalServer | undefined); + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + path: string; + writable?: boolean | undefined; + }, { + path: string; + writable?: boolean | undefined; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }>, z.ZodType<(request: Request, mf: Miniflare) => Awaitable, z.ZodTypeDef, (request: Request, mf: Miniflare) => Awaitable>]>>>; + wrappedBindings: z.ZodOptional; + bindings: z.ZodOptional>>; + }, "strip", z.ZodTypeAny, { + scriptName: string; + entrypoint?: string | undefined; + bindings?: Record | undefined; + }, { + scriptName: string; + entrypoint?: string | undefined; + bindings?: Record | undefined; + }>]>>>; + outboundService: z.ZodOptional, z.ZodObject<{ + name: z.ZodUnion<[z.ZodString, z.ZodLiteral]>; + entrypoint: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name: string | typeof kCurrentWorker; + entrypoint?: string | undefined; + }, { + name: string | typeof kCurrentWorker; + entrypoint?: string | undefined; + }>, z.ZodObject<{ + network: z.ZodObject<{ + allow: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer & (ExternalServer | undefined); + }, { + external: ExternalServer & (ExternalServer | undefined); + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + path: string; + writable?: boolean | undefined; + }, { + path: string; + writable?: boolean | undefined; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }>, z.ZodType<(request: Request, mf: Miniflare) => Awaitable, z.ZodTypeDef, (request: Request, mf: Miniflare) => Awaitable>]>>; + fetchMock: z.ZodOptional, z.ZodTypeDef, MockAgent>>; + unsafeEphemeralDurableObjects: z.ZodOptional; + unsafeDirectSockets: z.ZodOptional; + port: z.ZodOptional; + entrypoint: z.ZodOptional; + proxy: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }, { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }>, "many">>; + unsafeEvalBinding: z.ZodOptional; + unsafeUseModuleFallbackService: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | typeof kCurrentWorker | { + name: string | typeof kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; +}, { + name?: string | undefined; + rootPath?: string | undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | typeof kCurrentWorker | { + name: string | typeof kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; +}>>, ({ + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; +} & { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | typeof kCurrentWorker | { + name: string | typeof kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; +}) | ({ + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +} & { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | typeof kCurrentWorker | { + name: string | typeof kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; +}) | ({ + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +} & { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | typeof kCurrentWorker | { + name: string | typeof kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; +}), ({ + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; +} | { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +} | { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +}) & { + name?: string | undefined; + rootPath?: string | undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | typeof kCurrentWorker | { + name: string | typeof kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; +}>; + +export declare const CoreSharedOptionsSchema: z.ZodObject<{ + rootPath: z.ZodOptional>; + host: z.ZodOptional; + port: z.ZodOptional; + https: z.ZodOptional; + httpsKey: z.ZodOptional; + httpsKeyPath: z.ZodOptional; + httpsCert: z.ZodOptional; + httpsCertPath: z.ZodOptional; + inspectorPort: z.ZodOptional; + verbose: z.ZodOptional; + log: z.ZodOptional>; + handleRuntimeStdio: z.ZodOptional, z.ZodType], null>, z.ZodUnknown>>; + upstream: z.ZodOptional; + cf: z.ZodOptional]>>; + liveReload: z.ZodOptional; + unsafeProxySharedSecret: z.ZodOptional; + unsafeModuleFallbackService: z.ZodOptional, mf: Miniflare) => Awaitable, z.ZodTypeDef, (request: Request, mf: Miniflare) => Awaitable>>; + unsafeStickyBlobs: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + rootPath?: undefined; + host?: string | undefined; + port?: number | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + log?: Log | undefined; + handleRuntimeStdio?: ((args_0: Readable, args_1: Readable) => unknown) | undefined; + upstream?: string | undefined; + cf?: string | boolean | Record | undefined; + liveReload?: boolean | undefined; + unsafeProxySharedSecret?: string | undefined; + unsafeModuleFallbackService?: ((request: Request, mf: Miniflare) => Awaitable) | undefined; + unsafeStickyBlobs?: boolean | undefined; +}, { + rootPath?: string | undefined; + host?: string | undefined; + port?: number | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + log?: Log | undefined; + handleRuntimeStdio?: ((args_0: Readable, args_1: Readable) => unknown) | undefined; + upstream?: string | undefined; + cf?: string | boolean | Record | undefined; + liveReload?: boolean | undefined; + unsafeProxySharedSecret?: string | undefined; + unsafeModuleFallbackService?: ((request: Request, mf: Miniflare) => Awaitable) | undefined; + unsafeStickyBlobs?: boolean | undefined; +}>; + +export declare function coupleWebSocket(ws: NodeWebSocket, pair: WebSocket): Promise; + +export declare function createFetchMock(): MockAgent; + +export declare function createHTTPReducers(impl: PlatformImpl): ReducersRevivers; + +export declare function createHTTPRevivers(impl: PlatformImpl): ReducersRevivers; + +export declare const D1_PLUGIN: Plugin; + +export declare const D1_PLUGIN_NAME = "d1"; + +export declare const D1OptionsSchema: z.ZodObject<{ + d1Databases: z.ZodOptional, z.ZodArray]>>; +}, "strip", z.ZodTypeAny, { + d1Databases?: string[] | Record | undefined; +}, { + d1Databases?: string[] | Record | undefined; +}>; + +export declare const D1SharedOptionsSchema: z.ZodObject<{ + d1Persist: z.ZodOptional]>>; +}, "strip", z.ZodTypeAny, { + d1Persist?: string | boolean | undefined; +}, { + d1Persist?: string | boolean | undefined; +}>; + +export declare function decodeSitesKey(key: string): string; + +export declare const DEFAULT_PERSIST_ROOT = ".mf"; + +export declare class DeferredPromise extends Promise { + readonly resolve: DeferredPromiseResolve; + readonly reject: DeferredPromiseReject; + constructor(executor?: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void); +} + +export declare type DeferredPromiseReject = (reason?: any) => void; + +export declare type DeferredPromiseResolve = (value: T | PromiseLike) => void; + +export declare function deserialiseRegExps(matcher: SerialisableMatcherRegExps): MatcherRegExps; + +export declare function deserialiseSiteRegExps(siteRegExps: SerialisableSiteMatcherRegExps): SiteMatcherRegExps; + +export declare interface DiskDirectory { + path?: string; + writable?: boolean; +} + +export declare type DispatchFetch = (input: RequestInfo, init?: RequestInit>) => Promise; + +/** + * Dispatcher created for each `dispatchFetch()` call. Ensures request origin + * in Worker matches that passed to `dispatchFetch()`, not the address the + * `workerd` server is listening on. Handles cases where `fetch()` redirects to + * same origin and different external origins. + */ +export declare class DispatchFetchDispatcher extends Dispatcher { + private readonly globalDispatcher; + private readonly runtimeDispatcher; + private readonly actualRuntimeOrigin; + private readonly userRuntimeOrigin; + private readonly cfBlobJson?; + /** + * @param globalDispatcher Dispatcher to use for all non-runtime requests + * (rejects unauthorised certificates) + * @param runtimeDispatcher Dispatcher to use for runtime requests + * (permits unauthorised certificates) + * @param actualRuntimeOrigin Origin to send all runtime requests to + * @param userRuntimeOrigin Origin to treat as runtime request + * (initial URL passed by user to `dispatchFetch()`) + * @param cfBlob `request.cf` blob override for runtime requests + */ + constructor(globalDispatcher: Dispatcher, runtimeDispatcher: Dispatcher, actualRuntimeOrigin: string, userRuntimeOrigin: string, cfBlob?: IncomingRequestCfProperties); + addHeaders(headers: AnyHeaders, path: string): void; + dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + close(): Promise; + close(callback: () => void): void; + destroy(): Promise; + destroy(err: Error | null): Promise; + destroy(callback: () => void): void; + destroy(err: Error | null, callback: () => void): void; + get isMockActive(): boolean; +} + +export declare const DURABLE_OBJECTS_PLUGIN: Plugin; + +export declare const DURABLE_OBJECTS_PLUGIN_NAME = "do"; + +export declare const DURABLE_OBJECTS_STORAGE_SERVICE_NAME = "do:storage"; + +export declare type DurableObjectClassNames = Map>; + +export declare const DurableObjectsOptionsSchema: z.ZodObject<{ + durableObjects: z.ZodOptional; + unsafeUniqueKey: z.ZodOptional]>>; + unsafePreventEviction: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + className: string; + scriptName?: string | undefined; + unsafeUniqueKey?: string | typeof kUnsafeEphemeralUniqueKey | undefined; + unsafePreventEviction?: boolean | undefined; + }, { + className: string; + scriptName?: string | undefined; + unsafeUniqueKey?: string | typeof kUnsafeEphemeralUniqueKey | undefined; + unsafePreventEviction?: boolean | undefined; + }>]>>>; +}, "strip", z.ZodTypeAny, { + durableObjects?: Record | undefined; +}, { + durableObjects?: Record | undefined; +}>; + +export declare const DurableObjectsSharedOptionsSchema: z.ZodObject<{ + durableObjectsPersist: z.ZodOptional]>>; +}, "strip", z.ZodTypeAny, { + durableObjectsPersist?: string | boolean | undefined; +}, { + durableObjectsPersist?: string | boolean | undefined; +}>; + +/* Excluded from this release type: _enableControlEndpoints */ + +export declare function encodeSitesKey(key: string): string; + +export declare const ENTRY_SOCKET_HTTP_OPTIONS: HttpOptions; + +export declare class ErrorEvent extends Event { + readonly error: Error | null; + constructor(type: "error", init?: { + error?: Error; + }); +} + +export declare interface Extension { + modules?: Extension_Module[]; +} + +export declare interface Extension_Module { + name?: string; + internal?: boolean; + esModule?: string; +} + +export declare type ExternalServer = { + address?: string; +} & ({ + http: HttpOptions; +} | { + https: ExternalServer_Https; +} | { + tcp: ExternalServer_Tcp; +}); + +export declare interface ExternalServer_Https { + options?: HttpOptions; + tlsOptions?: TlsOptions; + certificateHost?: string; +} + +export declare interface ExternalServer_Tcp { + tlsOptions?: TlsOptions; + certificateHost?: string; +} + +export declare function fetch(input: RequestInfo, init?: RequestInit | Request): Promise; + +export { File } + +export declare function _forceColour(enabled?: boolean): void; + +export declare function formatZodError(error: z.ZodError, input: unknown): string; + +export { FormData } + +export declare function getAccessibleHosts(ipv4Only?: boolean): string[]; + +export declare function getCacheServiceName(workerIndex: number): string; + +export declare function getDirectSocketName(workerIndex: number, entrypoint: string): string; + +export declare function getEntrySocketHttpOptions(coreOpts: z.infer): Promise<{ + http: HttpOptions; +} | { + https: Socket_Https; +}>; + +export declare function getFreshSourceMapSupport(): cspotcodeSourceMapSupport; + +export declare function getGlobalServices({ sharedOptions, allWorkerRoutes, fallbackWorkerName, loopbackPort, log, proxyBindings, }: GlobalServicesOptions): Service[]; + +export declare function getMiniflareObjectBindings(unsafeStickyBlobs: boolean): Worker_Binding[]; + +export declare function getPersistPath(pluginName: string, tmpPath: string, persist: Persistence): string; + +export declare function getRootPath(opts: unknown): string; + +export declare interface GlobalServicesOptions { + sharedOptions: z.infer; + allWorkerRoutes: Map; + fallbackWorkerName: string | undefined; + loopbackPort: number; + log: Log; + proxyBindings: Worker_Binding[]; +} + +export declare function globsToRegExps(globs?: string[]): MatcherRegExps; + +export { Headers } + +export { HeadersInit } + +export declare const HOST_CAPNP_CONNECT = "miniflare-unsafe-internal-capnp-connect"; + +export declare interface HttpOptions { + style?: HttpOptions_Style; + forwardedProtoHeader?: string; + cfBlobHeader?: string; + injectRequestHeaders?: HttpOptions_Header[]; + injectResponseHeaders?: HttpOptions_Header[]; + capnpConnectHost?: string; +} + +export declare interface HttpOptions_Header { + name?: string; + value?: string; +} + +export declare enum HttpOptions_Style { + HOST = 0, + PROXY = 1 +} + +export declare const HYPERDRIVE_PLUGIN: Plugin; + +export declare const HYPERDRIVE_PLUGIN_NAME = "hyperdrive"; + +export declare const HyperdriveInputOptionsSchema: z.ZodObject<{ + hyperdrives: z.ZodOptional]>, URL_2, string | URL_2>>>; +}, "strip", z.ZodTypeAny, { + hyperdrives?: Record | undefined; +}, { + hyperdrives?: Record | undefined; +}>; + +export declare const HyperdriveSchema: z.ZodEffects]>, URL_2, string | URL_2>; + +export declare interface InclusiveRange { + start: number; + end: number; +} + +/* Excluded from this release type: _initialiseInstanceRegistry */ + +/* Excluded from this release type: _isCyclic */ + +export declare function isFetcherFetch(targetName: string, key: string): boolean; + +export declare function isR2ObjectWriteHttpMetadata(targetName: string, key: string): boolean; + +export declare function isSitesRequest(request: { + url: string; +}): boolean; + +export declare type Json = Literal | { + [key: string]: Json; +} | Json[]; + +export declare interface JsonError { + message?: string; + name?: string; + stack?: string; + cause?: JsonError; +} + +export declare const JsonSchema: z.ZodType; + +declare const kAccepted: unique symbol; + +declare const kCf: unique symbol; + +declare const kClose: unique symbol; + +declare const kClosedIncoming: unique symbol; + +declare const kClosedOutgoing: unique symbol; + +declare const kCoupled: unique symbol; + +export declare const kCurrentWorker: unique symbol; + +declare const kError: unique symbol; + +export declare const kInspectorSocket: unique symbol; + +declare const kPair: unique symbol; + +export declare const kProxyNodeBinding: unique symbol; + +declare const kSend: unique symbol; + +export declare const kUnsafeEphemeralUniqueKey: unique symbol; + +export declare const KV_PLUGIN: Plugin; + +export declare const KV_PLUGIN_NAME = "kv"; + +export declare const KVHeaders: { + readonly EXPIRATION: "CF-Expiration"; + readonly METADATA: "CF-KV-Metadata"; +}; + +export declare const KVLimits: { + readonly MIN_CACHE_TTL: 60; + readonly MAX_LIST_KEYS: 1000; + readonly MAX_KEY_SIZE: 512; + readonly MAX_VALUE_SIZE: number; + readonly MAX_VALUE_SIZE_TEST: 1024; + readonly MAX_METADATA_SIZE: 1024; +}; + +export declare const kVoid: unique symbol; + +export declare const KVOptionsSchema: z.ZodObject<{ + kvNamespaces: z.ZodOptional, z.ZodArray]>>; + sitePath: z.ZodOptional>; + siteInclude: z.ZodOptional>; + siteExclude: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; +}, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; +}>; + +export declare const KVParams: { + readonly URL_ENCODED: "urlencoded"; + readonly CACHE_TTL: "cache_ttl"; + readonly EXPIRATION: "expiration"; + readonly EXPIRATION_TTL: "expiration_ttl"; + readonly LIST_LIMIT: "key_count_limit"; + readonly LIST_PREFIX: "prefix"; + readonly LIST_CURSOR: "cursor"; +}; + +export declare const KVSharedOptionsSchema: z.ZodObject<{ + kvPersist: z.ZodOptional]>>; +}, "strip", z.ZodTypeAny, { + kvPersist?: string | boolean | undefined; +}, { + kvPersist?: string | boolean | undefined; +}>; + +declare const kWebSocket: unique symbol; + +export declare type Literal = z.infer; + +export declare const LiteralSchema: z.ZodUnion<[z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>; + +export declare class Log { + #private; + readonly level: LogLevel; + constructor(level?: LogLevel, opts?: LogOptions); + protected log(message: string): void; + logWithLevel(level: LogLevel, message: string): void; + error(message: Error): void; + warn(message: string): void; + info(message: string): void; + debug(message: string): void; + verbose(message: string): void; +} + +export declare enum LogLevel { + NONE = 0, + ERROR = 1, + WARN = 2, + INFO = 3, + DEBUG = 4, + VERBOSE = 5 +} + +export declare interface LogOptions { + prefix?: string; + suffix?: string; +} + +export declare interface MatcherRegExps { + include: RegExp[]; + exclude: RegExp[]; +} + +export declare function matchRoutes(routes: WorkerRoute[], url: URL): string | null; + +export declare function maybeApply(f: (value: From) => To, maybeValue: From | undefined): To | undefined; + +export declare function maybeParseURL(url: Persistence): URL | undefined; + +/** + * Merges all of `b`'s properties into `a`. Only merges 1 level deep, i.e. + * `kvNamespaces` will be fully-merged, but `durableObject` object-designators + * will be overwritten. + */ +export declare function mergeWorkerOptions(a: Partial, b: Partial): Partial; + +export declare class MessageEvent extends Event { + readonly data: ArrayBuffer | string; + constructor(type: "message", init: { + data: ArrayBuffer | string; + }); +} + +export declare function migrateDatabase(log: Log, uniqueKey: string, persistPath: string, namespace: string): Promise; + +export declare class Miniflare { + #private; + constructor(opts: MiniflareOptions); + get ready(): Promise; + getCf(): Promise>; + getInspectorURL(): Promise; + unsafeGetDirectURL(workerName?: string, entrypoint?: string): Promise; + setOptions(opts: MiniflareOptions): Promise; + dispatchFetch: DispatchFetch; + /* Excluded from this release type: _getProxyClient */ + getBindings>(workerName?: string): Promise; + getWorker(workerName?: string): Promise>; + getCaches(): Promise>; + getD1Database(bindingName: string, workerName?: string): Promise; + getDurableObjectNamespace(bindingName: string, workerName?: string): Promise>; + getKVNamespace(bindingName: string, workerName?: string): Promise>; + getQueueProducer(bindingName: string, workerName?: string): Promise>; + getR2Bucket(bindingName: string, workerName?: string): Promise>; + /* Excluded from this release type: _getInternalDurableObjectNamespace */ + unsafeGetPersistPaths(): Map; + dispose(): Promise; +} + +export declare class MiniflareCoreError extends MiniflareError { +} + +export declare type MiniflareCoreErrorCode = "ERR_RUNTIME_FAILURE" | "ERR_DISPOSED" | "ERR_MODULE_PARSE" | "ERR_MODULE_STRING_SCRIPT" | "ERR_MODULE_DYNAMIC_SPEC" | "ERR_MODULE_RULE" | "ERR_PERSIST_UNSUPPORTED" | "ERR_PERSIST_REMOTE_UNAUTHENTICATED" | "ERR_PERSIST_REMOTE_UNSUPPORTED" | "ERR_FUTURE_COMPATIBILITY_DATE" | "ERR_NO_WORKERS" | "ERR_VALIDATION" | "ERR_DUPLICATE_NAME" | "ERR_DIFFERENT_UNIQUE_KEYS" | "ERR_DIFFERENT_PREVENT_EVICTION" | "ERR_MULTIPLE_OUTBOUNDS" | "ERR_INVALID_WRAPPED" | "ERR_CYCLIC"; + +export declare class MiniflareError extends Error { + readonly code: Code; + readonly cause?: Error | undefined; + constructor(code: Code, message?: string, cause?: Error | undefined); +} + +export declare type MiniflareOptions = SharedOptions & (WorkerOptions | { + workers: WorkerOptions[]; +}); + +export declare type ModuleDefinition = z.infer; + +export declare const ModuleDefinitionSchema: z.ZodObject<{ + type: z.ZodEnum<["ESModule", "CommonJS", "NodeJsCompatModule", "Text", "Data", "CompiledWasm", "PythonModule", "PythonRequirement"]>; + path: z.ZodEffects; + contents: z.ZodOptional]>>; +}, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; +}, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; +}>; + +export declare type ModuleRule = z.infer; + +export declare const ModuleRuleSchema: z.ZodObject<{ + type: z.ZodEnum<["ESModule", "CommonJS", "NodeJsCompatModule", "Text", "Data", "CompiledWasm", "PythonModule", "PythonRequirement"]>; + include: z.ZodArray; + fallthrough: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; +}, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; +}>; + +export declare type ModuleRuleType = z.infer; + +export declare const ModuleRuleTypeSchema: z.ZodEnum<["ESModule", "CommonJS", "NodeJsCompatModule", "Text", "Data", "CompiledWasm", "PythonModule", "PythonRequirement"]>; + +export declare class Mutex { + private locked; + private resolveQueue; + private drainQueue; + private lock; + private unlock; + get hasWaiting(): boolean; + runWith(closure: () => Awaitable): Promise; + drained(): Promise; +} + +export declare function namespaceEntries(namespaces?: Record | string[]): [bindingName: string, id: string][]; + +export declare function namespaceKeys(namespaces?: Record | string[]): string[]; + +export declare interface Network { + allow?: string[]; + deny?: string[]; + tlsOptions?: TlsOptions; +} + +export declare const NODE_PLATFORM_IMPL: PlatformImpl; + +export declare class NoOpLog extends Log { + constructor(); + protected log(): void; + error(_message: Error): void; +} + +export declare function normaliseDurableObject(designator: NonNullable["durableObjects"]>[string]): { + className: string; + serviceName?: string; + unsafeUniqueKey?: UnsafeUniqueKey; + unsafePreventEviction?: boolean; +}; + +export declare function objectEntryWorker(durableObjectNamespace: Worker_Binding_DurableObjectNamespaceDesignator, namespace: string): Worker; + +export declare type OptionalZodTypeOf = T extends z.ZodTypeAny ? z.TypeOf : undefined; + +export declare type OverloadReplaceWorkersTypes = T extends (...args: any[]) => any ? UnionToIntersection>> : ReplaceWorkersTypes; + +export declare type OverloadUnion any> = Parameters extends [] ? T : OverloadUnion9; + +export declare type OverloadUnion2 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) : T; + +export declare type OverloadUnion3 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) : OverloadUnion2; + +export declare type OverloadUnion4 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) : OverloadUnion3; + +export declare type OverloadUnion5 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; + (...args: infer P5): infer R5; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) | ((...args: P5) => R5) : OverloadUnion4; + +export declare type OverloadUnion6 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; + (...args: infer P5): infer R5; + (...args: infer P6): infer R6; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) | ((...args: P5) => R5) | ((...args: P6) => R6) : OverloadUnion5; + +export declare type OverloadUnion7 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; + (...args: infer P5): infer R5; + (...args: infer P6): infer R6; + (...args: infer P7): infer R7; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) | ((...args: P5) => R5) | ((...args: P6) => R6) | ((...args: P7) => R7) : OverloadUnion6; + +export declare type OverloadUnion8 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; + (...args: infer P5): infer R5; + (...args: infer P6): infer R6; + (...args: infer P7): infer R7; + (...args: infer P8): infer R8; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) | ((...args: P5) => R5) | ((...args: P6) => R6) | ((...args: P7) => R7) | ((...args: P8) => R8) : OverloadUnion7; + +export declare type OverloadUnion9 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; + (...args: infer P5): infer R5; + (...args: infer P6): infer R6; + (...args: infer P7): infer R7; + (...args: infer P8): infer R8; + (...args: infer P9): infer R9; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) | ((...args: P5) => R5) | ((...args: P6) => R6) | ((...args: P7) => R7) | ((...args: P8) => R8) | ((...args: P9) => R9) : OverloadUnion8; + +/** + * Parses an HTTP `Range` header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range), + * returning either: + * - `undefined` indicating the range is unsatisfiable + * - An empty array indicating the entire response should be returned + * - A non-empty array of inclusive ranges of the response to return + */ +export declare function parseRanges(rangeHeader: string, length: number): InclusiveRange[] | undefined; + +export declare function parseRoutes(allRoutes: Map): WorkerRoute[]; + +export declare function parseWithReadableStreams(impl: PlatformImpl, stringified: StringifiedWithStream, revivers: ReducersRevivers): unknown; + +export declare function parseWithRootPath(newRootPath: string, schema: Z, data: unknown, params?: Partial): z.infer; + +export declare const PathSchema: z.ZodEffects; + +export declare enum PeriodType { + TENSECONDS = 10, + MINUTE = 60 +} + +export declare type Persistence = z.infer; + +export declare const PersistenceSchema: z.ZodOptional]>>; + +export declare interface PlatformImpl { + Blob: typeof Blob_2; + File: typeof File_2; + Headers: typeof Headers_2; + Request: typeof Request_3; + Response: typeof Response_3; + isReadableStream(value: unknown): value is RS; + bufferReadableStream(stream: RS): Promise; + unbufferReadableStream(buffer: ArrayBuffer): RS; +} + +export declare type Plugin = PluginBase & (SharedOptions extends undefined ? { + sharedOptions?: undefined; +} : { + sharedOptions: SharedOptions; +}); + +export declare const PLUGIN_ENTRIES: ["cache" | "core" | "do" | "d1" | "kv" | "queues" | "r2" | "hyperdrive" | "ratelimit", ValueOf<{ + core: Plugin; + path: z.ZodEffects; + contents: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }>, "many">; + modulesRoot: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; + }, { + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; + }>, z.ZodObject<{ + script: z.ZodString; + scriptPath: z.ZodOptional>; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }>, "many">>; + modulesRoot: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + }, { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + }>, z.ZodObject<{ + scriptPath: z.ZodEffects; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }>, "many">>; + modulesRoot: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + }, { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + }>]>, z.ZodObject<{ + name: z.ZodOptional; + rootPath: z.ZodOptional>; + compatibilityDate: z.ZodOptional; + compatibilityFlags: z.ZodOptional>; + routes: z.ZodOptional>; + bindings: z.ZodOptional>>; + wasmBindings: z.ZodOptional>>; + textBlobBindings: z.ZodOptional>>; + dataBlobBindings: z.ZodOptional>>; + serviceBindings: z.ZodOptional, z.ZodObject<{ + name: z.ZodUnion<[z.ZodString, z.ZodLiteral]>; + entrypoint: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + }, { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + }>, z.ZodObject<{ + network: z.ZodObject<{ + allow: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer & (ExternalServer | undefined); + }, { + external: ExternalServer & (ExternalServer | undefined); + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + path: string; + writable?: boolean | undefined; + }, { + path: string; + writable?: boolean | undefined; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }>, z.ZodType<(request: Request, mf: Miniflare) => Awaitable, z.ZodTypeDef, (request: Request, mf: Miniflare) => Awaitable>]>>>; + wrappedBindings: z.ZodOptional; + bindings: z.ZodOptional>>; + }, "strip", z.ZodTypeAny, { + scriptName: string; + entrypoint?: string | undefined; + bindings?: Record | undefined; + }, { + scriptName: string; + entrypoint?: string | undefined; + bindings?: Record | undefined; + }>]>>>; + outboundService: z.ZodOptional, z.ZodObject<{ + name: z.ZodUnion<[z.ZodString, z.ZodLiteral]>; + entrypoint: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + }, { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + }>, z.ZodObject<{ + network: z.ZodObject<{ + allow: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer & (ExternalServer | undefined); + }, { + external: ExternalServer & (ExternalServer | undefined); + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + path: string; + writable?: boolean | undefined; + }, { + path: string; + writable?: boolean | undefined; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }>, z.ZodType<(request: Request, mf: Miniflare) => Awaitable, z.ZodTypeDef, (request: Request, mf: Miniflare) => Awaitable>]>>; + fetchMock: z.ZodOptional, z.ZodTypeDef, MockAgent>>; + unsafeEphemeralDurableObjects: z.ZodOptional; + unsafeDirectSockets: z.ZodOptional; + port: z.ZodOptional; + entrypoint: z.ZodOptional; + proxy: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }, { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }>, "many">>; + unsafeEvalBinding: z.ZodOptional; + unsafeUseModuleFallbackService: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }, { + name?: string | undefined; + rootPath?: string | undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }>>, ({ + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; + } & { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }) | ({ + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + } & { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }) | ({ + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + } & { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }), ({ + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; + } | { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + } | { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + }) & { + name?: string | undefined; + rootPath?: string | undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }>, z.ZodObject<{ + rootPath: z.ZodOptional>; + host: z.ZodOptional; + port: z.ZodOptional; + https: z.ZodOptional; + httpsKey: z.ZodOptional; + httpsKeyPath: z.ZodOptional; + httpsCert: z.ZodOptional; + httpsCertPath: z.ZodOptional; + inspectorPort: z.ZodOptional; + verbose: z.ZodOptional; + log: z.ZodOptional>; + handleRuntimeStdio: z.ZodOptional, z.ZodType], null>, z.ZodUnknown>>; + upstream: z.ZodOptional; + cf: z.ZodOptional]>>; + liveReload: z.ZodOptional; + unsafeProxySharedSecret: z.ZodOptional; + unsafeModuleFallbackService: z.ZodOptional, mf: Miniflare) => Awaitable, z.ZodTypeDef, (request: Request, mf: Miniflare) => Awaitable>>; + unsafeStickyBlobs: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + rootPath?: undefined; + host?: string | undefined; + port?: number | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + log?: Log | undefined; + handleRuntimeStdio?: ((args_0: Readable, args_1: Readable) => unknown) | undefined; + upstream?: string | undefined; + cf?: string | boolean | Record | undefined; + liveReload?: boolean | undefined; + unsafeProxySharedSecret?: string | undefined; + unsafeModuleFallbackService?: ((request: Request, mf: Miniflare) => Awaitable) | undefined; + unsafeStickyBlobs?: boolean | undefined; + }, { + rootPath?: string | undefined; + host?: string | undefined; + port?: number | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + log?: Log | undefined; + handleRuntimeStdio?: ((args_0: Readable, args_1: Readable) => unknown) | undefined; + upstream?: string | undefined; + cf?: string | boolean | Record | undefined; + liveReload?: boolean | undefined; + unsafeProxySharedSecret?: string | undefined; + unsafeModuleFallbackService?: ((request: Request, mf: Miniflare) => Awaitable) | undefined; + unsafeStickyBlobs?: boolean | undefined; + }>>; + cache: Plugin; + cacheWarnUsage: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; + }, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; + }>, z.ZodObject<{ + cachePersist: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + cachePersist?: string | boolean | undefined; + }, { + cachePersist?: string | boolean | undefined; + }>>; + d1: Plugin, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + d1Databases?: string[] | Record | undefined; + }, { + d1Databases?: string[] | Record | undefined; + }>, z.ZodObject<{ + d1Persist: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + d1Persist?: string | boolean | undefined; + }, { + d1Persist?: string | boolean | undefined; + }>>; + do: Plugin; + unsafeUniqueKey: z.ZodOptional]>>; + unsafePreventEviction: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + className: string; + scriptName?: string | undefined; + unsafeUniqueKey?: string | kUnsafeEphemeralUniqueKey | undefined; + unsafePreventEviction?: boolean | undefined; + }, { + className: string; + scriptName?: string | undefined; + unsafeUniqueKey?: string | kUnsafeEphemeralUniqueKey | undefined; + unsafePreventEviction?: boolean | undefined; + }>]>>>; + }, "strip", z.ZodTypeAny, { + durableObjects?: Record | undefined; + }, { + durableObjects?: Record | undefined; + }>, z.ZodObject<{ + durableObjectsPersist: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + durableObjectsPersist?: string | boolean | undefined; + }, { + durableObjectsPersist?: string | boolean | undefined; + }>>; + kv: Plugin, z.ZodArray]>>; + sitePath: z.ZodOptional>; + siteInclude: z.ZodOptional>; + siteExclude: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; + }, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; + }>, z.ZodObject<{ + kvPersist: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + kvPersist?: string | boolean | undefined; + }, { + kvPersist?: string | boolean | undefined; + }>>; + queues: Plugin; + }, "strip", z.ZodTypeAny, { + queueName: string; + deliveryDelay?: number | undefined; + }, { + queueName: string; + deliveryDelay?: number | undefined; + }>>, z.ZodArray, z.ZodRecord]>>; + queueConsumers: z.ZodOptional; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; + retryDelay: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; + }, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; + }>>, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + queueProducers?: string[] | Record | Record | undefined; + queueConsumers?: string[] | Record | undefined; + }, { + queueProducers?: string[] | Record | Record | undefined; + queueConsumers?: string[] | Record | undefined; + }>>; + r2: Plugin, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + r2Buckets?: string[] | Record | undefined; + }, { + r2Buckets?: string[] | Record | undefined; + }>, z.ZodObject<{ + r2Persist: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + r2Persist?: string | boolean | undefined; + }, { + r2Persist?: string | boolean | undefined; + }>>; + hyperdrive: Plugin]>, URL_2, string | URL_2>>>; + }, "strip", z.ZodTypeAny, { + hyperdrives?: Record | undefined; + }, { + hyperdrives?: Record | undefined; + }>>; + ratelimit: Plugin>; + }, "strip", z.ZodTypeAny, { + limit: number; + period?: PeriodType | undefined; + }, { + limit: number; + period?: PeriodType | undefined; + }>; + }, "strip", z.ZodTypeAny, { + simple: { + limit: number; + period?: PeriodType | undefined; + }; + }, { + simple: { + limit: number; + period?: PeriodType | undefined; + }; + }>>>; + }, "strip", z.ZodTypeAny, { + ratelimits?: Record | undefined; + }, { + ratelimits?: Record | undefined; + }>>; +}>][]; + +export declare interface PluginBase { + options: Options; + getBindings(options: z.infer, workerIndex: number): Awaitable; + getNodeBindings(options: z.infer): Awaitable>; + getServices(options: PluginServicesOptions): Awaitable; + getPersistPath?(sharedOptions: OptionalZodTypeOf, tmpPath: string): string; +} + +export declare const PLUGINS: { + core: Plugin; + path: z.ZodEffects; + contents: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }>, "many">; + modulesRoot: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; + }, { + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; + }>, z.ZodObject<{ + script: z.ZodString; + scriptPath: z.ZodOptional>; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }>, "many">>; + modulesRoot: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + }, { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + }>, z.ZodObject<{ + scriptPath: z.ZodEffects; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }>, "many">>; + modulesRoot: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + }, { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + }>]>, z.ZodObject<{ + name: z.ZodOptional; + rootPath: z.ZodOptional>; + compatibilityDate: z.ZodOptional; + compatibilityFlags: z.ZodOptional>; + routes: z.ZodOptional>; + bindings: z.ZodOptional>>; + wasmBindings: z.ZodOptional>>; + textBlobBindings: z.ZodOptional>>; + dataBlobBindings: z.ZodOptional>>; + serviceBindings: z.ZodOptional, z.ZodObject<{ + name: z.ZodUnion<[z.ZodString, z.ZodLiteral]>; + entrypoint: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + }, { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + }>, z.ZodObject<{ + network: z.ZodObject<{ + allow: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer & (ExternalServer | undefined); + }, { + external: ExternalServer & (ExternalServer | undefined); + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + path: string; + writable?: boolean | undefined; + }, { + path: string; + writable?: boolean | undefined; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }>, z.ZodType<(request: Request, mf: Miniflare) => Awaitable, z.ZodTypeDef, (request: Request, mf: Miniflare) => Awaitable>]>>>; + wrappedBindings: z.ZodOptional; + bindings: z.ZodOptional>>; + }, "strip", z.ZodTypeAny, { + scriptName: string; + entrypoint?: string | undefined; + bindings?: Record | undefined; + }, { + scriptName: string; + entrypoint?: string | undefined; + bindings?: Record | undefined; + }>]>>>; + outboundService: z.ZodOptional, z.ZodObject<{ + name: z.ZodUnion<[z.ZodString, z.ZodLiteral]>; + entrypoint: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + }, { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + }>, z.ZodObject<{ + network: z.ZodObject<{ + allow: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }, { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer & (ExternalServer | undefined); + }, { + external: ExternalServer & (ExternalServer | undefined); + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + path: string; + writable?: boolean | undefined; + }, { + path: string; + writable?: boolean | undefined; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }, { + disk: { + path: string; + writable?: boolean | undefined; + }; + }>, z.ZodType<(request: Request, mf: Miniflare) => Awaitable, z.ZodTypeDef, (request: Request, mf: Miniflare) => Awaitable>]>>; + fetchMock: z.ZodOptional, z.ZodTypeDef, MockAgent>>; + unsafeEphemeralDurableObjects: z.ZodOptional; + unsafeDirectSockets: z.ZodOptional; + port: z.ZodOptional; + entrypoint: z.ZodOptional; + proxy: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }, { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }>, "many">>; + unsafeEvalBinding: z.ZodOptional; + unsafeUseModuleFallbackService: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }, { + name?: string | undefined; + rootPath?: string | undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }>>, ({ + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; + } & { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }) | ({ + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + } & { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }) | ({ + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + } & { + name?: string | undefined; + rootPath?: undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }), ({ + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; + } | { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + } | { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; + }) & { + name?: string | undefined; + rootPath?: string | undefined; + compatibilityDate?: string | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + bindings?: Record | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, mf: Miniflare) => Awaitable)> | undefined; + wrappedBindings?: Record | undefined; + }> | undefined; + outboundService?: string | kCurrentWorker | { + name: string | kCurrentWorker; + entrypoint?: string | undefined; + } | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + minVersion?: TlsOptions_Version | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer & (ExternalServer | undefined); + } | { + disk: { + path: string; + writable?: boolean | undefined; + }; + } | ((request: Request, mf: Miniflare) => Awaitable) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + unsafeDirectSockets?: { + host?: string | undefined; + port?: number | undefined; + entrypoint?: string | undefined; + proxy?: boolean | undefined; + }[] | undefined; + unsafeEvalBinding?: string | undefined; + unsafeUseModuleFallbackService?: boolean | undefined; + }>, z.ZodObject<{ + rootPath: z.ZodOptional>; + host: z.ZodOptional; + port: z.ZodOptional; + https: z.ZodOptional; + httpsKey: z.ZodOptional; + httpsKeyPath: z.ZodOptional; + httpsCert: z.ZodOptional; + httpsCertPath: z.ZodOptional; + inspectorPort: z.ZodOptional; + verbose: z.ZodOptional; + log: z.ZodOptional>; + handleRuntimeStdio: z.ZodOptional, z.ZodType], null>, z.ZodUnknown>>; + upstream: z.ZodOptional; + cf: z.ZodOptional]>>; + liveReload: z.ZodOptional; + unsafeProxySharedSecret: z.ZodOptional; + unsafeModuleFallbackService: z.ZodOptional, mf: Miniflare) => Awaitable, z.ZodTypeDef, (request: Request, mf: Miniflare) => Awaitable>>; + unsafeStickyBlobs: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + rootPath?: undefined; + host?: string | undefined; + port?: number | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + log?: Log | undefined; + handleRuntimeStdio?: ((args_0: Readable, args_1: Readable) => unknown) | undefined; + upstream?: string | undefined; + cf?: string | boolean | Record | undefined; + liveReload?: boolean | undefined; + unsafeProxySharedSecret?: string | undefined; + unsafeModuleFallbackService?: ((request: Request, mf: Miniflare) => Awaitable) | undefined; + unsafeStickyBlobs?: boolean | undefined; + }, { + rootPath?: string | undefined; + host?: string | undefined; + port?: number | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + log?: Log | undefined; + handleRuntimeStdio?: ((args_0: Readable, args_1: Readable) => unknown) | undefined; + upstream?: string | undefined; + cf?: string | boolean | Record | undefined; + liveReload?: boolean | undefined; + unsafeProxySharedSecret?: string | undefined; + unsafeModuleFallbackService?: ((request: Request, mf: Miniflare) => Awaitable) | undefined; + unsafeStickyBlobs?: boolean | undefined; + }>>; + cache: Plugin; + cacheWarnUsage: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; + }, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; + }>, z.ZodObject<{ + cachePersist: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + cachePersist?: string | boolean | undefined; + }, { + cachePersist?: string | boolean | undefined; + }>>; + d1: Plugin, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + d1Databases?: string[] | Record | undefined; + }, { + d1Databases?: string[] | Record | undefined; + }>, z.ZodObject<{ + d1Persist: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + d1Persist?: string | boolean | undefined; + }, { + d1Persist?: string | boolean | undefined; + }>>; + do: Plugin; + unsafeUniqueKey: z.ZodOptional]>>; + unsafePreventEviction: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + className: string; + scriptName?: string | undefined; + unsafeUniqueKey?: string | kUnsafeEphemeralUniqueKey | undefined; + unsafePreventEviction?: boolean | undefined; + }, { + className: string; + scriptName?: string | undefined; + unsafeUniqueKey?: string | kUnsafeEphemeralUniqueKey | undefined; + unsafePreventEviction?: boolean | undefined; + }>]>>>; + }, "strip", z.ZodTypeAny, { + durableObjects?: Record | undefined; + }, { + durableObjects?: Record | undefined; + }>, z.ZodObject<{ + durableObjectsPersist: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + durableObjectsPersist?: string | boolean | undefined; + }, { + durableObjectsPersist?: string | boolean | undefined; + }>>; + kv: Plugin, z.ZodArray]>>; + sitePath: z.ZodOptional>; + siteInclude: z.ZodOptional>; + siteExclude: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; + }, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; + }>, z.ZodObject<{ + kvPersist: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + kvPersist?: string | boolean | undefined; + }, { + kvPersist?: string | boolean | undefined; + }>>; + queues: Plugin; + }, "strip", z.ZodTypeAny, { + queueName: string; + deliveryDelay?: number | undefined; + }, { + queueName: string; + deliveryDelay?: number | undefined; + }>>, z.ZodArray, z.ZodRecord]>>; + queueConsumers: z.ZodOptional; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; + retryDelay: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; + }, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; + }>>, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + queueProducers?: string[] | Record | Record | undefined; + queueConsumers?: string[] | Record | undefined; + }, { + queueProducers?: string[] | Record | Record | undefined; + queueConsumers?: string[] | Record | undefined; + }>>; + r2: Plugin, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + r2Buckets?: string[] | Record | undefined; + }, { + r2Buckets?: string[] | Record | undefined; + }>, z.ZodObject<{ + r2Persist: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + r2Persist?: string | boolean | undefined; + }, { + r2Persist?: string | boolean | undefined; + }>>; + hyperdrive: Plugin]>, URL_2, string | URL_2>>>; + }, "strip", z.ZodTypeAny, { + hyperdrives?: Record | undefined; + }, { + hyperdrives?: Record | undefined; + }>>; + ratelimit: Plugin>; + }, "strip", z.ZodTypeAny, { + limit: number; + period?: PeriodType | undefined; + }, { + limit: number; + period?: PeriodType | undefined; + }>; + }, "strip", z.ZodTypeAny, { + simple: { + limit: number; + period?: PeriodType | undefined; + }; + }, { + simple: { + limit: number; + period?: PeriodType | undefined; + }; + }>>>; + }, "strip", z.ZodTypeAny, { + ratelimits?: Record | undefined; + }, { + ratelimits?: Record | undefined; + }>>; +}; + +export declare type Plugins = typeof PLUGINS; + +export declare interface PluginServicesOptions { + log: Log; + options: z.infer; + sharedOptions: OptionalZodTypeOf; + workerBindings: Worker_Binding[]; + workerIndex: number; + additionalModules: Worker_Module[]; + tmpPath: string; + workerNames: string[]; + loopbackPort: number; + unsafeStickyBlobs: boolean; + wrappedBindingNames: WrappedBindingNames; + durableObjectClassNames: DurableObjectClassNames; + unsafeEphemeralDurableObjects: boolean; + queueProducers: QueueProducers; + queueConsumers: QueueConsumers; +} + +export declare function prefixError(prefix: string, e: any): Error; + +export declare function prefixStream(prefix: Uint8Array, stream: ReadableStream_2): ReadableStream_2; + +export declare const ProxyAddresses: { + readonly GLOBAL: 0; + readonly ENV: 1; + readonly USER_START: 2; +}; + +export declare class ProxyClient { + #private; + constructor(runtimeEntryURL: URL, dispatchFetch: DispatchFetch); + get global(): ServiceWorkerGlobalScope; + get env(): Record; + poisonProxies(): void; + setRuntimeEntryURL(runtimeEntryURL: URL): void; + dispose(): Promise; +} + +export declare const ProxyOps: { + readonly GET: "GET"; + readonly GET_OWN_DESCRIPTOR: "GET_OWN_DESCRIPTOR"; + readonly GET_OWN_KEYS: "GET_OWN_KEYS"; + readonly CALL: "CALL"; + readonly FREE: "FREE"; +}; + +export declare const QueueBindings: { + readonly SERVICE_WORKER_PREFIX: "MINIFLARE_WORKER_"; + readonly MAYBE_JSON_QUEUE_PRODUCERS: "MINIFLARE_QUEUE_PRODUCERS"; + readonly MAYBE_JSON_QUEUE_CONSUMERS: "MINIFLARE_QUEUE_CONSUMERS"; +}; + +export declare type QueueConsumer = z.infer; + +export declare const QueueConsumerOptionsSchema: z.ZodObject<{ + maxBatchSize: z.ZodOptional; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; + retryDelay: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; +}, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; +}>; + +export declare type QueueConsumers = Map>; + +export declare const QueueConsumerSchema: z.ZodIntersection; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; + retryDelay: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; +}, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; +}>, z.ZodObject<{ + workerName: z.ZodString; +}, "strip", z.ZodTypeAny, { + workerName: string; +}, { + workerName: string; +}>>; + +export declare const QueueConsumersSchema: z.ZodRecord; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; + retryDelay: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; +}, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; +}>, z.ZodObject<{ + workerName: z.ZodString; +}, "strip", z.ZodTypeAny, { + workerName: string; +}, { + workerName: string; +}>>>; + +export declare type QueueContentType = z.infer; + +export declare const QueueContentTypeSchema: z.ZodDefault>; + +export declare type QueueIncomingMessage = z.infer; + +export declare const QueueIncomingMessageSchema: z.ZodObject<{ + contentType: z.ZodDefault>; + delaySecs: z.ZodOptional; + body: z.ZodEffects; + id: z.ZodOptional; + timestamp: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + body: Buffer; + contentType: "text" | "json" | "bytes" | "v8"; + delaySecs?: number | undefined; + id?: string | undefined; + timestamp?: number | undefined; +}, { + body: string; + contentType?: "text" | "json" | "bytes" | "v8" | undefined; + delaySecs?: number | undefined; + id?: string | undefined; + timestamp?: number | undefined; +}>; + +export declare type QueueMessageDelay = z.infer; + +export declare const QueueMessageDelaySchema: z.ZodOptional; + +export declare type QueueOutgoingMessage = z.input; + +export declare type QueueProducer = z.infer; + +export declare const QueueProducerOptionsSchema: z.ZodObject<{ + queueName: z.ZodString; + deliveryDelay: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + queueName: string; + deliveryDelay?: number | undefined; +}, { + queueName: string; + deliveryDelay?: number | undefined; +}>; + +export declare type QueueProducers = Map>; + +export declare const QueueProducerSchema: z.ZodIntersection; +}, "strip", z.ZodTypeAny, { + queueName: string; + deliveryDelay?: number | undefined; +}, { + queueName: string; + deliveryDelay?: number | undefined; +}>, z.ZodObject<{ + workerName: z.ZodString; +}, "strip", z.ZodTypeAny, { + workerName: string; +}, { + workerName: string; +}>>; + +export declare const QueueProducersSchema: z.ZodRecord; +}, "strip", z.ZodTypeAny, { + queueName: string; + deliveryDelay?: number | undefined; +}, { + queueName: string; + deliveryDelay?: number | undefined; +}>, z.ZodObject<{ + workerName: z.ZodString; +}, "strip", z.ZodTypeAny, { + workerName: string; +}, { + workerName: string; +}>>>; + +export declare const QUEUES_PLUGIN: Plugin; + +export declare const QUEUES_PLUGIN_NAME = "queues"; + +export declare const QueuesBatchRequestSchema: z.ZodObject<{ + messages: z.ZodArray>; + delaySecs: z.ZodOptional; + body: z.ZodEffects; + id: z.ZodOptional; + timestamp: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + body: Buffer; + contentType: "text" | "json" | "bytes" | "v8"; + delaySecs?: number | undefined; + id?: string | undefined; + timestamp?: number | undefined; + }, { + body: string; + contentType?: "text" | "json" | "bytes" | "v8" | undefined; + delaySecs?: number | undefined; + id?: string | undefined; + timestamp?: number | undefined; + }>, "many">; +}, "strip", z.ZodTypeAny, { + messages: { + body: Buffer; + contentType: "text" | "json" | "bytes" | "v8"; + delaySecs?: number | undefined; + id?: string | undefined; + timestamp?: number | undefined; + }[]; +}, { + messages: { + body: string; + contentType?: "text" | "json" | "bytes" | "v8" | undefined; + delaySecs?: number | undefined; + id?: string | undefined; + timestamp?: number | undefined; + }[]; +}>; + +export declare class QueuesError extends MiniflareError { +} + +export declare type QueuesErrorCode = "ERR_MULTIPLE_CONSUMERS" | "ERR_DEAD_LETTER_QUEUE_CYCLE"; + +export declare const QueuesOptionsSchema: z.ZodObject<{ + queueProducers: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + queueName: string; + deliveryDelay?: number | undefined; + }, { + queueName: string; + deliveryDelay?: number | undefined; + }>>, z.ZodArray, z.ZodRecord]>>; + queueConsumers: z.ZodOptional; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; + retryDelay: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; + }, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + retryDelay?: number | undefined; + }>>, z.ZodArray]>>; +}, "strip", z.ZodTypeAny, { + queueProducers?: string[] | Record | Record | undefined; + queueConsumers?: string[] | Record | undefined; +}, { + queueProducers?: string[] | Record | Record | undefined; + queueConsumers?: string[] | Record | undefined; +}>; + +export declare type QueuesOutgoingBatchRequest = z.input; + +export declare const R2_PLUGIN: Plugin; + +export declare const R2_PLUGIN_NAME = "r2"; + +export declare const R2OptionsSchema: z.ZodObject<{ + r2Buckets: z.ZodOptional, z.ZodArray]>>; +}, "strip", z.ZodTypeAny, { + r2Buckets?: string[] | Record | undefined; +}, { + r2Buckets?: string[] | Record | undefined; +}>; + +export declare const R2SharedOptionsSchema: z.ZodObject<{ + r2Persist: z.ZodOptional]>>; +}, "strip", z.ZodTypeAny, { + r2Persist?: string | boolean | undefined; +}, { + r2Persist?: string | boolean | undefined; +}>; + +export declare const RATELIMIT_PLUGIN: Plugin; + +export declare const RATELIMIT_PLUGIN_NAME = "ratelimit"; + +export declare const RatelimitConfigSchema: z.ZodObject<{ + simple: z.ZodObject<{ + limit: z.ZodNumber; + period: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + limit: number; + period?: PeriodType | undefined; + }, { + limit: number; + period?: PeriodType | undefined; + }>; +}, "strip", z.ZodTypeAny, { + simple: { + limit: number; + period?: PeriodType | undefined; + }; +}, { + simple: { + limit: number; + period?: PeriodType | undefined; + }; +}>; + +export declare const RatelimitOptionsSchema: z.ZodObject<{ + ratelimits: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + limit: number; + period?: PeriodType | undefined; + }, { + limit: number; + period?: PeriodType | undefined; + }>; + }, "strip", z.ZodTypeAny, { + simple: { + limit: number; + period?: PeriodType | undefined; + }; + }, { + simple: { + limit: number; + period?: PeriodType | undefined; + }; + }>>>; +}, "strip", z.ZodTypeAny, { + ratelimits?: Record | undefined; +}, { + ratelimits?: Record | undefined; +}>; + +export declare function readPrefix(stream: ReadableStream_2, prefixLength: number): Promise<[prefix: Buffer, rest: ReadableStream_2]>; + +export declare function reduceError(e: any): JsonError; + +export declare type ReducerReviver = (value: unknown) => unknown; + +export declare type ReducersRevivers = Record; + +export { ReferrerPolicy } + +export declare type ReplaceWorkersTypes = T extends Request_3 ? Request : T extends Response_3 ? Response : T extends ReadableStream ? ReadableStream_2 : Required extends Required ? RequestInit : T extends Headers_2 ? Headers : T extends Blob_2 ? Blob_3 : T extends AbortSignal_2 ? AbortSignal : T extends Promise ? Promise> : T extends (...args: infer P) => infer R ? (...args: ReplaceWorkersTypes

) => ReplaceWorkersTypes : T extends object ? { + [K in keyof T]: OverloadReplaceWorkersTypes; +} : T; + +export declare class Request extends Request_2 { + [kCf]?: CfType; + constructor(input: RequestInfo, init?: RequestInit); + get cf(): CfType | undefined; + /** @ts-expect-error `clone` is actually defined as a method internally */ + clone(): Request; +} + +export { RequestCache } + +export { RequestCredentials } + +export { RequestDestination } + +export { RequestDuplex } + +export declare type RequestInfo = RequestInfo_2 | Request; + +export declare interface RequestInit extends RequestInit_2 { + cf?: CfType; +} + +export declare type RequestInitCfType = Partial | RequestInitCfProperties; + +export { RequestMode } + +export { RequestRedirect } + +export declare class Response extends Response_2 { + readonly [kWebSocket]: WebSocket | null; + static error(): Response; + static redirect(url: string | URL, status: ResponseRedirectStatus): Response; + static json(data: any, init?: ResponseInit): Response; + constructor(body?: BodyInit, init?: ResponseInit); + /** @ts-expect-error `status` is actually defined as a getter internally */ + get status(): number; + get webSocket(): WebSocket | null; + /** @ts-expect-error `clone` is actually defined as a method internally */ + clone(): Response; +} + +export declare interface ResponseInit extends ResponseInit_2 { + webSocket?: WebSocket | null; +} + +export { ResponseRedirectStatus } + +export { ResponseType } + +export declare class RouterError extends MiniflareError { +} + +export declare type RouterErrorCode = "ERR_QUERY_STRING" | "ERR_INFIX_WILDCARD"; + +export declare class Runtime { + #private; + updateConfig(configBuffer: Buffer, options: Abortable & RuntimeOptions): Promise; + dispose(): Awaitable; +} + +export declare interface RuntimeOptions { + entryAddress: string; + loopbackAddress: string; + requiredSockets: SocketIdentifier[]; + inspectorAddress?: string; + verbose?: boolean; + handleRuntimeStdio?: (stdout: Readable, stderr: Readable) => void; +} + +export declare function sanitisePath(unsafe: string): string; + +export declare interface SerialisableMatcherRegExps { + include: string[]; + exclude: string[]; +} + +export declare interface SerialisableSiteMatcherRegExps { + include?: SerialisableMatcherRegExps; + exclude?: SerialisableMatcherRegExps; +} + +export declare function serialiseRegExps(matcher: MatcherRegExps): SerialisableMatcherRegExps; + +export declare function serialiseSiteRegExps(siteRegExps: SiteMatcherRegExps): SerialisableSiteMatcherRegExps; + +export declare function serializeConfig(config: Config): Buffer; + +export declare type Service = { + name?: string; +} & ({ + worker?: Worker; +} | { + network?: Network; +} | { + external?: ExternalServer; +} | { + disk?: DiskDirectory; +}); + +export declare const SERVICE_ENTRY = "core:entry"; + +export declare const SERVICE_LOOPBACK = "loopback"; + +export declare interface ServiceDesignator { + name?: string; + entrypoint?: string; +} + +export declare interface ServicesExtensions { + services: Service[]; + extensions: Extension[]; +} + +export declare const SharedBindings: { + readonly TEXT_NAMESPACE: "MINIFLARE_NAMESPACE"; + readonly DURABLE_OBJECT_NAMESPACE_OBJECT: "MINIFLARE_OBJECT"; + readonly MAYBE_SERVICE_BLOBS: "MINIFLARE_BLOBS"; + readonly MAYBE_SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK"; + readonly MAYBE_JSON_ENABLE_CONTROL_ENDPOINTS: "MINIFLARE_ENABLE_CONTROL_ENDPOINTS"; + readonly MAYBE_JSON_ENABLE_STICKY_BLOBS: "MINIFLARE_STICKY_BLOBS"; +}; + +export declare const SharedHeaders: { + readonly LOG_LEVEL: "MF-Log-Level"; +}; + +export declare type SharedOptions = z.input & z.input & z.input & z.input & z.input & z.input; + +export declare const SiteBindings: { + readonly KV_NAMESPACE_SITE: "__STATIC_CONTENT"; + readonly JSON_SITE_MANIFEST: "__STATIC_CONTENT_MANIFEST"; + readonly JSON_SITE_FILTER: "MINIFLARE_SITE_FILTER"; +}; + +export declare interface SiteMatcherRegExps { + include?: MatcherRegExps; + exclude?: MatcherRegExps; +} + +export declare const SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/"; + +export declare type Socket = { + name?: string; + address?: string; + service?: ServiceDesignator; +} & ({ + http?: HttpOptions; +} | { + https?: Socket_Https; +}); + +export declare const SOCKET_ENTRY = "entry"; + +export declare const SOCKET_ENTRY_LOCAL = "entry:local"; + +export declare interface Socket_Https { + options?: HttpOptions; + tlsOptions?: TlsOptions; +} + +export declare type SocketIdentifier = string | typeof kInspectorSocket; + +export declare type SocketPorts = Map; + +export declare type SourceOptions = z.infer; + +export declare const SourceOptionsSchema: z.ZodUnion<[z.ZodObject<{ + modules: z.ZodArray; + path: z.ZodEffects; + contents: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }>, "many">; + modulesRoot: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; +}, { + modules: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + path: string; + contents?: string | Uint8Array | undefined; + }[]; + modulesRoot?: string | undefined; +}>, z.ZodObject<{ + script: z.ZodString; + scriptPath: z.ZodOptional>; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }>, "many">>; + modulesRoot: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +}, { + script: string; + scriptPath?: string | undefined; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +}>, z.ZodObject<{ + scriptPath: z.ZodEffects; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }, { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }>, "many">>; + modulesRoot: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +}, { + scriptPath: string; + modules?: boolean | undefined; + modulesRules?: { + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm" | "PythonModule" | "PythonRequirement"; + include: string[]; + fallthrough?: boolean | undefined; + }[] | undefined; + modulesRoot?: string | undefined; +}>]>; + +export declare interface StringifiedWithStream { + value: string; + unbufferedStream?: RS; +} + +export declare function stringifyWithStreams(impl: PlatformImpl, value: unknown, reducers: ReducersRevivers, allowUnbufferedStream: boolean): StringifiedWithStream | Promise>; + +export declare function stripAnsi(value: string): string; + +export declare const structuredSerializableReducers: ReducersRevivers; + +export declare const structuredSerializableRevivers: ReducersRevivers; + +export { supportedCompatibilityDate } + +export declare function testRegExps(matcher: MatcherRegExps, value: string): boolean; + +export declare function testSiteRegExps(regExps: SiteMatcherRegExps, key: string): boolean; + +export declare interface TlsOptions { + keypair?: TlsOptions_Keypair; + requireClientCerts?: boolean; + trustBrowserCas?: boolean; + trustedCertificates?: string[]; + minVersion?: TlsOptions_Version; + cipherList?: string; +} + +export declare interface TlsOptions_Keypair { + privateKey?: string; + certificateChain?: string; +} + +export declare enum TlsOptions_Version { + GOOD_DEFAULT = 0, + SSL3 = 1, + TLS1DOT0 = 2, + TLS1DOT1 = 3, + TLS1DOT2 = 4, + TLS1DOT3 = 5 +} + +export declare function _transformsForContentEncoding(encoding?: string): Transform[]; + +export declare type TypedEventListener = ((e: E) => void) | { + handleEvent(e: E): void; +}; + +export declare class TypedEventTarget> extends EventTarget { + addEventListener(type: Type, listener: TypedEventListener | null, options?: AddEventListenerOptions | boolean): void; + removeEventListener(type: Type, listener: TypedEventListener | null, options?: EventListenerOptions | boolean): void; + dispatchEvent(event: ValueOf): boolean; +} + +export declare type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; + +export declare type UnsafeUniqueKey = string | typeof kUnsafeEphemeralUniqueKey; + +export declare type ValueOf = T[keyof T]; + +export declare function viewToBuffer(view: ArrayBufferView): ArrayBuffer; + +export declare type Void = typeof kVoid; + +export declare class WaitGroup { + private counter; + private resolveQueue; + add(): void; + done(): void; + wait(): Promise; +} + +export declare class WebSocket extends TypedEventTarget { + #private; + static readonly READY_STATE_CONNECTING = 0; + static readonly READY_STATE_OPEN = 1; + static readonly READY_STATE_CLOSING = 2; + static readonly READY_STATE_CLOSED = 3; + [kPair]?: WebSocket; + [kAccepted]: boolean; + [kCoupled]: boolean; + [kClosedOutgoing]: boolean; + [kClosedIncoming]: boolean; + get readyState(): number; + accept(): void; + send(message: ArrayBuffer | string): void; + [kSend](message: ArrayBuffer | string): void; + close(code?: number, reason?: string): void; + [kClose](code?: number, reason?: string): void; + [kError](error?: Error): void; +} + +export declare type WebSocketEventMap = { + message: MessageEvent; + close: CloseEvent; + error: ErrorEvent; +}; + +export declare type WebSocketPair = { + 0: WebSocket; + 1: WebSocket; +}; + +export declare const WebSocketPair: new () => WebSocketPair; + +export declare type Worker = ({ + modules?: Worker_Module[]; +} | { + serviceWorkerScript?: string; +} | { + inherit?: string; +}) & { + compatibilityDate?: string; + compatibilityFlags?: string[]; + bindings?: Worker_Binding[]; + globalOutbound?: ServiceDesignator; + cacheApiOutbound?: ServiceDesignator; + durableObjectNamespaces?: Worker_DurableObjectNamespace[]; + durableObjectUniqueKeyModifier?: string; + durableObjectStorage?: Worker_DurableObjectStorage; + moduleFallback?: string; +}; + +export declare type Worker_Binding = { + name?: string; +} & ({ + parameter?: Worker_Binding_Parameter; +} | { + text?: string; +} | { + data?: Uint8Array; +} | { + json?: string; +} | { + wasmModule?: Uint8Array; +} | { + cryptoKey?: Worker_Binding_CryptoKey; +} | { + service?: ServiceDesignator; +} | { + durableObjectNamespace?: Worker_Binding_DurableObjectNamespaceDesignator; +} | { + kvNamespace?: ServiceDesignator; +} | { + r2Bucket?: ServiceDesignator; +} | { + r2Admin?: ServiceDesignator; +} | { + wrapped?: Worker_Binding_WrappedBinding; +} | { + queue?: ServiceDesignator; +} | { + fromEnvironment?: string; +} | { + analyticsEngine?: ServiceDesignator; +} | { + hyperdrive?: Worker_Binding_Hyperdrive; +} | { + unsafeEval?: Void; +}); + +export declare type Worker_Binding_CryptoKey = ({ + raw?: Uint8Array; +} | { + hex?: string; +} | { + base64?: string; +} | { + pkcs8?: string; +} | { + spki?: string; +} | { + jwk?: string; +}) & { + algorithm?: Worker_Binding_CryptoKey_Algorithm; + extractable?: boolean; + usages?: Worker_Binding_CryptoKey_Usage[]; +}; + +export declare type Worker_Binding_CryptoKey_Algorithm = { + name?: string; +} | { + json?: string; +}; + +export declare enum Worker_Binding_CryptoKey_Usage { + ENCRYPT = 0, + DECRYPT = 1, + SIGN = 2, + VERIFY = 3, + DERIVE_KEY = 4, + DERIVE_BITS = 5, + WRAP_KEY = 6, + UNWRAP_KEY = 7 +} + +export declare type Worker_Binding_DurableObjectNamespaceDesignator = { + className?: string; + serviceName?: string; +}; + +export declare interface Worker_Binding_Hyperdrive { + designator?: ServiceDesignator; + database?: string; + user?: string; + password?: string; + scheme?: string; +} + +export declare interface Worker_Binding_MemoryCache { + id?: string; + limits?: Worker_Binding_MemoryCacheLimits; +} + +export declare interface Worker_Binding_MemoryCacheLimits { + maxKeys?: number; + maxValueSize?: number; + maxTotalValueSize?: number; +} + +export declare interface Worker_Binding_Parameter { + type?: Worker_Binding_Type; + optional?: boolean; +} + +export declare const WORKER_BINDING_SERVICE_LOOPBACK: Worker_Binding; + +export declare type Worker_Binding_Type = { + text?: Void; +} | { + data?: Void; +} | { + json?: Void; +} | { + wasm?: Void; +} | { + cryptoKey?: Worker_Binding_CryptoKey_Usage[]; +} | { + service?: Void; +} | { + durableObjectNamespace: Void; +} | { + kvNamespace?: Void; +} | { + r2Bucket?: Void; +} | { + r2Admin?: Void; +} | { + queue?: Void; +} | { + analyticsEngine?: Void; +} | { + hyperdrive?: Void; +}; + +export declare interface Worker_Binding_WrappedBinding { + moduleName?: string; + entrypoint?: string; + innerBindings?: Worker_Binding[]; +} + +export declare type Worker_DurableObjectNamespace = { + className?: string; + preventEviction?: boolean; +} & ({ + uniqueKey?: string; +} | { + ephemeralLocal?: Void; +}); + +export declare type Worker_DurableObjectStorage = { + none?: Void; +} | { + inMemory?: Void; +} | { + localDisk?: string; +}; + +export declare type Worker_Module = { + name: string; +} & ({ + esModule?: string; +} | { + commonJsModule?: string; +} | { + text?: string; +} | { + data?: Uint8Array; +} | { + wasm?: Uint8Array; +} | { + json?: string; +} | { + nodeJsCompatModule?: string; +} | { + pythonModule?: string; +} | { + pythonRequirement?: string; +}); + +export declare type WorkerOptions = z.input & z.input & z.input & z.input & z.input & z.input & z.input & z.input & z.input; + +export declare interface WorkerRoute { + target: string; + route: string; + specificity: number; + protocol?: string; + allowHostnamePrefix: boolean; + hostname: string; + path: string; + allowPathSuffix: boolean; +} + +export declare type WrappedBindingNames = Set; + +export declare function zAwaitable(type: T): z.ZodUnion<[T, z.ZodPromise]>; + +export { } diff --git a/node_modules/miniflare/dist/src/index.js b/node_modules/miniflare/dist/src/index.js new file mode 100644 index 0000000..13c011c --- /dev/null +++ b/node_modules/miniflare/dist/src/index.js @@ -0,0 +1,9575 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; +var __privateMethod = (obj, member, method) => { + __accessCheck(obj, member, "access private method"); + return method; +}; + +// src/runtime/config/workerd.capnp.js +var require_workerd_capnp = __commonJS({ + "src/runtime/config/workerd.capnp.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Extension = exports.Extension_Module = exports.TlsOptions = exports.TlsOptions_Version = exports.TlsOptions_Keypair = exports.HttpOptions = exports.HttpOptions_Header = exports.HttpOptions_Style = exports.DiskDirectory = exports.Network = exports.ExternalServer = exports.ExternalServer_Which = exports.ExternalServer_Tcp = exports.ExternalServer_Https = exports.Worker = exports.Worker_Which = exports.Worker_DurableObjectStorage = exports.Worker_DurableObjectStorage_Which = exports.Worker_DurableObjectNamespace = exports.Worker_DurableObjectNamespace_Which = exports.Worker_Binding = exports.Worker_Binding_Which = exports.Worker_Binding_MemoryCache = exports.Worker_Binding_Hyperdrive = exports.Worker_Binding_Parameter = exports.Worker_Binding_WrappedBinding = exports.Worker_Binding_MemoryCacheLimits = exports.Worker_Binding_CryptoKey = exports.Worker_Binding_CryptoKey_Which = exports.Worker_Binding_CryptoKey_Algorithm = exports.Worker_Binding_CryptoKey_Algorithm_Which = exports.Worker_Binding_CryptoKey_Usage = exports.Worker_Binding_DurableObjectNamespaceDesignator = exports.Worker_Binding_Type = exports.Worker_Binding_Type_Which = exports.Worker_Module = exports.Worker_Module_Which = exports.ServiceDesignator = exports.Service = exports.Service_Which = exports.Socket = exports.Socket_Which = exports.Socket_Https = exports.Config = exports._capnpFileId = void 0; + var capnp = require("capnp-ts"); + var capnp_ts_1 = require("capnp-ts"); + exports._capnpFileId = "e6afd26682091c01"; + var Config3 = class extends capnp_ts_1.Struct { + adoptServices(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownServices() { + return capnp_ts_1.Struct.disown(this.getServices()); + } + getServices() { + return capnp_ts_1.Struct.getList(0, Config3._Services, this); + } + hasServices() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initServices(length) { + return capnp_ts_1.Struct.initList(0, Config3._Services, length, this); + } + setServices(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + adoptSockets(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownSockets() { + return capnp_ts_1.Struct.disown(this.getSockets()); + } + getSockets() { + return capnp_ts_1.Struct.getList(1, Config3._Sockets, this); + } + hasSockets() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initSockets(length) { + return capnp_ts_1.Struct.initList(1, Config3._Sockets, length, this); + } + setSockets(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptV8Flags(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownV8Flags() { + return capnp_ts_1.Struct.disown(this.getV8Flags()); + } + getV8Flags() { + return capnp_ts_1.Struct.getList(2, capnp.TextList, this); + } + hasV8Flags() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initV8Flags(length) { + return capnp_ts_1.Struct.initList(2, capnp.TextList, length, this); + } + setV8Flags(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + adoptExtensions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this)); + } + disownExtensions() { + return capnp_ts_1.Struct.disown(this.getExtensions()); + } + getExtensions() { + return capnp_ts_1.Struct.getList(3, Config3._Extensions, this); + } + hasExtensions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this)); + } + initExtensions(length) { + return capnp_ts_1.Struct.initList(3, Config3._Extensions, length, this); + } + setExtensions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this)); + } + adoptAutogates(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(4, this)); + } + disownAutogates() { + return capnp_ts_1.Struct.disown(this.getAutogates()); + } + getAutogates() { + return capnp_ts_1.Struct.getList(4, capnp.TextList, this); + } + hasAutogates() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(4, this)); + } + initAutogates(length) { + return capnp_ts_1.Struct.initList(4, capnp.TextList, length, this); + } + setAutogates(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(4, this)); + } + toString() { + return "Config_" + super.toString(); + } + }; + exports.Config = Config3; + Config3._capnp = { displayName: "Config", id: "8794486c76aaa7d6", size: new capnp_ts_1.ObjectSize(0, 5) }; + var Socket_Https = class extends capnp_ts_1.Struct { + adoptOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownOptions() { + return capnp_ts_1.Struct.disown(this.getOptions()); + } + getOptions() { + return capnp_ts_1.Struct.getStruct(2, HttpOptions, this); + } + hasOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initOptions() { + return capnp_ts_1.Struct.initStructAt(2, HttpOptions, this); + } + setOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + adoptTlsOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this)); + } + disownTlsOptions() { + return capnp_ts_1.Struct.disown(this.getTlsOptions()); + } + getTlsOptions() { + return capnp_ts_1.Struct.getStruct(3, TlsOptions, this); + } + hasTlsOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this)); + } + initTlsOptions() { + return capnp_ts_1.Struct.initStructAt(3, TlsOptions, this); + } + setTlsOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this)); + } + toString() { + return "Socket_Https_" + super.toString(); + } + }; + exports.Socket_Https = Socket_Https; + Socket_Https._capnp = { displayName: "https", id: "de123876383cbbdc", size: new capnp_ts_1.ObjectSize(8, 5) }; + var Socket_Which; + (function(Socket_Which2) { + Socket_Which2[Socket_Which2["HTTP"] = 0] = "HTTP"; + Socket_Which2[Socket_Which2["HTTPS"] = 1] = "HTTPS"; + })(Socket_Which = exports.Socket_Which || (exports.Socket_Which = {})); + var Socket2 = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getAddress() { + return capnp_ts_1.Struct.getText(1, this); + } + setAddress(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + adoptHttp(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownHttp() { + return capnp_ts_1.Struct.disown(this.getHttp()); + } + getHttp() { + capnp_ts_1.Struct.testWhich("http", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getStruct(2, HttpOptions, this); + } + hasHttp() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initHttp() { + capnp_ts_1.Struct.setUint16(0, 0, this); + return capnp_ts_1.Struct.initStructAt(2, HttpOptions, this); + } + isHttp() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setHttp(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + getHttps() { + capnp_ts_1.Struct.testWhich("https", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getAs(Socket_Https, this); + } + initHttps() { + capnp_ts_1.Struct.setUint16(0, 1, this); + return capnp_ts_1.Struct.getAs(Socket_Https, this); + } + isHttps() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setHttps() { + capnp_ts_1.Struct.setUint16(0, 1, this); + } + adoptService(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(4, this)); + } + disownService() { + return capnp_ts_1.Struct.disown(this.getService()); + } + getService() { + return capnp_ts_1.Struct.getStruct(4, ServiceDesignator2, this); + } + hasService() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(4, this)); + } + initService() { + return capnp_ts_1.Struct.initStructAt(4, ServiceDesignator2, this); + } + setService(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(4, this)); + } + toString() { + return "Socket_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Socket = Socket2; + Socket2.HTTP = Socket_Which.HTTP; + Socket2.HTTPS = Socket_Which.HTTPS; + Socket2._capnp = { displayName: "Socket", id: "9a0eba45530ee79f", size: new capnp_ts_1.ObjectSize(8, 5) }; + var Service_Which; + (function(Service_Which2) { + Service_Which2[Service_Which2["UNSPECIFIED"] = 0] = "UNSPECIFIED"; + Service_Which2[Service_Which2["WORKER"] = 1] = "WORKER"; + Service_Which2[Service_Which2["NETWORK"] = 2] = "NETWORK"; + Service_Which2[Service_Which2["EXTERNAL"] = 3] = "EXTERNAL"; + Service_Which2[Service_Which2["DISK"] = 4] = "DISK"; + })(Service_Which = exports.Service_Which || (exports.Service_Which = {})); + var Service4 = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + isUnspecified() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setUnspecified() { + capnp_ts_1.Struct.setUint16(0, 0, this); + } + adoptWorker(value) { + capnp_ts_1.Struct.setUint16(0, 1, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownWorker() { + return capnp_ts_1.Struct.disown(this.getWorker()); + } + getWorker() { + capnp_ts_1.Struct.testWhich("worker", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getStruct(1, Worker2, this); + } + hasWorker() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initWorker() { + capnp_ts_1.Struct.setUint16(0, 1, this); + return capnp_ts_1.Struct.initStructAt(1, Worker2, this); + } + isWorker() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setWorker(value) { + capnp_ts_1.Struct.setUint16(0, 1, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptNetwork(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownNetwork() { + return capnp_ts_1.Struct.disown(this.getNetwork()); + } + getNetwork() { + capnp_ts_1.Struct.testWhich("network", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getStruct(1, Network, this); + } + hasNetwork() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initNetwork() { + capnp_ts_1.Struct.setUint16(0, 2, this); + return capnp_ts_1.Struct.initStructAt(1, Network, this); + } + isNetwork() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setNetwork(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptExternal(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownExternal() { + return capnp_ts_1.Struct.disown(this.getExternal()); + } + getExternal() { + capnp_ts_1.Struct.testWhich("external", capnp_ts_1.Struct.getUint16(0, this), 3, this); + return capnp_ts_1.Struct.getStruct(1, ExternalServer2, this); + } + hasExternal() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initExternal() { + capnp_ts_1.Struct.setUint16(0, 3, this); + return capnp_ts_1.Struct.initStructAt(1, ExternalServer2, this); + } + isExternal() { + return capnp_ts_1.Struct.getUint16(0, this) === 3; + } + setExternal(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptDisk(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownDisk() { + return capnp_ts_1.Struct.disown(this.getDisk()); + } + getDisk() { + capnp_ts_1.Struct.testWhich("disk", capnp_ts_1.Struct.getUint16(0, this), 4, this); + return capnp_ts_1.Struct.getStruct(1, DiskDirectory, this); + } + hasDisk() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initDisk() { + capnp_ts_1.Struct.setUint16(0, 4, this); + return capnp_ts_1.Struct.initStructAt(1, DiskDirectory, this); + } + isDisk() { + return capnp_ts_1.Struct.getUint16(0, this) === 4; + } + setDisk(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + toString() { + return "Service_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Service = Service4; + Service4.UNSPECIFIED = Service_Which.UNSPECIFIED; + Service4.WORKER = Service_Which.WORKER; + Service4.NETWORK = Service_Which.NETWORK; + Service4.EXTERNAL = Service_Which.EXTERNAL; + Service4.DISK = Service_Which.DISK; + Service4._capnp = { displayName: "Service", id: "e5c88e8bb7bcb6b9", size: new capnp_ts_1.ObjectSize(8, 2) }; + var ServiceDesignator2 = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getEntrypoint() { + return capnp_ts_1.Struct.getText(1, this); + } + setEntrypoint(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "ServiceDesignator_" + super.toString(); + } + }; + exports.ServiceDesignator = ServiceDesignator2; + ServiceDesignator2._capnp = { displayName: "ServiceDesignator", id: "ae8ec91cee724450", size: new capnp_ts_1.ObjectSize(0, 2) }; + var Worker_Module_Which; + (function(Worker_Module_Which2) { + Worker_Module_Which2[Worker_Module_Which2["ES_MODULE"] = 0] = "ES_MODULE"; + Worker_Module_Which2[Worker_Module_Which2["COMMON_JS_MODULE"] = 1] = "COMMON_JS_MODULE"; + Worker_Module_Which2[Worker_Module_Which2["TEXT"] = 2] = "TEXT"; + Worker_Module_Which2[Worker_Module_Which2["DATA"] = 3] = "DATA"; + Worker_Module_Which2[Worker_Module_Which2["WASM"] = 4] = "WASM"; + Worker_Module_Which2[Worker_Module_Which2["JSON"] = 5] = "JSON"; + Worker_Module_Which2[Worker_Module_Which2["NODE_JS_COMPAT_MODULE"] = 6] = "NODE_JS_COMPAT_MODULE"; + Worker_Module_Which2[Worker_Module_Which2["PYTHON_MODULE"] = 7] = "PYTHON_MODULE"; + Worker_Module_Which2[Worker_Module_Which2["PYTHON_REQUIREMENT"] = 8] = "PYTHON_REQUIREMENT"; + })(Worker_Module_Which = exports.Worker_Module_Which || (exports.Worker_Module_Which = {})); + var Worker_Module3 = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getEsModule() { + capnp_ts_1.Struct.testWhich("esModule", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getText(1, this); + } + isEsModule() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setEsModule(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.setText(1, value, this); + } + getCommonJsModule() { + capnp_ts_1.Struct.testWhich("commonJsModule", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getText(1, this); + } + isCommonJsModule() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setCommonJsModule(value) { + capnp_ts_1.Struct.setUint16(0, 1, this); + capnp_ts_1.Struct.setText(1, value, this); + } + getText() { + capnp_ts_1.Struct.testWhich("text", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getText(1, this); + } + isText() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setText(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.setText(1, value, this); + } + adoptData(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownData() { + return capnp_ts_1.Struct.disown(this.getData()); + } + getData() { + capnp_ts_1.Struct.testWhich("data", capnp_ts_1.Struct.getUint16(0, this), 3, this); + return capnp_ts_1.Struct.getData(1, this); + } + hasData() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initData(length) { + capnp_ts_1.Struct.setUint16(0, 3, this); + return capnp_ts_1.Struct.initData(1, length, this); + } + isData() { + return capnp_ts_1.Struct.getUint16(0, this) === 3; + } + setData(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptWasm(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownWasm() { + return capnp_ts_1.Struct.disown(this.getWasm()); + } + getWasm() { + capnp_ts_1.Struct.testWhich("wasm", capnp_ts_1.Struct.getUint16(0, this), 4, this); + return capnp_ts_1.Struct.getData(1, this); + } + hasWasm() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initWasm(length) { + capnp_ts_1.Struct.setUint16(0, 4, this); + return capnp_ts_1.Struct.initData(1, length, this); + } + isWasm() { + return capnp_ts_1.Struct.getUint16(0, this) === 4; + } + setWasm(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getJson() { + capnp_ts_1.Struct.testWhich("json", capnp_ts_1.Struct.getUint16(0, this), 5, this); + return capnp_ts_1.Struct.getText(1, this); + } + isJson() { + return capnp_ts_1.Struct.getUint16(0, this) === 5; + } + setJson(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.setText(1, value, this); + } + getNodeJsCompatModule() { + capnp_ts_1.Struct.testWhich("nodeJsCompatModule", capnp_ts_1.Struct.getUint16(0, this), 6, this); + return capnp_ts_1.Struct.getText(1, this); + } + isNodeJsCompatModule() { + return capnp_ts_1.Struct.getUint16(0, this) === 6; + } + setNodeJsCompatModule(value) { + capnp_ts_1.Struct.setUint16(0, 6, this); + capnp_ts_1.Struct.setText(1, value, this); + } + getPythonModule() { + capnp_ts_1.Struct.testWhich("pythonModule", capnp_ts_1.Struct.getUint16(0, this), 7, this); + return capnp_ts_1.Struct.getText(1, this); + } + isPythonModule() { + return capnp_ts_1.Struct.getUint16(0, this) === 7; + } + setPythonModule(value) { + capnp_ts_1.Struct.setUint16(0, 7, this); + capnp_ts_1.Struct.setText(1, value, this); + } + getPythonRequirement() { + capnp_ts_1.Struct.testWhich("pythonRequirement", capnp_ts_1.Struct.getUint16(0, this), 8, this); + return capnp_ts_1.Struct.getText(1, this); + } + isPythonRequirement() { + return capnp_ts_1.Struct.getUint16(0, this) === 8; + } + setPythonRequirement(value) { + capnp_ts_1.Struct.setUint16(0, 8, this); + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "Worker_Module_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker_Module = Worker_Module3; + Worker_Module3.ES_MODULE = Worker_Module_Which.ES_MODULE; + Worker_Module3.COMMON_JS_MODULE = Worker_Module_Which.COMMON_JS_MODULE; + Worker_Module3.TEXT = Worker_Module_Which.TEXT; + Worker_Module3.DATA = Worker_Module_Which.DATA; + Worker_Module3.WASM = Worker_Module_Which.WASM; + Worker_Module3.JSON = Worker_Module_Which.JSON; + Worker_Module3.NODE_JS_COMPAT_MODULE = Worker_Module_Which.NODE_JS_COMPAT_MODULE; + Worker_Module3.PYTHON_MODULE = Worker_Module_Which.PYTHON_MODULE; + Worker_Module3.PYTHON_REQUIREMENT = Worker_Module_Which.PYTHON_REQUIREMENT; + Worker_Module3._capnp = { displayName: "Module", id: "d9d87a63770a12f3", size: new capnp_ts_1.ObjectSize(8, 2) }; + var Worker_Binding_Type_Which; + (function(Worker_Binding_Type_Which2) { + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["UNSPECIFIED"] = 0] = "UNSPECIFIED"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["TEXT"] = 1] = "TEXT"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["DATA"] = 2] = "DATA"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["JSON"] = 3] = "JSON"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["WASM"] = 4] = "WASM"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["CRYPTO_KEY"] = 5] = "CRYPTO_KEY"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["SERVICE"] = 6] = "SERVICE"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["DURABLE_OBJECT_NAMESPACE"] = 7] = "DURABLE_OBJECT_NAMESPACE"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["KV_NAMESPACE"] = 8] = "KV_NAMESPACE"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["R2BUCKET"] = 9] = "R2BUCKET"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["R2ADMIN"] = 10] = "R2ADMIN"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["QUEUE"] = 11] = "QUEUE"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["ANALYTICS_ENGINE"] = 12] = "ANALYTICS_ENGINE"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["HYPERDRIVE"] = 13] = "HYPERDRIVE"; + })(Worker_Binding_Type_Which = exports.Worker_Binding_Type_Which || (exports.Worker_Binding_Type_Which = {})); + var Worker_Binding_Type = class extends capnp_ts_1.Struct { + isUnspecified() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setUnspecified() { + capnp_ts_1.Struct.setUint16(0, 0, this); + } + isText() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setText() { + capnp_ts_1.Struct.setUint16(0, 1, this); + } + isData() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setData() { + capnp_ts_1.Struct.setUint16(0, 2, this); + } + isJson() { + return capnp_ts_1.Struct.getUint16(0, this) === 3; + } + setJson() { + capnp_ts_1.Struct.setUint16(0, 3, this); + } + isWasm() { + return capnp_ts_1.Struct.getUint16(0, this) === 4; + } + setWasm() { + capnp_ts_1.Struct.setUint16(0, 4, this); + } + adoptCryptoKey(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownCryptoKey() { + return capnp_ts_1.Struct.disown(this.getCryptoKey()); + } + getCryptoKey() { + capnp_ts_1.Struct.testWhich("cryptoKey", capnp_ts_1.Struct.getUint16(0, this), 5, this); + return capnp_ts_1.Struct.getList(0, capnp.Uint16List, this); + } + hasCryptoKey() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initCryptoKey(length) { + capnp_ts_1.Struct.setUint16(0, 5, this); + return capnp_ts_1.Struct.initList(0, capnp.Uint16List, length, this); + } + isCryptoKey() { + return capnp_ts_1.Struct.getUint16(0, this) === 5; + } + setCryptoKey(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + isService() { + return capnp_ts_1.Struct.getUint16(0, this) === 6; + } + setService() { + capnp_ts_1.Struct.setUint16(0, 6, this); + } + isDurableObjectNamespace() { + return capnp_ts_1.Struct.getUint16(0, this) === 7; + } + setDurableObjectNamespace() { + capnp_ts_1.Struct.setUint16(0, 7, this); + } + isKvNamespace() { + return capnp_ts_1.Struct.getUint16(0, this) === 8; + } + setKvNamespace() { + capnp_ts_1.Struct.setUint16(0, 8, this); + } + isR2Bucket() { + return capnp_ts_1.Struct.getUint16(0, this) === 9; + } + setR2Bucket() { + capnp_ts_1.Struct.setUint16(0, 9, this); + } + isR2Admin() { + return capnp_ts_1.Struct.getUint16(0, this) === 10; + } + setR2Admin() { + capnp_ts_1.Struct.setUint16(0, 10, this); + } + isQueue() { + return capnp_ts_1.Struct.getUint16(0, this) === 11; + } + setQueue() { + capnp_ts_1.Struct.setUint16(0, 11, this); + } + isAnalyticsEngine() { + return capnp_ts_1.Struct.getUint16(0, this) === 12; + } + setAnalyticsEngine() { + capnp_ts_1.Struct.setUint16(0, 12, this); + } + isHyperdrive() { + return capnp_ts_1.Struct.getUint16(0, this) === 13; + } + setHyperdrive() { + capnp_ts_1.Struct.setUint16(0, 13, this); + } + toString() { + return "Worker_Binding_Type_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker_Binding_Type = Worker_Binding_Type; + Worker_Binding_Type.UNSPECIFIED = Worker_Binding_Type_Which.UNSPECIFIED; + Worker_Binding_Type.TEXT = Worker_Binding_Type_Which.TEXT; + Worker_Binding_Type.DATA = Worker_Binding_Type_Which.DATA; + Worker_Binding_Type.JSON = Worker_Binding_Type_Which.JSON; + Worker_Binding_Type.WASM = Worker_Binding_Type_Which.WASM; + Worker_Binding_Type.CRYPTO_KEY = Worker_Binding_Type_Which.CRYPTO_KEY; + Worker_Binding_Type.SERVICE = Worker_Binding_Type_Which.SERVICE; + Worker_Binding_Type.DURABLE_OBJECT_NAMESPACE = Worker_Binding_Type_Which.DURABLE_OBJECT_NAMESPACE; + Worker_Binding_Type.KV_NAMESPACE = Worker_Binding_Type_Which.KV_NAMESPACE; + Worker_Binding_Type.R2BUCKET = Worker_Binding_Type_Which.R2BUCKET; + Worker_Binding_Type.R2ADMIN = Worker_Binding_Type_Which.R2ADMIN; + Worker_Binding_Type.QUEUE = Worker_Binding_Type_Which.QUEUE; + Worker_Binding_Type.ANALYTICS_ENGINE = Worker_Binding_Type_Which.ANALYTICS_ENGINE; + Worker_Binding_Type.HYPERDRIVE = Worker_Binding_Type_Which.HYPERDRIVE; + Worker_Binding_Type._capnp = { displayName: "Type", id: "8906a1296519bf8a", size: new capnp_ts_1.ObjectSize(8, 1) }; + var Worker_Binding_DurableObjectNamespaceDesignator2 = class extends capnp_ts_1.Struct { + getClassName() { + return capnp_ts_1.Struct.getText(0, this); + } + setClassName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getServiceName() { + return capnp_ts_1.Struct.getText(1, this); + } + setServiceName(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "Worker_Binding_DurableObjectNamespaceDesignator_" + super.toString(); + } + }; + exports.Worker_Binding_DurableObjectNamespaceDesignator = Worker_Binding_DurableObjectNamespaceDesignator2; + Worker_Binding_DurableObjectNamespaceDesignator2._capnp = { displayName: "DurableObjectNamespaceDesignator", id: "804f144ff477aac7", size: new capnp_ts_1.ObjectSize(0, 2) }; + var Worker_Binding_CryptoKey_Usage2; + (function(Worker_Binding_CryptoKey_Usage3) { + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["ENCRYPT"] = 0] = "ENCRYPT"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["DECRYPT"] = 1] = "DECRYPT"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["SIGN"] = 2] = "SIGN"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["VERIFY"] = 3] = "VERIFY"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["DERIVE_KEY"] = 4] = "DERIVE_KEY"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["DERIVE_BITS"] = 5] = "DERIVE_BITS"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["WRAP_KEY"] = 6] = "WRAP_KEY"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["UNWRAP_KEY"] = 7] = "UNWRAP_KEY"; + })(Worker_Binding_CryptoKey_Usage2 = exports.Worker_Binding_CryptoKey_Usage || (exports.Worker_Binding_CryptoKey_Usage = {})); + var Worker_Binding_CryptoKey_Algorithm_Which; + (function(Worker_Binding_CryptoKey_Algorithm_Which2) { + Worker_Binding_CryptoKey_Algorithm_Which2[Worker_Binding_CryptoKey_Algorithm_Which2["NAME"] = 0] = "NAME"; + Worker_Binding_CryptoKey_Algorithm_Which2[Worker_Binding_CryptoKey_Algorithm_Which2["JSON"] = 1] = "JSON"; + })(Worker_Binding_CryptoKey_Algorithm_Which = exports.Worker_Binding_CryptoKey_Algorithm_Which || (exports.Worker_Binding_CryptoKey_Algorithm_Which = {})); + var Worker_Binding_CryptoKey_Algorithm = class extends capnp_ts_1.Struct { + getName() { + capnp_ts_1.Struct.testWhich("name", capnp_ts_1.Struct.getUint16(2, this), 0, this); + return capnp_ts_1.Struct.getText(1, this); + } + isName() { + return capnp_ts_1.Struct.getUint16(2, this) === 0; + } + setName(value) { + capnp_ts_1.Struct.setUint16(2, 0, this); + capnp_ts_1.Struct.setText(1, value, this); + } + getJson() { + capnp_ts_1.Struct.testWhich("json", capnp_ts_1.Struct.getUint16(2, this), 1, this); + return capnp_ts_1.Struct.getText(1, this); + } + isJson() { + return capnp_ts_1.Struct.getUint16(2, this) === 1; + } + setJson(value) { + capnp_ts_1.Struct.setUint16(2, 1, this); + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "Worker_Binding_CryptoKey_Algorithm_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(2, this); + } + }; + exports.Worker_Binding_CryptoKey_Algorithm = Worker_Binding_CryptoKey_Algorithm; + Worker_Binding_CryptoKey_Algorithm.NAME = Worker_Binding_CryptoKey_Algorithm_Which.NAME; + Worker_Binding_CryptoKey_Algorithm.JSON = Worker_Binding_CryptoKey_Algorithm_Which.JSON; + Worker_Binding_CryptoKey_Algorithm._capnp = { displayName: "algorithm", id: "a1a040c5e00d7021", size: new capnp_ts_1.ObjectSize(8, 3) }; + var Worker_Binding_CryptoKey_Which; + (function(Worker_Binding_CryptoKey_Which2) { + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["RAW"] = 0] = "RAW"; + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["HEX"] = 1] = "HEX"; + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["BASE64"] = 2] = "BASE64"; + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["PKCS8"] = 3] = "PKCS8"; + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["SPKI"] = 4] = "SPKI"; + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["JWK"] = 5] = "JWK"; + })(Worker_Binding_CryptoKey_Which = exports.Worker_Binding_CryptoKey_Which || (exports.Worker_Binding_CryptoKey_Which = {})); + var Worker_Binding_CryptoKey = class extends capnp_ts_1.Struct { + adoptRaw(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownRaw() { + return capnp_ts_1.Struct.disown(this.getRaw()); + } + getRaw() { + capnp_ts_1.Struct.testWhich("raw", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getData(0, this); + } + hasRaw() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initRaw(length) { + capnp_ts_1.Struct.setUint16(0, 0, this); + return capnp_ts_1.Struct.initData(0, length, this); + } + isRaw() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setRaw(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + getHex() { + capnp_ts_1.Struct.testWhich("hex", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getText(0, this); + } + isHex() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setHex(value) { + capnp_ts_1.Struct.setUint16(0, 1, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getBase64() { + capnp_ts_1.Struct.testWhich("base64", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getText(0, this); + } + isBase64() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setBase64(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getPkcs8() { + capnp_ts_1.Struct.testWhich("pkcs8", capnp_ts_1.Struct.getUint16(0, this), 3, this); + return capnp_ts_1.Struct.getText(0, this); + } + isPkcs8() { + return capnp_ts_1.Struct.getUint16(0, this) === 3; + } + setPkcs8(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getSpki() { + capnp_ts_1.Struct.testWhich("spki", capnp_ts_1.Struct.getUint16(0, this), 4, this); + return capnp_ts_1.Struct.getText(0, this); + } + isSpki() { + return capnp_ts_1.Struct.getUint16(0, this) === 4; + } + setSpki(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getJwk() { + capnp_ts_1.Struct.testWhich("jwk", capnp_ts_1.Struct.getUint16(0, this), 5, this); + return capnp_ts_1.Struct.getText(0, this); + } + isJwk() { + return capnp_ts_1.Struct.getUint16(0, this) === 5; + } + setJwk(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getAlgorithm() { + return capnp_ts_1.Struct.getAs(Worker_Binding_CryptoKey_Algorithm, this); + } + initAlgorithm() { + return capnp_ts_1.Struct.getAs(Worker_Binding_CryptoKey_Algorithm, this); + } + getExtractable() { + return capnp_ts_1.Struct.getBit(32, this, Worker_Binding_CryptoKey._capnp.defaultExtractable); + } + setExtractable(value) { + capnp_ts_1.Struct.setBit(32, value, this); + } + adoptUsages(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownUsages() { + return capnp_ts_1.Struct.disown(this.getUsages()); + } + getUsages() { + return capnp_ts_1.Struct.getList(2, capnp.Uint16List, this); + } + hasUsages() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initUsages(length) { + return capnp_ts_1.Struct.initList(2, capnp.Uint16List, length, this); + } + setUsages(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + toString() { + return "Worker_Binding_CryptoKey_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker_Binding_CryptoKey = Worker_Binding_CryptoKey; + Worker_Binding_CryptoKey.RAW = Worker_Binding_CryptoKey_Which.RAW; + Worker_Binding_CryptoKey.HEX = Worker_Binding_CryptoKey_Which.HEX; + Worker_Binding_CryptoKey.BASE64 = Worker_Binding_CryptoKey_Which.BASE64; + Worker_Binding_CryptoKey.PKCS8 = Worker_Binding_CryptoKey_Which.PKCS8; + Worker_Binding_CryptoKey.SPKI = Worker_Binding_CryptoKey_Which.SPKI; + Worker_Binding_CryptoKey.JWK = Worker_Binding_CryptoKey_Which.JWK; + Worker_Binding_CryptoKey.Usage = Worker_Binding_CryptoKey_Usage2; + Worker_Binding_CryptoKey._capnp = { displayName: "CryptoKey", id: "b5e1bff0e57d6eb0", size: new capnp_ts_1.ObjectSize(8, 3), defaultExtractable: capnp.getBitMask(false, 0) }; + var Worker_Binding_MemoryCacheLimits = class extends capnp_ts_1.Struct { + getMaxKeys() { + return capnp_ts_1.Struct.getUint32(0, this); + } + setMaxKeys(value) { + capnp_ts_1.Struct.setUint32(0, value, this); + } + getMaxValueSize() { + return capnp_ts_1.Struct.getUint32(4, this); + } + setMaxValueSize(value) { + capnp_ts_1.Struct.setUint32(4, value, this); + } + getMaxTotalValueSize() { + return capnp_ts_1.Struct.getUint64(8, this); + } + setMaxTotalValueSize(value) { + capnp_ts_1.Struct.setUint64(8, value, this); + } + toString() { + return "Worker_Binding_MemoryCacheLimits_" + super.toString(); + } + }; + exports.Worker_Binding_MemoryCacheLimits = Worker_Binding_MemoryCacheLimits; + Worker_Binding_MemoryCacheLimits._capnp = { displayName: "MemoryCacheLimits", id: "8d66725b0867e634", size: new capnp_ts_1.ObjectSize(16, 0) }; + var Worker_Binding_WrappedBinding = class extends capnp_ts_1.Struct { + getModuleName() { + return capnp_ts_1.Struct.getText(0, this); + } + setModuleName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getEntrypoint() { + return capnp_ts_1.Struct.getText(1, this, Worker_Binding_WrappedBinding._capnp.defaultEntrypoint); + } + setEntrypoint(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + adoptInnerBindings(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownInnerBindings() { + return capnp_ts_1.Struct.disown(this.getInnerBindings()); + } + getInnerBindings() { + return capnp_ts_1.Struct.getList(2, Worker_Binding_WrappedBinding._InnerBindings, this); + } + hasInnerBindings() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initInnerBindings(length) { + return capnp_ts_1.Struct.initList(2, Worker_Binding_WrappedBinding._InnerBindings, length, this); + } + setInnerBindings(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + toString() { + return "Worker_Binding_WrappedBinding_" + super.toString(); + } + }; + exports.Worker_Binding_WrappedBinding = Worker_Binding_WrappedBinding; + Worker_Binding_WrappedBinding._capnp = { displayName: "WrappedBinding", id: "e6f066b75f0ea113", size: new capnp_ts_1.ObjectSize(0, 3), defaultEntrypoint: "default" }; + var Worker_Binding_Parameter = class extends capnp_ts_1.Struct { + adoptType(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownType() { + return capnp_ts_1.Struct.disown(this.getType()); + } + getType() { + return capnp_ts_1.Struct.getStruct(1, Worker_Binding_Type, this); + } + hasType() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initType() { + return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_Type, this); + } + setType(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getOptional() { + return capnp_ts_1.Struct.getBit(16, this); + } + setOptional(value) { + capnp_ts_1.Struct.setBit(16, value, this); + } + toString() { + return "Worker_Binding_Parameter_" + super.toString(); + } + }; + exports.Worker_Binding_Parameter = Worker_Binding_Parameter; + Worker_Binding_Parameter._capnp = { displayName: "parameter", id: "dc57e1258d26d152", size: new capnp_ts_1.ObjectSize(8, 6) }; + var Worker_Binding_Hyperdrive = class extends capnp_ts_1.Struct { + adoptDesignator(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownDesignator() { + return capnp_ts_1.Struct.disown(this.getDesignator()); + } + getDesignator() { + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasDesignator() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initDesignator() { + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + setDesignator(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getDatabase() { + return capnp_ts_1.Struct.getText(2, this); + } + setDatabase(value) { + capnp_ts_1.Struct.setText(2, value, this); + } + getUser() { + return capnp_ts_1.Struct.getText(3, this); + } + setUser(value) { + capnp_ts_1.Struct.setText(3, value, this); + } + getPassword() { + return capnp_ts_1.Struct.getText(4, this); + } + setPassword(value) { + capnp_ts_1.Struct.setText(4, value, this); + } + getScheme() { + return capnp_ts_1.Struct.getText(5, this); + } + setScheme(value) { + capnp_ts_1.Struct.setText(5, value, this); + } + toString() { + return "Worker_Binding_Hyperdrive_" + super.toString(); + } + }; + exports.Worker_Binding_Hyperdrive = Worker_Binding_Hyperdrive; + Worker_Binding_Hyperdrive._capnp = { displayName: "hyperdrive", id: "ad6c391cd55f3134", size: new capnp_ts_1.ObjectSize(8, 6) }; + var Worker_Binding_MemoryCache = class extends capnp_ts_1.Struct { + getId() { + return capnp_ts_1.Struct.getText(1, this); + } + setId(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + adoptLimits(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownLimits() { + return capnp_ts_1.Struct.disown(this.getLimits()); + } + getLimits() { + return capnp_ts_1.Struct.getStruct(2, Worker_Binding_MemoryCacheLimits, this); + } + hasLimits() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initLimits() { + return capnp_ts_1.Struct.initStructAt(2, Worker_Binding_MemoryCacheLimits, this); + } + setLimits(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + toString() { + return "Worker_Binding_MemoryCache_" + super.toString(); + } + }; + exports.Worker_Binding_MemoryCache = Worker_Binding_MemoryCache; + Worker_Binding_MemoryCache._capnp = { displayName: "memoryCache", id: "aed5760c349869da", size: new capnp_ts_1.ObjectSize(8, 6) }; + var Worker_Binding_Which; + (function(Worker_Binding_Which2) { + Worker_Binding_Which2[Worker_Binding_Which2["UNSPECIFIED"] = 0] = "UNSPECIFIED"; + Worker_Binding_Which2[Worker_Binding_Which2["PARAMETER"] = 1] = "PARAMETER"; + Worker_Binding_Which2[Worker_Binding_Which2["TEXT"] = 2] = "TEXT"; + Worker_Binding_Which2[Worker_Binding_Which2["DATA"] = 3] = "DATA"; + Worker_Binding_Which2[Worker_Binding_Which2["JSON"] = 4] = "JSON"; + Worker_Binding_Which2[Worker_Binding_Which2["WASM_MODULE"] = 5] = "WASM_MODULE"; + Worker_Binding_Which2[Worker_Binding_Which2["CRYPTO_KEY"] = 6] = "CRYPTO_KEY"; + Worker_Binding_Which2[Worker_Binding_Which2["SERVICE"] = 7] = "SERVICE"; + Worker_Binding_Which2[Worker_Binding_Which2["DURABLE_OBJECT_NAMESPACE"] = 8] = "DURABLE_OBJECT_NAMESPACE"; + Worker_Binding_Which2[Worker_Binding_Which2["KV_NAMESPACE"] = 9] = "KV_NAMESPACE"; + Worker_Binding_Which2[Worker_Binding_Which2["R2BUCKET"] = 10] = "R2BUCKET"; + Worker_Binding_Which2[Worker_Binding_Which2["R2ADMIN"] = 11] = "R2ADMIN"; + Worker_Binding_Which2[Worker_Binding_Which2["WRAPPED"] = 12] = "WRAPPED"; + Worker_Binding_Which2[Worker_Binding_Which2["QUEUE"] = 13] = "QUEUE"; + Worker_Binding_Which2[Worker_Binding_Which2["FROM_ENVIRONMENT"] = 14] = "FROM_ENVIRONMENT"; + Worker_Binding_Which2[Worker_Binding_Which2["ANALYTICS_ENGINE"] = 15] = "ANALYTICS_ENGINE"; + Worker_Binding_Which2[Worker_Binding_Which2["HYPERDRIVE"] = 16] = "HYPERDRIVE"; + Worker_Binding_Which2[Worker_Binding_Which2["UNSAFE_EVAL"] = 17] = "UNSAFE_EVAL"; + Worker_Binding_Which2[Worker_Binding_Which2["MEMORY_CACHE"] = 18] = "MEMORY_CACHE"; + })(Worker_Binding_Which = exports.Worker_Binding_Which || (exports.Worker_Binding_Which = {})); + var Worker_Binding4 = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + isUnspecified() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setUnspecified() { + capnp_ts_1.Struct.setUint16(0, 0, this); + } + getParameter() { + capnp_ts_1.Struct.testWhich("parameter", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getAs(Worker_Binding_Parameter, this); + } + initParameter() { + capnp_ts_1.Struct.setUint16(0, 1, this); + return capnp_ts_1.Struct.getAs(Worker_Binding_Parameter, this); + } + isParameter() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setParameter() { + capnp_ts_1.Struct.setUint16(0, 1, this); + } + getText() { + capnp_ts_1.Struct.testWhich("text", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getText(1, this); + } + isText() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setText(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.setText(1, value, this); + } + adoptData(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownData() { + return capnp_ts_1.Struct.disown(this.getData()); + } + getData() { + capnp_ts_1.Struct.testWhich("data", capnp_ts_1.Struct.getUint16(0, this), 3, this); + return capnp_ts_1.Struct.getData(1, this); + } + hasData() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initData(length) { + capnp_ts_1.Struct.setUint16(0, 3, this); + return capnp_ts_1.Struct.initData(1, length, this); + } + isData() { + return capnp_ts_1.Struct.getUint16(0, this) === 3; + } + setData(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getJson() { + capnp_ts_1.Struct.testWhich("json", capnp_ts_1.Struct.getUint16(0, this), 4, this); + return capnp_ts_1.Struct.getText(1, this); + } + isJson() { + return capnp_ts_1.Struct.getUint16(0, this) === 4; + } + setJson(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.setText(1, value, this); + } + adoptWasmModule(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownWasmModule() { + return capnp_ts_1.Struct.disown(this.getWasmModule()); + } + getWasmModule() { + capnp_ts_1.Struct.testWhich("wasmModule", capnp_ts_1.Struct.getUint16(0, this), 5, this); + return capnp_ts_1.Struct.getData(1, this); + } + hasWasmModule() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initWasmModule(length) { + capnp_ts_1.Struct.setUint16(0, 5, this); + return capnp_ts_1.Struct.initData(1, length, this); + } + isWasmModule() { + return capnp_ts_1.Struct.getUint16(0, this) === 5; + } + setWasmModule(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptCryptoKey(value) { + capnp_ts_1.Struct.setUint16(0, 6, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownCryptoKey() { + return capnp_ts_1.Struct.disown(this.getCryptoKey()); + } + getCryptoKey() { + capnp_ts_1.Struct.testWhich("cryptoKey", capnp_ts_1.Struct.getUint16(0, this), 6, this); + return capnp_ts_1.Struct.getStruct(1, Worker_Binding_CryptoKey, this); + } + hasCryptoKey() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initCryptoKey() { + capnp_ts_1.Struct.setUint16(0, 6, this); + return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_CryptoKey, this); + } + isCryptoKey() { + return capnp_ts_1.Struct.getUint16(0, this) === 6; + } + setCryptoKey(value) { + capnp_ts_1.Struct.setUint16(0, 6, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptService(value) { + capnp_ts_1.Struct.setUint16(0, 7, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownService() { + return capnp_ts_1.Struct.disown(this.getService()); + } + getService() { + capnp_ts_1.Struct.testWhich("service", capnp_ts_1.Struct.getUint16(0, this), 7, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasService() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initService() { + capnp_ts_1.Struct.setUint16(0, 7, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isService() { + return capnp_ts_1.Struct.getUint16(0, this) === 7; + } + setService(value) { + capnp_ts_1.Struct.setUint16(0, 7, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptDurableObjectNamespace(value) { + capnp_ts_1.Struct.setUint16(0, 8, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownDurableObjectNamespace() { + return capnp_ts_1.Struct.disown(this.getDurableObjectNamespace()); + } + getDurableObjectNamespace() { + capnp_ts_1.Struct.testWhich("durableObjectNamespace", capnp_ts_1.Struct.getUint16(0, this), 8, this); + return capnp_ts_1.Struct.getStruct(1, Worker_Binding_DurableObjectNamespaceDesignator2, this); + } + hasDurableObjectNamespace() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initDurableObjectNamespace() { + capnp_ts_1.Struct.setUint16(0, 8, this); + return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_DurableObjectNamespaceDesignator2, this); + } + isDurableObjectNamespace() { + return capnp_ts_1.Struct.getUint16(0, this) === 8; + } + setDurableObjectNamespace(value) { + capnp_ts_1.Struct.setUint16(0, 8, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptKvNamespace(value) { + capnp_ts_1.Struct.setUint16(0, 9, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownKvNamespace() { + return capnp_ts_1.Struct.disown(this.getKvNamespace()); + } + getKvNamespace() { + capnp_ts_1.Struct.testWhich("kvNamespace", capnp_ts_1.Struct.getUint16(0, this), 9, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasKvNamespace() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initKvNamespace() { + capnp_ts_1.Struct.setUint16(0, 9, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isKvNamespace() { + return capnp_ts_1.Struct.getUint16(0, this) === 9; + } + setKvNamespace(value) { + capnp_ts_1.Struct.setUint16(0, 9, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptR2Bucket(value) { + capnp_ts_1.Struct.setUint16(0, 10, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownR2Bucket() { + return capnp_ts_1.Struct.disown(this.getR2Bucket()); + } + getR2Bucket() { + capnp_ts_1.Struct.testWhich("r2Bucket", capnp_ts_1.Struct.getUint16(0, this), 10, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasR2Bucket() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initR2Bucket() { + capnp_ts_1.Struct.setUint16(0, 10, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isR2Bucket() { + return capnp_ts_1.Struct.getUint16(0, this) === 10; + } + setR2Bucket(value) { + capnp_ts_1.Struct.setUint16(0, 10, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptR2Admin(value) { + capnp_ts_1.Struct.setUint16(0, 11, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownR2Admin() { + return capnp_ts_1.Struct.disown(this.getR2Admin()); + } + getR2Admin() { + capnp_ts_1.Struct.testWhich("r2Admin", capnp_ts_1.Struct.getUint16(0, this), 11, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasR2Admin() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initR2Admin() { + capnp_ts_1.Struct.setUint16(0, 11, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isR2Admin() { + return capnp_ts_1.Struct.getUint16(0, this) === 11; + } + setR2Admin(value) { + capnp_ts_1.Struct.setUint16(0, 11, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptWrapped(value) { + capnp_ts_1.Struct.setUint16(0, 12, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownWrapped() { + return capnp_ts_1.Struct.disown(this.getWrapped()); + } + getWrapped() { + capnp_ts_1.Struct.testWhich("wrapped", capnp_ts_1.Struct.getUint16(0, this), 12, this); + return capnp_ts_1.Struct.getStruct(1, Worker_Binding_WrappedBinding, this); + } + hasWrapped() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initWrapped() { + capnp_ts_1.Struct.setUint16(0, 12, this); + return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_WrappedBinding, this); + } + isWrapped() { + return capnp_ts_1.Struct.getUint16(0, this) === 12; + } + setWrapped(value) { + capnp_ts_1.Struct.setUint16(0, 12, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptQueue(value) { + capnp_ts_1.Struct.setUint16(0, 13, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownQueue() { + return capnp_ts_1.Struct.disown(this.getQueue()); + } + getQueue() { + capnp_ts_1.Struct.testWhich("queue", capnp_ts_1.Struct.getUint16(0, this), 13, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasQueue() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initQueue() { + capnp_ts_1.Struct.setUint16(0, 13, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isQueue() { + return capnp_ts_1.Struct.getUint16(0, this) === 13; + } + setQueue(value) { + capnp_ts_1.Struct.setUint16(0, 13, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getFromEnvironment() { + capnp_ts_1.Struct.testWhich("fromEnvironment", capnp_ts_1.Struct.getUint16(0, this), 14, this); + return capnp_ts_1.Struct.getText(1, this); + } + isFromEnvironment() { + return capnp_ts_1.Struct.getUint16(0, this) === 14; + } + setFromEnvironment(value) { + capnp_ts_1.Struct.setUint16(0, 14, this); + capnp_ts_1.Struct.setText(1, value, this); + } + adoptAnalyticsEngine(value) { + capnp_ts_1.Struct.setUint16(0, 15, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownAnalyticsEngine() { + return capnp_ts_1.Struct.disown(this.getAnalyticsEngine()); + } + getAnalyticsEngine() { + capnp_ts_1.Struct.testWhich("analyticsEngine", capnp_ts_1.Struct.getUint16(0, this), 15, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasAnalyticsEngine() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initAnalyticsEngine() { + capnp_ts_1.Struct.setUint16(0, 15, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isAnalyticsEngine() { + return capnp_ts_1.Struct.getUint16(0, this) === 15; + } + setAnalyticsEngine(value) { + capnp_ts_1.Struct.setUint16(0, 15, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getHyperdrive() { + capnp_ts_1.Struct.testWhich("hyperdrive", capnp_ts_1.Struct.getUint16(0, this), 16, this); + return capnp_ts_1.Struct.getAs(Worker_Binding_Hyperdrive, this); + } + initHyperdrive() { + capnp_ts_1.Struct.setUint16(0, 16, this); + return capnp_ts_1.Struct.getAs(Worker_Binding_Hyperdrive, this); + } + isHyperdrive() { + return capnp_ts_1.Struct.getUint16(0, this) === 16; + } + setHyperdrive() { + capnp_ts_1.Struct.setUint16(0, 16, this); + } + isUnsafeEval() { + return capnp_ts_1.Struct.getUint16(0, this) === 17; + } + setUnsafeEval() { + capnp_ts_1.Struct.setUint16(0, 17, this); + } + getMemoryCache() { + capnp_ts_1.Struct.testWhich("memoryCache", capnp_ts_1.Struct.getUint16(0, this), 18, this); + return capnp_ts_1.Struct.getAs(Worker_Binding_MemoryCache, this); + } + initMemoryCache() { + capnp_ts_1.Struct.setUint16(0, 18, this); + return capnp_ts_1.Struct.getAs(Worker_Binding_MemoryCache, this); + } + isMemoryCache() { + return capnp_ts_1.Struct.getUint16(0, this) === 18; + } + setMemoryCache() { + capnp_ts_1.Struct.setUint16(0, 18, this); + } + toString() { + return "Worker_Binding_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker_Binding = Worker_Binding4; + Worker_Binding4.UNSPECIFIED = Worker_Binding_Which.UNSPECIFIED; + Worker_Binding4.PARAMETER = Worker_Binding_Which.PARAMETER; + Worker_Binding4.TEXT = Worker_Binding_Which.TEXT; + Worker_Binding4.DATA = Worker_Binding_Which.DATA; + Worker_Binding4.JSON = Worker_Binding_Which.JSON; + Worker_Binding4.WASM_MODULE = Worker_Binding_Which.WASM_MODULE; + Worker_Binding4.CRYPTO_KEY = Worker_Binding_Which.CRYPTO_KEY; + Worker_Binding4.SERVICE = Worker_Binding_Which.SERVICE; + Worker_Binding4.DURABLE_OBJECT_NAMESPACE = Worker_Binding_Which.DURABLE_OBJECT_NAMESPACE; + Worker_Binding4.KV_NAMESPACE = Worker_Binding_Which.KV_NAMESPACE; + Worker_Binding4.R2BUCKET = Worker_Binding_Which.R2BUCKET; + Worker_Binding4.R2ADMIN = Worker_Binding_Which.R2ADMIN; + Worker_Binding4.WRAPPED = Worker_Binding_Which.WRAPPED; + Worker_Binding4.QUEUE = Worker_Binding_Which.QUEUE; + Worker_Binding4.FROM_ENVIRONMENT = Worker_Binding_Which.FROM_ENVIRONMENT; + Worker_Binding4.ANALYTICS_ENGINE = Worker_Binding_Which.ANALYTICS_ENGINE; + Worker_Binding4.HYPERDRIVE = Worker_Binding_Which.HYPERDRIVE; + Worker_Binding4.UNSAFE_EVAL = Worker_Binding_Which.UNSAFE_EVAL; + Worker_Binding4.MEMORY_CACHE = Worker_Binding_Which.MEMORY_CACHE; + Worker_Binding4.Type = Worker_Binding_Type; + Worker_Binding4.DurableObjectNamespaceDesignator = Worker_Binding_DurableObjectNamespaceDesignator2; + Worker_Binding4.CryptoKey = Worker_Binding_CryptoKey; + Worker_Binding4.MemoryCacheLimits = Worker_Binding_MemoryCacheLimits; + Worker_Binding4.WrappedBinding = Worker_Binding_WrappedBinding; + Worker_Binding4._capnp = { displayName: "Binding", id: "8e7e492fd7e35f3e", size: new capnp_ts_1.ObjectSize(8, 6) }; + var Worker_DurableObjectNamespace_Which; + (function(Worker_DurableObjectNamespace_Which2) { + Worker_DurableObjectNamespace_Which2[Worker_DurableObjectNamespace_Which2["UNIQUE_KEY"] = 0] = "UNIQUE_KEY"; + Worker_DurableObjectNamespace_Which2[Worker_DurableObjectNamespace_Which2["EPHEMERAL_LOCAL"] = 1] = "EPHEMERAL_LOCAL"; + })(Worker_DurableObjectNamespace_Which = exports.Worker_DurableObjectNamespace_Which || (exports.Worker_DurableObjectNamespace_Which = {})); + var Worker_DurableObjectNamespace2 = class extends capnp_ts_1.Struct { + getClassName() { + return capnp_ts_1.Struct.getText(0, this); + } + setClassName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getUniqueKey() { + capnp_ts_1.Struct.testWhich("uniqueKey", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getText(1, this); + } + isUniqueKey() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setUniqueKey(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.setText(1, value, this); + } + isEphemeralLocal() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setEphemeralLocal() { + capnp_ts_1.Struct.setUint16(0, 1, this); + } + getPreventEviction() { + return capnp_ts_1.Struct.getBit(16, this); + } + setPreventEviction(value) { + capnp_ts_1.Struct.setBit(16, value, this); + } + toString() { + return "Worker_DurableObjectNamespace_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker_DurableObjectNamespace = Worker_DurableObjectNamespace2; + Worker_DurableObjectNamespace2.UNIQUE_KEY = Worker_DurableObjectNamespace_Which.UNIQUE_KEY; + Worker_DurableObjectNamespace2.EPHEMERAL_LOCAL = Worker_DurableObjectNamespace_Which.EPHEMERAL_LOCAL; + Worker_DurableObjectNamespace2._capnp = { displayName: "DurableObjectNamespace", id: "b429dd547d15747d", size: new capnp_ts_1.ObjectSize(8, 2) }; + var Worker_DurableObjectStorage_Which; + (function(Worker_DurableObjectStorage_Which2) { + Worker_DurableObjectStorage_Which2[Worker_DurableObjectStorage_Which2["NONE"] = 0] = "NONE"; + Worker_DurableObjectStorage_Which2[Worker_DurableObjectStorage_Which2["IN_MEMORY"] = 1] = "IN_MEMORY"; + Worker_DurableObjectStorage_Which2[Worker_DurableObjectStorage_Which2["LOCAL_DISK"] = 2] = "LOCAL_DISK"; + })(Worker_DurableObjectStorage_Which = exports.Worker_DurableObjectStorage_Which || (exports.Worker_DurableObjectStorage_Which = {})); + var Worker_DurableObjectStorage = class extends capnp_ts_1.Struct { + isNone() { + return capnp_ts_1.Struct.getUint16(2, this) === 0; + } + setNone() { + capnp_ts_1.Struct.setUint16(2, 0, this); + } + isInMemory() { + return capnp_ts_1.Struct.getUint16(2, this) === 1; + } + setInMemory() { + capnp_ts_1.Struct.setUint16(2, 1, this); + } + getLocalDisk() { + capnp_ts_1.Struct.testWhich("localDisk", capnp_ts_1.Struct.getUint16(2, this), 2, this); + return capnp_ts_1.Struct.getText(8, this); + } + isLocalDisk() { + return capnp_ts_1.Struct.getUint16(2, this) === 2; + } + setLocalDisk(value) { + capnp_ts_1.Struct.setUint16(2, 2, this); + capnp_ts_1.Struct.setText(8, value, this); + } + toString() { + return "Worker_DurableObjectStorage_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(2, this); + } + }; + exports.Worker_DurableObjectStorage = Worker_DurableObjectStorage; + Worker_DurableObjectStorage.NONE = Worker_DurableObjectStorage_Which.NONE; + Worker_DurableObjectStorage.IN_MEMORY = Worker_DurableObjectStorage_Which.IN_MEMORY; + Worker_DurableObjectStorage.LOCAL_DISK = Worker_DurableObjectStorage_Which.LOCAL_DISK; + Worker_DurableObjectStorage._capnp = { displayName: "durableObjectStorage", id: "cc72b3faa57827d4", size: new capnp_ts_1.ObjectSize(8, 10) }; + var Worker_Which; + (function(Worker_Which2) { + Worker_Which2[Worker_Which2["MODULES"] = 0] = "MODULES"; + Worker_Which2[Worker_Which2["SERVICE_WORKER_SCRIPT"] = 1] = "SERVICE_WORKER_SCRIPT"; + Worker_Which2[Worker_Which2["INHERIT"] = 2] = "INHERIT"; + })(Worker_Which = exports.Worker_Which || (exports.Worker_Which = {})); + var Worker2 = class extends capnp_ts_1.Struct { + adoptModules(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownModules() { + return capnp_ts_1.Struct.disown(this.getModules()); + } + getModules() { + capnp_ts_1.Struct.testWhich("modules", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getList(0, Worker2._Modules, this); + } + hasModules() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initModules(length) { + capnp_ts_1.Struct.setUint16(0, 0, this); + return capnp_ts_1.Struct.initList(0, Worker2._Modules, length, this); + } + isModules() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setModules(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + getServiceWorkerScript() { + capnp_ts_1.Struct.testWhich("serviceWorkerScript", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getText(0, this); + } + isServiceWorkerScript() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setServiceWorkerScript(value) { + capnp_ts_1.Struct.setUint16(0, 1, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getInherit() { + capnp_ts_1.Struct.testWhich("inherit", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getText(0, this); + } + isInherit() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setInherit(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getCompatibilityDate() { + return capnp_ts_1.Struct.getText(1, this); + } + setCompatibilityDate(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + adoptCompatibilityFlags(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownCompatibilityFlags() { + return capnp_ts_1.Struct.disown(this.getCompatibilityFlags()); + } + getCompatibilityFlags() { + return capnp_ts_1.Struct.getList(2, capnp.TextList, this); + } + hasCompatibilityFlags() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initCompatibilityFlags(length) { + return capnp_ts_1.Struct.initList(2, capnp.TextList, length, this); + } + setCompatibilityFlags(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + adoptBindings(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this)); + } + disownBindings() { + return capnp_ts_1.Struct.disown(this.getBindings()); + } + getBindings() { + return capnp_ts_1.Struct.getList(3, Worker2._Bindings, this); + } + hasBindings() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this)); + } + initBindings(length) { + return capnp_ts_1.Struct.initList(3, Worker2._Bindings, length, this); + } + setBindings(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this)); + } + adoptGlobalOutbound(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(4, this)); + } + disownGlobalOutbound() { + return capnp_ts_1.Struct.disown(this.getGlobalOutbound()); + } + getGlobalOutbound() { + return capnp_ts_1.Struct.getStruct(4, ServiceDesignator2, this, Worker2._capnp.defaultGlobalOutbound); + } + hasGlobalOutbound() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(4, this)); + } + initGlobalOutbound() { + return capnp_ts_1.Struct.initStructAt(4, ServiceDesignator2, this); + } + setGlobalOutbound(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(4, this)); + } + adoptCacheApiOutbound(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(7, this)); + } + disownCacheApiOutbound() { + return capnp_ts_1.Struct.disown(this.getCacheApiOutbound()); + } + getCacheApiOutbound() { + return capnp_ts_1.Struct.getStruct(7, ServiceDesignator2, this); + } + hasCacheApiOutbound() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(7, this)); + } + initCacheApiOutbound() { + return capnp_ts_1.Struct.initStructAt(7, ServiceDesignator2, this); + } + setCacheApiOutbound(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(7, this)); + } + adoptDurableObjectNamespaces(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(5, this)); + } + disownDurableObjectNamespaces() { + return capnp_ts_1.Struct.disown(this.getDurableObjectNamespaces()); + } + getDurableObjectNamespaces() { + return capnp_ts_1.Struct.getList(5, Worker2._DurableObjectNamespaces, this); + } + hasDurableObjectNamespaces() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(5, this)); + } + initDurableObjectNamespaces(length) { + return capnp_ts_1.Struct.initList(5, Worker2._DurableObjectNamespaces, length, this); + } + setDurableObjectNamespaces(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(5, this)); + } + getDurableObjectUniqueKeyModifier() { + return capnp_ts_1.Struct.getText(6, this); + } + setDurableObjectUniqueKeyModifier(value) { + capnp_ts_1.Struct.setText(6, value, this); + } + getDurableObjectStorage() { + return capnp_ts_1.Struct.getAs(Worker_DurableObjectStorage, this); + } + initDurableObjectStorage() { + return capnp_ts_1.Struct.getAs(Worker_DurableObjectStorage, this); + } + getModuleFallback() { + return capnp_ts_1.Struct.getText(9, this); + } + setModuleFallback(value) { + capnp_ts_1.Struct.setText(9, value, this); + } + toString() { + return "Worker_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker = Worker2; + Worker2.MODULES = Worker_Which.MODULES; + Worker2.SERVICE_WORKER_SCRIPT = Worker_Which.SERVICE_WORKER_SCRIPT; + Worker2.INHERIT = Worker_Which.INHERIT; + Worker2.Module = Worker_Module3; + Worker2.Binding = Worker_Binding4; + Worker2.DurableObjectNamespace = Worker_DurableObjectNamespace2; + Worker2._capnp = { displayName: "Worker", id: "acfa77e88fd97d1c", size: new capnp_ts_1.ObjectSize(8, 10), defaultGlobalOutbound: capnp.readRawPointer(new Uint8Array([16, 5, 64, 2, 17, 5, 74, 0, 0, 255, 105, 110, 116, 101, 114, 110, 101, 116, 0, 0, 0]).buffer) }; + var ExternalServer_Https = class extends capnp_ts_1.Struct { + adoptOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownOptions() { + return capnp_ts_1.Struct.disown(this.getOptions()); + } + getOptions() { + return capnp_ts_1.Struct.getStruct(1, HttpOptions, this); + } + hasOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initOptions() { + return capnp_ts_1.Struct.initStructAt(1, HttpOptions, this); + } + setOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptTlsOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownTlsOptions() { + return capnp_ts_1.Struct.disown(this.getTlsOptions()); + } + getTlsOptions() { + return capnp_ts_1.Struct.getStruct(2, TlsOptions, this); + } + hasTlsOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initTlsOptions() { + return capnp_ts_1.Struct.initStructAt(2, TlsOptions, this); + } + setTlsOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + getCertificateHost() { + return capnp_ts_1.Struct.getText(3, this); + } + setCertificateHost(value) { + capnp_ts_1.Struct.setText(3, value, this); + } + toString() { + return "ExternalServer_Https_" + super.toString(); + } + }; + exports.ExternalServer_Https = ExternalServer_Https; + ExternalServer_Https._capnp = { displayName: "https", id: "ac37e02afd3dc6db", size: new capnp_ts_1.ObjectSize(8, 4) }; + var ExternalServer_Tcp = class extends capnp_ts_1.Struct { + adoptTlsOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownTlsOptions() { + return capnp_ts_1.Struct.disown(this.getTlsOptions()); + } + getTlsOptions() { + return capnp_ts_1.Struct.getStruct(1, TlsOptions, this); + } + hasTlsOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initTlsOptions() { + return capnp_ts_1.Struct.initStructAt(1, TlsOptions, this); + } + setTlsOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getCertificateHost() { + return capnp_ts_1.Struct.getText(2, this); + } + setCertificateHost(value) { + capnp_ts_1.Struct.setText(2, value, this); + } + toString() { + return "ExternalServer_Tcp_" + super.toString(); + } + }; + exports.ExternalServer_Tcp = ExternalServer_Tcp; + ExternalServer_Tcp._capnp = { displayName: "tcp", id: "d941637df0fb39f1", size: new capnp_ts_1.ObjectSize(8, 4) }; + var ExternalServer_Which; + (function(ExternalServer_Which2) { + ExternalServer_Which2[ExternalServer_Which2["HTTP"] = 0] = "HTTP"; + ExternalServer_Which2[ExternalServer_Which2["HTTPS"] = 1] = "HTTPS"; + ExternalServer_Which2[ExternalServer_Which2["TCP"] = 2] = "TCP"; + })(ExternalServer_Which = exports.ExternalServer_Which || (exports.ExternalServer_Which = {})); + var ExternalServer2 = class extends capnp_ts_1.Struct { + getAddress() { + return capnp_ts_1.Struct.getText(0, this); + } + setAddress(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + adoptHttp(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownHttp() { + return capnp_ts_1.Struct.disown(this.getHttp()); + } + getHttp() { + capnp_ts_1.Struct.testWhich("http", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getStruct(1, HttpOptions, this); + } + hasHttp() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initHttp() { + capnp_ts_1.Struct.setUint16(0, 0, this); + return capnp_ts_1.Struct.initStructAt(1, HttpOptions, this); + } + isHttp() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setHttp(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getHttps() { + capnp_ts_1.Struct.testWhich("https", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getAs(ExternalServer_Https, this); + } + initHttps() { + capnp_ts_1.Struct.setUint16(0, 1, this); + return capnp_ts_1.Struct.getAs(ExternalServer_Https, this); + } + isHttps() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setHttps() { + capnp_ts_1.Struct.setUint16(0, 1, this); + } + getTcp() { + capnp_ts_1.Struct.testWhich("tcp", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getAs(ExternalServer_Tcp, this); + } + initTcp() { + capnp_ts_1.Struct.setUint16(0, 2, this); + return capnp_ts_1.Struct.getAs(ExternalServer_Tcp, this); + } + isTcp() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setTcp() { + capnp_ts_1.Struct.setUint16(0, 2, this); + } + toString() { + return "ExternalServer_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.ExternalServer = ExternalServer2; + ExternalServer2.HTTP = ExternalServer_Which.HTTP; + ExternalServer2.HTTPS = ExternalServer_Which.HTTPS; + ExternalServer2.TCP = ExternalServer_Which.TCP; + ExternalServer2._capnp = { displayName: "ExternalServer", id: "ff209f9aa352f5a4", size: new capnp_ts_1.ObjectSize(8, 4) }; + var Network = class extends capnp_ts_1.Struct { + adoptAllow(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownAllow() { + return capnp_ts_1.Struct.disown(this.getAllow()); + } + getAllow() { + return capnp_ts_1.Struct.getList(0, capnp.TextList, this, Network._capnp.defaultAllow); + } + hasAllow() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initAllow(length) { + return capnp_ts_1.Struct.initList(0, capnp.TextList, length, this); + } + setAllow(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + adoptDeny(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownDeny() { + return capnp_ts_1.Struct.disown(this.getDeny()); + } + getDeny() { + return capnp_ts_1.Struct.getList(1, capnp.TextList, this); + } + hasDeny() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initDeny(length) { + return capnp_ts_1.Struct.initList(1, capnp.TextList, length, this); + } + setDeny(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptTlsOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownTlsOptions() { + return capnp_ts_1.Struct.disown(this.getTlsOptions()); + } + getTlsOptions() { + return capnp_ts_1.Struct.getStruct(2, TlsOptions, this); + } + hasTlsOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initTlsOptions() { + return capnp_ts_1.Struct.initStructAt(2, TlsOptions, this); + } + setTlsOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + toString() { + return "Network_" + super.toString(); + } + }; + exports.Network = Network; + Network._capnp = { displayName: "Network", id: "fa42244f950c9b9c", size: new capnp_ts_1.ObjectSize(0, 3), defaultAllow: capnp.readRawPointer(new Uint8Array([16, 3, 17, 1, 14, 17, 1, 58, 63, 112, 117, 98, 108, 105, 99]).buffer) }; + var DiskDirectory = class extends capnp_ts_1.Struct { + getPath() { + return capnp_ts_1.Struct.getText(0, this); + } + setPath(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getWritable() { + return capnp_ts_1.Struct.getBit(0, this, DiskDirectory._capnp.defaultWritable); + } + setWritable(value) { + capnp_ts_1.Struct.setBit(0, value, this); + } + getAllowDotfiles() { + return capnp_ts_1.Struct.getBit(1, this, DiskDirectory._capnp.defaultAllowDotfiles); + } + setAllowDotfiles(value) { + capnp_ts_1.Struct.setBit(1, value, this); + } + toString() { + return "DiskDirectory_" + super.toString(); + } + }; + exports.DiskDirectory = DiskDirectory; + DiskDirectory._capnp = { displayName: "DiskDirectory", id: "9048ab22835f51c3", size: new capnp_ts_1.ObjectSize(8, 1), defaultWritable: capnp.getBitMask(false, 0), defaultAllowDotfiles: capnp.getBitMask(false, 1) }; + var HttpOptions_Style2; + (function(HttpOptions_Style3) { + HttpOptions_Style3[HttpOptions_Style3["HOST"] = 0] = "HOST"; + HttpOptions_Style3[HttpOptions_Style3["PROXY"] = 1] = "PROXY"; + })(HttpOptions_Style2 = exports.HttpOptions_Style || (exports.HttpOptions_Style = {})); + var HttpOptions_Header = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getValue() { + return capnp_ts_1.Struct.getText(1, this); + } + setValue(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "HttpOptions_Header_" + super.toString(); + } + }; + exports.HttpOptions_Header = HttpOptions_Header; + HttpOptions_Header._capnp = { displayName: "Header", id: "dc0394b5a6f3417e", size: new capnp_ts_1.ObjectSize(0, 2) }; + var HttpOptions = class extends capnp_ts_1.Struct { + getStyle() { + return capnp_ts_1.Struct.getUint16(0, this, HttpOptions._capnp.defaultStyle); + } + setStyle(value) { + capnp_ts_1.Struct.setUint16(0, value, this); + } + getForwardedProtoHeader() { + return capnp_ts_1.Struct.getText(0, this); + } + setForwardedProtoHeader(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getCfBlobHeader() { + return capnp_ts_1.Struct.getText(1, this); + } + setCfBlobHeader(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + adoptInjectRequestHeaders(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownInjectRequestHeaders() { + return capnp_ts_1.Struct.disown(this.getInjectRequestHeaders()); + } + getInjectRequestHeaders() { + return capnp_ts_1.Struct.getList(2, HttpOptions._InjectRequestHeaders, this); + } + hasInjectRequestHeaders() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initInjectRequestHeaders(length) { + return capnp_ts_1.Struct.initList(2, HttpOptions._InjectRequestHeaders, length, this); + } + setInjectRequestHeaders(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + adoptInjectResponseHeaders(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this)); + } + disownInjectResponseHeaders() { + return capnp_ts_1.Struct.disown(this.getInjectResponseHeaders()); + } + getInjectResponseHeaders() { + return capnp_ts_1.Struct.getList(3, HttpOptions._InjectResponseHeaders, this); + } + hasInjectResponseHeaders() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this)); + } + initInjectResponseHeaders(length) { + return capnp_ts_1.Struct.initList(3, HttpOptions._InjectResponseHeaders, length, this); + } + setInjectResponseHeaders(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this)); + } + getCapnpConnectHost() { + return capnp_ts_1.Struct.getText(4, this); + } + setCapnpConnectHost(value) { + capnp_ts_1.Struct.setText(4, value, this); + } + toString() { + return "HttpOptions_" + super.toString(); + } + }; + exports.HttpOptions = HttpOptions; + HttpOptions.Style = HttpOptions_Style2; + HttpOptions.Header = HttpOptions_Header; + HttpOptions._capnp = { displayName: "HttpOptions", id: "aa8dc6885da78f19", size: new capnp_ts_1.ObjectSize(8, 5), defaultStyle: capnp.getUint16Mask(0) }; + var TlsOptions_Keypair = class extends capnp_ts_1.Struct { + getPrivateKey() { + return capnp_ts_1.Struct.getText(0, this); + } + setPrivateKey(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getCertificateChain() { + return capnp_ts_1.Struct.getText(1, this); + } + setCertificateChain(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "TlsOptions_Keypair_" + super.toString(); + } + }; + exports.TlsOptions_Keypair = TlsOptions_Keypair; + TlsOptions_Keypair._capnp = { displayName: "Keypair", id: "f546bf2d5d8bd13e", size: new capnp_ts_1.ObjectSize(0, 2) }; + var TlsOptions_Version2; + (function(TlsOptions_Version3) { + TlsOptions_Version3[TlsOptions_Version3["GOOD_DEFAULT"] = 0] = "GOOD_DEFAULT"; + TlsOptions_Version3[TlsOptions_Version3["SSL3"] = 1] = "SSL3"; + TlsOptions_Version3[TlsOptions_Version3["TLS1DOT0"] = 2] = "TLS1DOT0"; + TlsOptions_Version3[TlsOptions_Version3["TLS1DOT1"] = 3] = "TLS1DOT1"; + TlsOptions_Version3[TlsOptions_Version3["TLS1DOT2"] = 4] = "TLS1DOT2"; + TlsOptions_Version3[TlsOptions_Version3["TLS1DOT3"] = 5] = "TLS1DOT3"; + })(TlsOptions_Version2 = exports.TlsOptions_Version || (exports.TlsOptions_Version = {})); + var TlsOptions = class extends capnp_ts_1.Struct { + adoptKeypair(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownKeypair() { + return capnp_ts_1.Struct.disown(this.getKeypair()); + } + getKeypair() { + return capnp_ts_1.Struct.getStruct(0, TlsOptions_Keypair, this); + } + hasKeypair() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initKeypair() { + return capnp_ts_1.Struct.initStructAt(0, TlsOptions_Keypair, this); + } + setKeypair(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + getRequireClientCerts() { + return capnp_ts_1.Struct.getBit(0, this, TlsOptions._capnp.defaultRequireClientCerts); + } + setRequireClientCerts(value) { + capnp_ts_1.Struct.setBit(0, value, this); + } + getTrustBrowserCas() { + return capnp_ts_1.Struct.getBit(1, this, TlsOptions._capnp.defaultTrustBrowserCas); + } + setTrustBrowserCas(value) { + capnp_ts_1.Struct.setBit(1, value, this); + } + adoptTrustedCertificates(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownTrustedCertificates() { + return capnp_ts_1.Struct.disown(this.getTrustedCertificates()); + } + getTrustedCertificates() { + return capnp_ts_1.Struct.getList(1, capnp.TextList, this); + } + hasTrustedCertificates() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initTrustedCertificates(length) { + return capnp_ts_1.Struct.initList(1, capnp.TextList, length, this); + } + setTrustedCertificates(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getMinVersion() { + return capnp_ts_1.Struct.getUint16(2, this, TlsOptions._capnp.defaultMinVersion); + } + setMinVersion(value) { + capnp_ts_1.Struct.setUint16(2, value, this); + } + getCipherList() { + return capnp_ts_1.Struct.getText(2, this); + } + setCipherList(value) { + capnp_ts_1.Struct.setText(2, value, this); + } + toString() { + return "TlsOptions_" + super.toString(); + } + }; + exports.TlsOptions = TlsOptions; + TlsOptions.Keypair = TlsOptions_Keypair; + TlsOptions.Version = TlsOptions_Version2; + TlsOptions._capnp = { displayName: "TlsOptions", id: "aabb3c3778ac4311", size: new capnp_ts_1.ObjectSize(8, 3), defaultRequireClientCerts: capnp.getBitMask(false, 0), defaultTrustBrowserCas: capnp.getBitMask(false, 1), defaultMinVersion: capnp.getUint16Mask(0) }; + var Extension_Module = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getInternal() { + return capnp_ts_1.Struct.getBit(0, this, Extension_Module._capnp.defaultInternal); + } + setInternal(value) { + capnp_ts_1.Struct.setBit(0, value, this); + } + getEsModule() { + return capnp_ts_1.Struct.getText(1, this); + } + setEsModule(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "Extension_Module_" + super.toString(); + } + }; + exports.Extension_Module = Extension_Module; + Extension_Module._capnp = { displayName: "Module", id: "d5d16e76fdedc37d", size: new capnp_ts_1.ObjectSize(8, 2), defaultInternal: capnp.getBitMask(false, 0) }; + var Extension3 = class extends capnp_ts_1.Struct { + adoptModules(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownModules() { + return capnp_ts_1.Struct.disown(this.getModules()); + } + getModules() { + return capnp_ts_1.Struct.getList(0, Extension3._Modules, this); + } + hasModules() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initModules(length) { + return capnp_ts_1.Struct.initList(0, Extension3._Modules, length, this); + } + setModules(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + toString() { + return "Extension_" + super.toString(); + } + }; + exports.Extension = Extension3; + Extension3.Module = Extension_Module; + Extension3._capnp = { displayName: "Extension", id: "e390128a861973a6", size: new capnp_ts_1.ObjectSize(0, 1) }; + Config3._Services = capnp.CompositeList(Service4); + Config3._Sockets = capnp.CompositeList(Socket2); + Config3._Extensions = capnp.CompositeList(Extension3); + Worker_Binding_WrappedBinding._InnerBindings = capnp.CompositeList(Worker_Binding4); + Worker2._Modules = capnp.CompositeList(Worker_Module3); + Worker2._Bindings = capnp.CompositeList(Worker_Binding4); + Worker2._DurableObjectNamespaces = capnp.CompositeList(Worker_DurableObjectNamespace2); + HttpOptions._InjectRequestHeaders = capnp.CompositeList(HttpOptions_Header); + HttpOptions._InjectResponseHeaders = capnp.CompositeList(HttpOptions_Header); + Extension3._Modules = capnp.CompositeList(Extension_Module); + } +}); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + CACHE_PLUGIN: () => CACHE_PLUGIN, + CACHE_PLUGIN_NAME: () => CACHE_PLUGIN_NAME, + CORE_PLUGIN: () => CORE_PLUGIN, + CORE_PLUGIN_NAME: () => CORE_PLUGIN_NAME2, + CacheBindings: () => CacheBindings, + CacheHeaders: () => CacheHeaders, + CacheOptionsSchema: () => CacheOptionsSchema, + CacheSharedOptionsSchema: () => CacheSharedOptionsSchema, + CloseEvent: () => CloseEvent, + CoreBindings: () => CoreBindings, + CoreHeaders: () => CoreHeaders, + CoreOptionsSchema: () => CoreOptionsSchema, + CoreSharedOptionsSchema: () => CoreSharedOptionsSchema, + D1OptionsSchema: () => D1OptionsSchema, + D1SharedOptionsSchema: () => D1SharedOptionsSchema, + D1_PLUGIN: () => D1_PLUGIN, + D1_PLUGIN_NAME: () => D1_PLUGIN_NAME, + DEFAULT_PERSIST_ROOT: () => DEFAULT_PERSIST_ROOT, + DURABLE_OBJECTS_PLUGIN: () => DURABLE_OBJECTS_PLUGIN, + DURABLE_OBJECTS_PLUGIN_NAME: () => DURABLE_OBJECTS_PLUGIN_NAME, + DURABLE_OBJECTS_STORAGE_SERVICE_NAME: () => DURABLE_OBJECTS_STORAGE_SERVICE_NAME, + DeferredPromise: () => DeferredPromise, + DispatchFetchDispatcher: () => DispatchFetchDispatcher, + DurableObjectsOptionsSchema: () => DurableObjectsOptionsSchema, + DurableObjectsSharedOptionsSchema: () => DurableObjectsSharedOptionsSchema, + ENTRY_SOCKET_HTTP_OPTIONS: () => ENTRY_SOCKET_HTTP_OPTIONS, + ErrorEvent: () => ErrorEvent, + File: () => import_undici5.File, + FormData: () => import_undici5.FormData, + HOST_CAPNP_CONNECT: () => HOST_CAPNP_CONNECT, + HYPERDRIVE_PLUGIN: () => HYPERDRIVE_PLUGIN, + HYPERDRIVE_PLUGIN_NAME: () => HYPERDRIVE_PLUGIN_NAME, + Headers: () => import_undici5.Headers, + HttpOptions_Style: () => import_workerd_capnp.HttpOptions_Style, + HyperdriveInputOptionsSchema: () => HyperdriveInputOptionsSchema, + HyperdriveSchema: () => HyperdriveSchema, + JsonSchema: () => JsonSchema, + KVHeaders: () => KVHeaders, + KVLimits: () => KVLimits, + KVOptionsSchema: () => KVOptionsSchema, + KVParams: () => KVParams, + KVSharedOptionsSchema: () => KVSharedOptionsSchema, + KV_PLUGIN: () => KV_PLUGIN, + KV_PLUGIN_NAME: () => KV_PLUGIN_NAME, + LiteralSchema: () => LiteralSchema, + Log: () => Log, + LogLevel: () => LogLevel, + MessageEvent: () => MessageEvent, + Miniflare: () => Miniflare2, + MiniflareCoreError: () => MiniflareCoreError, + MiniflareError: () => MiniflareError, + ModuleDefinitionSchema: () => ModuleDefinitionSchema, + ModuleRuleSchema: () => ModuleRuleSchema, + ModuleRuleTypeSchema: () => ModuleRuleTypeSchema, + Mutex: () => Mutex, + NoOpLog: () => NoOpLog, + PLUGINS: () => PLUGINS, + PLUGIN_ENTRIES: () => PLUGIN_ENTRIES, + PathSchema: () => PathSchema, + PeriodType: () => PeriodType, + PersistenceSchema: () => PersistenceSchema, + ProxyAddresses: () => ProxyAddresses, + ProxyClient: () => ProxyClient, + ProxyOps: () => ProxyOps, + QUEUES_PLUGIN: () => QUEUES_PLUGIN, + QUEUES_PLUGIN_NAME: () => QUEUES_PLUGIN_NAME, + QueueBindings: () => QueueBindings, + QueueConsumerOptionsSchema: () => QueueConsumerOptionsSchema, + QueueConsumerSchema: () => QueueConsumerSchema, + QueueConsumersSchema: () => QueueConsumersSchema, + QueueContentTypeSchema: () => QueueContentTypeSchema, + QueueIncomingMessageSchema: () => QueueIncomingMessageSchema, + QueueMessageDelaySchema: () => QueueMessageDelaySchema, + QueueProducerOptionsSchema: () => QueueProducerOptionsSchema, + QueueProducerSchema: () => QueueProducerSchema, + QueueProducersSchema: () => QueueProducersSchema, + QueuesBatchRequestSchema: () => QueuesBatchRequestSchema, + QueuesError: () => QueuesError, + QueuesOptionsSchema: () => QueuesOptionsSchema, + R2OptionsSchema: () => R2OptionsSchema, + R2SharedOptionsSchema: () => R2SharedOptionsSchema, + R2_PLUGIN: () => R2_PLUGIN, + R2_PLUGIN_NAME: () => R2_PLUGIN_NAME, + RATELIMIT_PLUGIN: () => RATELIMIT_PLUGIN, + RATELIMIT_PLUGIN_NAME: () => RATELIMIT_PLUGIN_NAME, + RatelimitConfigSchema: () => RatelimitConfigSchema, + RatelimitOptionsSchema: () => RatelimitOptionsSchema, + Request: () => Request, + Response: () => Response, + RouterError: () => RouterError, + Runtime: () => Runtime, + SERVICE_ENTRY: () => SERVICE_ENTRY, + SERVICE_LOOPBACK: () => SERVICE_LOOPBACK, + SITES_NO_CACHE_PREFIX: () => SITES_NO_CACHE_PREFIX, + SOCKET_ENTRY: () => SOCKET_ENTRY, + SOCKET_ENTRY_LOCAL: () => SOCKET_ENTRY_LOCAL, + SharedBindings: () => SharedBindings, + SharedHeaders: () => SharedHeaders, + SiteBindings: () => SiteBindings, + SourceOptionsSchema: () => SourceOptionsSchema, + TlsOptions_Version: () => import_workerd_capnp.TlsOptions_Version, + TypedEventTarget: () => TypedEventTarget, + WORKER_BINDING_SERVICE_LOOPBACK: () => WORKER_BINDING_SERVICE_LOOPBACK, + WaitGroup: () => WaitGroup, + WebSocket: () => WebSocket, + WebSocketPair: () => WebSocketPair, + Worker_Binding_CryptoKey_Usage: () => import_workerd_capnp.Worker_Binding_CryptoKey_Usage, + _enableControlEndpoints: () => _enableControlEndpoints, + _forceColour: () => _forceColour, + _initialiseInstanceRegistry: () => _initialiseInstanceRegistry, + _isCyclic: () => _isCyclic, + _transformsForContentEncoding: () => _transformsForContentEncoding, + base64Decode: () => base64Decode, + base64Encode: () => base64Encode, + compileModuleRules: () => compileModuleRules, + coupleWebSocket: () => coupleWebSocket, + createFetchMock: () => createFetchMock, + createHTTPReducers: () => createHTTPReducers, + createHTTPRevivers: () => createHTTPRevivers, + decodeSitesKey: () => decodeSitesKey, + deserialiseRegExps: () => deserialiseRegExps, + deserialiseSiteRegExps: () => deserialiseSiteRegExps, + encodeSitesKey: () => encodeSitesKey, + fetch: () => fetch2, + formatZodError: () => formatZodError, + getAccessibleHosts: () => getAccessibleHosts, + getCacheServiceName: () => getCacheServiceName, + getDirectSocketName: () => getDirectSocketName, + getEntrySocketHttpOptions: () => getEntrySocketHttpOptions, + getFreshSourceMapSupport: () => getFreshSourceMapSupport, + getGlobalServices: () => getGlobalServices, + getMiniflareObjectBindings: () => getMiniflareObjectBindings, + getPersistPath: () => getPersistPath, + getRootPath: () => getRootPath, + globsToRegExps: () => globsToRegExps, + isFetcherFetch: () => isFetcherFetch, + isR2ObjectWriteHttpMetadata: () => isR2ObjectWriteHttpMetadata, + isSitesRequest: () => isSitesRequest, + kCurrentWorker: () => kCurrentWorker, + kInspectorSocket: () => kInspectorSocket, + kProxyNodeBinding: () => kProxyNodeBinding, + kUnsafeEphemeralUniqueKey: () => kUnsafeEphemeralUniqueKey, + kVoid: () => kVoid, + matchRoutes: () => matchRoutes, + maybeApply: () => maybeApply, + maybeParseURL: () => maybeParseURL, + mergeWorkerOptions: () => mergeWorkerOptions, + migrateDatabase: () => migrateDatabase, + namespaceEntries: () => namespaceEntries, + namespaceKeys: () => namespaceKeys, + normaliseDurableObject: () => normaliseDurableObject, + objectEntryWorker: () => objectEntryWorker, + parseRanges: () => parseRanges, + parseRoutes: () => parseRoutes, + parseWithReadableStreams: () => parseWithReadableStreams, + parseWithRootPath: () => parseWithRootPath, + prefixError: () => prefixError, + prefixStream: () => prefixStream, + readPrefix: () => readPrefix, + reduceError: () => reduceError, + sanitisePath: () => sanitisePath, + serialiseRegExps: () => serialiseRegExps, + serialiseSiteRegExps: () => serialiseSiteRegExps, + serializeConfig: () => serializeConfig, + stringifyWithStreams: () => stringifyWithStreams, + stripAnsi: () => stripAnsi, + structuredSerializableReducers: () => structuredSerializableReducers, + structuredSerializableRevivers: () => structuredSerializableRevivers, + supportedCompatibilityDate: () => import_workerd2.compatibilityDate, + testRegExps: () => testRegExps, + testSiteRegExps: () => testSiteRegExps, + viewToBuffer: () => viewToBuffer, + zAwaitable: () => zAwaitable +}); +module.exports = __toCommonJS(src_exports); +var import_assert12 = __toESM(require("assert")); +var import_crypto3 = __toESM(require("crypto")); +var import_fs18 = __toESM(require("fs")); +var import_http6 = __toESM(require("http")); +var import_net = __toESM(require("net")); +var import_os2 = __toESM(require("os")); +var import_path22 = __toESM(require("path")); +var import_web5 = require("stream/web"); +var import_util5 = __toESM(require("util")); +var import_zlib = __toESM(require("zlib")); +var import_exit_hook = __toESM(require("exit-hook")); + +// ../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs +var FORCE_COLOR; +var NODE_DISABLE_COLORS; +var NO_COLOR; +var TERM; +var isTTY = true; +if (typeof process !== "undefined") { + ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}); + isTTY = process.stdout && process.stdout.isTTY; +} +var $ = { + enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY) +}; +function init(x, y) { + let rgx = new RegExp(`\\x1b\\[${y}m`, "g"); + let open = `\x1B[${x}m`, close = `\x1B[${y}m`; + return function(txt) { + if (!$.enabled || txt == null) + return txt; + return open + (!!~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close; + }; +} +var reset = init(0, 0); +var bold = init(1, 22); +var dim = init(2, 22); +var italic = init(3, 23); +var underline = init(4, 24); +var inverse = init(7, 27); +var hidden = init(8, 28); +var strikethrough = init(9, 29); +var black = init(30, 39); +var red = init(31, 39); +var green = init(32, 39); +var yellow = init(33, 39); +var blue = init(34, 39); +var magenta = init(35, 39); +var cyan = init(36, 39); +var white = init(37, 39); +var gray = init(90, 39); +var grey = init(90, 39); +var bgBlack = init(40, 49); +var bgRed = init(41, 49); +var bgGreen = init(42, 49); +var bgYellow = init(43, 49); +var bgBlue = init(44, 49); +var bgMagenta = init(45, 49); +var bgCyan = init(46, 49); +var bgWhite = init(47, 49); + +// src/index.ts +var import_stoppable = __toESM(require("stoppable")); +var import_undici9 = require("undici"); + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/index.worker.ts +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var import_url = __toESM(require("url")); +var contents; +function index_worker_default() { + if (contents !== void 0) + return contents; + const filePath = import_path.default.join(__dirname, "workers", "shared/index.worker.js"); + contents = import_fs.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url.default.pathToFileURL(filePath); + return contents; +} + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/zod.worker.ts +var import_fs2 = __toESM(require("fs")); +var import_path2 = __toESM(require("path")); +var import_url2 = __toESM(require("url")); +var contents2; +function zod_worker_default() { + if (contents2 !== void 0) + return contents2; + const filePath = import_path2.default.join(__dirname, "workers", "shared/zod.worker.js"); + contents2 = import_fs2.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url2.default.pathToFileURL(filePath); + return contents2; +} + +// src/index.ts +var import_ws3 = require("ws"); +var import_zod19 = require("zod"); + +// src/cf.ts +var import_assert = __toESM(require("assert")); +var import_promises = require("fs/promises"); +var import_path3 = __toESM(require("path")); +var import_undici = require("undici"); +var defaultCfPath = import_path3.default.resolve("node_modules", ".mf", "cf.json"); +var defaultCfFetchEndpoint = "https://workers.cloudflare.com/cf.json"; +var fallbackCf = { + asOrganization: "", + asn: 395747, + colo: "DFW", + city: "Austin", + region: "Texas", + regionCode: "TX", + metroCode: "635", + postalCode: "78701", + country: "US", + continent: "NA", + timezone: "America/Chicago", + latitude: "30.27130", + longitude: "-97.74260", + clientTcpRtt: 0, + httpProtocol: "HTTP/1.1", + requestPriority: "weight=192;exclusive=0", + tlsCipher: "AEAD-AES128-GCM-SHA256", + tlsVersion: "TLSv1.3", + tlsClientAuth: { + certPresented: "0", + certVerified: "NONE", + certRevoked: "0", + certIssuerDN: "", + certSubjectDN: "", + certIssuerDNRFC2253: "", + certSubjectDNRFC2253: "", + certIssuerDNLegacy: "", + certSubjectDNLegacy: "", + certSerial: "", + certIssuerSerial: "", + certSKI: "", + certIssuerSKI: "", + certFingerprintSHA1: "", + certFingerprintSHA256: "", + certNotBefore: "", + certNotAfter: "" + }, + edgeRequestKeepAliveStatus: 0, + hostMetadata: void 0, + clientTrustScore: 99, + botManagement: { + corporateProxy: false, + verifiedBot: false, + ja3Hash: "25b4882c2bcb50cd6b469ff28c596742", + staticResource: false, + detectionIds: [], + score: 99 + } +}; +var DAY = 864e5; +var CF_DAYS = 30; +async function setupCf(log, cf) { + if (!(cf ?? process.env.NODE_ENV !== "test")) { + return fallbackCf; + } + if (typeof cf === "object") { + return cf; + } + let cfPath = defaultCfPath; + if (typeof cf === "string") { + cfPath = cf; + } + try { + const storedCf = JSON.parse(await (0, import_promises.readFile)(cfPath, "utf8")); + const cfStat = await (0, import_promises.stat)(cfPath); + (0, import_assert.default)(Date.now() - cfStat.mtimeMs <= CF_DAYS * DAY); + return storedCf; + } catch { + } + try { + const res = await (0, import_undici.fetch)(defaultCfFetchEndpoint); + const cfText = await res.text(); + const storedCf = JSON.parse(cfText); + await (0, import_promises.mkdir)(import_path3.default.dirname(cfPath), { recursive: true }); + await (0, import_promises.writeFile)(cfPath, cfText, "utf8"); + log.debug("Updated `Request.cf` object cache!"); + return storedCf; + } catch (e) { + log.warn( + "Unable to fetch the `Request.cf` object! Falling back to a default placeholder...\n" + dim(e.cause ? e.cause.stack : e.stack) + ); + return fallbackCf; + } +} + +// src/http/fetch.ts +var import_undici4 = require("undici"); +var import_ws2 = __toESM(require("ws")); + +// src/workers/cache/constants.ts +var CacheHeaders = { + NAMESPACE: "cf-cache-namespace", + STATUS: "cf-cache-status" +}; +var CacheBindings = { + MAYBE_JSON_CACHE_WARN_USAGE: "MINIFLARE_CACHE_WARN_USAGE" +}; + +// src/workers/core/constants.ts +var CoreHeaders = { + CUSTOM_SERVICE: "MF-Custom-Service", + ORIGINAL_URL: "MF-Original-URL", + PROXY_SHARED_SECRET: "MF-Proxy-Shared-Secret", + DISABLE_PRETTY_ERROR: "MF-Disable-Pretty-Error", + ERROR_STACK: "MF-Experimental-Error-Stack", + ROUTE_OVERRIDE: "MF-Route-Override", + CF_BLOB: "MF-CF-Blob", + // API Proxy + OP_SECRET: "MF-Op-Secret", + OP: "MF-Op", + OP_TARGET: "MF-Op-Target", + OP_KEY: "MF-Op-Key", + OP_SYNC: "MF-Op-Sync", + OP_STRINGIFIED_SIZE: "MF-Op-Stringified-Size", + OP_RESULT_TYPE: "MF-Op-Result-Type" +}; +var CoreBindings = { + SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK", + SERVICE_USER_ROUTE_PREFIX: "MINIFLARE_USER_ROUTE_", + SERVICE_USER_FALLBACK: "MINIFLARE_USER_FALLBACK", + TEXT_CUSTOM_SERVICE: "MINIFLARE_CUSTOM_SERVICE", + TEXT_UPSTREAM_URL: "MINIFLARE_UPSTREAM_URL", + JSON_CF_BLOB: "CF_BLOB", + JSON_ROUTES: "MINIFLARE_ROUTES", + JSON_LOG_LEVEL: "MINIFLARE_LOG_LEVEL", + DATA_LIVE_RELOAD_SCRIPT: "MINIFLARE_LIVE_RELOAD_SCRIPT", + DURABLE_OBJECT_NAMESPACE_PROXY: "MINIFLARE_PROXY", + DATA_PROXY_SECRET: "MINIFLARE_PROXY_SECRET", + DATA_PROXY_SHARED_SECRET: "MINIFLARE_PROXY_SHARED_SECRET" +}; +var ProxyOps = { + // Get the target or a property of the target + GET: "GET", + // Get the descriptor for a property of the target + GET_OWN_DESCRIPTOR: "GET_OWN_DESCRIPTOR", + // Get the target's own property names + GET_OWN_KEYS: "GET_OWN_KEYS", + // Call a method on the target + CALL: "CALL", + // Remove the strong reference to the target on the "heap", allowing it to be + // garbage collected + FREE: "FREE" +}; +var ProxyAddresses = { + GLOBAL: 0, + // globalThis + ENV: 1, + // env + USER_START: 2 +}; +function isFetcherFetch(targetName, key) { + return (targetName === "Fetcher" || targetName === "DurableObject" || targetName === "WorkerRpc") && key === "fetch"; +} +function isR2ObjectWriteHttpMetadata(targetName, key) { + return (targetName === "HeadResult" || targetName === "GetResult") && key === "writeHttpMetadata"; +} + +// src/workers/core/devalue.ts +var import_node_assert = __toESM(require("node:assert")); +var import_node_buffer = require("node:buffer"); + +// ../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/utils.js +var DevalueError = class extends Error { + /** + * @param {string} message + * @param {string[]} keys + */ + constructor(message, keys) { + super(message); + this.name = "DevalueError"; + this.path = keys.join(""); + } +}; +function is_primitive(thing) { + return Object(thing) !== thing; +} +var object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames( + Object.prototype +).sort().join("\0"); +function is_plain_object(thing) { + const proto = Object.getPrototypeOf(thing); + return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names; +} +function get_type(thing) { + return Object.prototype.toString.call(thing).slice(8, -1); +} +function get_escaped_char(char) { + switch (char) { + case '"': + return '\\"'; + case "<": + return "\\u003C"; + case "\\": + return "\\\\"; + case "\n": + return "\\n"; + case "\r": + return "\\r"; + case " ": + return "\\t"; + case "\b": + return "\\b"; + case "\f": + return "\\f"; + case "\u2028": + return "\\u2028"; + case "\u2029": + return "\\u2029"; + default: + return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : ""; + } +} +function stringify_string(str) { + let result = ""; + let last_pos = 0; + const len = str.length; + for (let i = 0; i < len; i += 1) { + const char = str[i]; + const replacement = get_escaped_char(char); + if (replacement) { + result += str.slice(last_pos, i) + replacement; + last_pos = i + 1; + } + } + return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`; +} + +// ../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/constants.js +var UNDEFINED = -1; +var HOLE = -2; +var NAN = -3; +var POSITIVE_INFINITY = -4; +var NEGATIVE_INFINITY = -5; +var NEGATIVE_ZERO = -6; + +// ../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/parse.js +function parse(serialized, revivers2) { + return unflatten(JSON.parse(serialized), revivers2); +} +function unflatten(parsed, revivers2) { + if (typeof parsed === "number") + return hydrate(parsed, true); + if (!Array.isArray(parsed) || parsed.length === 0) { + throw new Error("Invalid input"); + } + const values = ( + /** @type {any[]} */ + parsed + ); + const hydrated = Array(values.length); + function hydrate(index, standalone = false) { + if (index === UNDEFINED) + return void 0; + if (index === NAN) + return NaN; + if (index === POSITIVE_INFINITY) + return Infinity; + if (index === NEGATIVE_INFINITY) + return -Infinity; + if (index === NEGATIVE_ZERO) + return -0; + if (standalone) + throw new Error(`Invalid input`); + if (index in hydrated) + return hydrated[index]; + const value = values[index]; + if (!value || typeof value !== "object") { + hydrated[index] = value; + } else if (Array.isArray(value)) { + if (typeof value[0] === "string") { + const type = value[0]; + const reviver = revivers2?.[type]; + if (reviver) { + return hydrated[index] = reviver(hydrate(value[1])); + } + switch (type) { + case "Date": + hydrated[index] = new Date(value[1]); + break; + case "Set": + const set = /* @__PURE__ */ new Set(); + hydrated[index] = set; + for (let i = 1; i < value.length; i += 1) { + set.add(hydrate(value[i])); + } + break; + case "Map": + const map = /* @__PURE__ */ new Map(); + hydrated[index] = map; + for (let i = 1; i < value.length; i += 2) { + map.set(hydrate(value[i]), hydrate(value[i + 1])); + } + break; + case "RegExp": + hydrated[index] = new RegExp(value[1], value[2]); + break; + case "Object": + hydrated[index] = Object(value[1]); + break; + case "BigInt": + hydrated[index] = BigInt(value[1]); + break; + case "null": + const obj = /* @__PURE__ */ Object.create(null); + hydrated[index] = obj; + for (let i = 1; i < value.length; i += 2) { + obj[value[i]] = hydrate(value[i + 1]); + } + break; + default: + throw new Error(`Unknown type ${type}`); + } + } else { + const array = new Array(value.length); + hydrated[index] = array; + for (let i = 0; i < value.length; i += 1) { + const n = value[i]; + if (n === HOLE) + continue; + array[i] = hydrate(n); + } + } + } else { + const object = {}; + hydrated[index] = object; + for (const key in value) { + const n = value[key]; + object[key] = hydrate(n); + } + } + return hydrated[index]; + } + return hydrate(0); +} + +// ../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/stringify.js +function stringify(value, reducers2) { + const stringified = []; + const indexes = /* @__PURE__ */ new Map(); + const custom = []; + for (const key in reducers2) { + custom.push({ key, fn: reducers2[key] }); + } + const keys = []; + let p = 0; + function flatten(thing) { + if (typeof thing === "function") { + throw new DevalueError(`Cannot stringify a function`, keys); + } + if (indexes.has(thing)) + return indexes.get(thing); + if (thing === void 0) + return UNDEFINED; + if (Number.isNaN(thing)) + return NAN; + if (thing === Infinity) + return POSITIVE_INFINITY; + if (thing === -Infinity) + return NEGATIVE_INFINITY; + if (thing === 0 && 1 / thing < 0) + return NEGATIVE_ZERO; + const index2 = p++; + indexes.set(thing, index2); + for (const { key, fn } of custom) { + const value2 = fn(thing); + if (value2) { + stringified[index2] = `["${key}",${flatten(value2)}]`; + return index2; + } + } + let str = ""; + if (is_primitive(thing)) { + str = stringify_primitive(thing); + } else { + const type = get_type(thing); + switch (type) { + case "Number": + case "String": + case "Boolean": + str = `["Object",${stringify_primitive(thing)}]`; + break; + case "BigInt": + str = `["BigInt",${thing}]`; + break; + case "Date": + str = `["Date","${thing.toISOString()}"]`; + break; + case "RegExp": + const { source, flags } = thing; + str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`; + break; + case "Array": + str = "["; + for (let i = 0; i < thing.length; i += 1) { + if (i > 0) + str += ","; + if (i in thing) { + keys.push(`[${i}]`); + str += flatten(thing[i]); + keys.pop(); + } else { + str += HOLE; + } + } + str += "]"; + break; + case "Set": + str = '["Set"'; + for (const value2 of thing) { + str += `,${flatten(value2)}`; + } + str += "]"; + break; + case "Map": + str = '["Map"'; + for (const [key, value2] of thing) { + keys.push( + `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})` + ); + str += `,${flatten(key)},${flatten(value2)}`; + } + str += "]"; + break; + default: + if (!is_plain_object(thing)) { + throw new DevalueError( + `Cannot stringify arbitrary non-POJOs`, + keys + ); + } + if (Object.getOwnPropertySymbols(thing).length > 0) { + throw new DevalueError( + `Cannot stringify POJOs with symbolic keys`, + keys + ); + } + if (Object.getPrototypeOf(thing) === null) { + str = '["null"'; + for (const key in thing) { + keys.push(`.${key}`); + str += `,${stringify_string(key)},${flatten(thing[key])}`; + keys.pop(); + } + str += "]"; + } else { + str = "{"; + let started = false; + for (const key in thing) { + if (started) + str += ","; + started = true; + keys.push(`.${key}`); + str += `${stringify_string(key)}:${flatten(thing[key])}`; + keys.pop(); + } + str += "}"; + } + } + } + stringified[index2] = str; + return index2; + } + const index = flatten(value); + if (index < 0) + return `${index}`; + return `[${stringified.join(",")}]`; +} +function stringify_primitive(thing) { + const type = typeof thing; + if (type === "string") + return stringify_string(thing); + if (thing instanceof String) + return stringify_string(thing.toString()); + if (thing === void 0) + return UNDEFINED.toString(); + if (thing === 0 && 1 / thing < 0) + return NEGATIVE_ZERO.toString(); + if (type === "bigint") + return `["BigInt","${thing}"]`; + return String(thing); +} + +// src/workers/core/devalue.ts +var ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS = [ + DataView, + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + BigInt64Array, + BigUint64Array +]; +var ALLOWED_ERROR_CONSTRUCTORS = [ + EvalError, + RangeError, + ReferenceError, + SyntaxError, + TypeError, + URIError, + Error + // `Error` last so more specific error subclasses preferred +]; +var structuredSerializableReducers = { + ArrayBuffer(value) { + if (value instanceof ArrayBuffer) { + return [import_node_buffer.Buffer.from(value).toString("base64")]; + } + }, + ArrayBufferView(value) { + if (ArrayBuffer.isView(value)) { + return [ + value.constructor.name, + value.buffer, + value.byteOffset, + value.byteLength + ]; + } + }, + Error(value) { + for (const ctor of ALLOWED_ERROR_CONSTRUCTORS) { + if (value instanceof ctor && value.name === ctor.name) { + return [value.name, value.message, value.stack, value.cause]; + } + } + if (value instanceof Error) { + return ["Error", value.message, value.stack, value.cause]; + } + } +}; +var structuredSerializableRevivers = { + ArrayBuffer(value) { + (0, import_node_assert.default)(Array.isArray(value)); + const [encoded] = value; + (0, import_node_assert.default)(typeof encoded === "string"); + const view = import_node_buffer.Buffer.from(encoded, "base64"); + return view.buffer.slice( + view.byteOffset, + view.byteOffset + view.byteLength + ); + }, + ArrayBufferView(value) { + (0, import_node_assert.default)(Array.isArray(value)); + const [name, buffer, byteOffset, byteLength] = value; + (0, import_node_assert.default)(typeof name === "string"); + (0, import_node_assert.default)(buffer instanceof ArrayBuffer); + (0, import_node_assert.default)(typeof byteOffset === "number"); + (0, import_node_assert.default)(typeof byteLength === "number"); + const ctor = globalThis[name]; + (0, import_node_assert.default)(ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS.includes(ctor)); + let length = byteLength; + if ("BYTES_PER_ELEMENT" in ctor) + length /= ctor.BYTES_PER_ELEMENT; + return new ctor(buffer, byteOffset, length); + }, + Error(value) { + (0, import_node_assert.default)(Array.isArray(value)); + const [name, message, stack, cause] = value; + (0, import_node_assert.default)(typeof name === "string"); + (0, import_node_assert.default)(typeof message === "string"); + (0, import_node_assert.default)(stack === void 0 || typeof stack === "string"); + const ctor = globalThis[name]; + (0, import_node_assert.default)(ALLOWED_ERROR_CONSTRUCTORS.includes(ctor)); + const error = new ctor(message, { cause }); + error.stack = stack; + return error; + } +}; +function createHTTPReducers(impl) { + return { + Headers(val) { + if (val instanceof impl.Headers) + return Object.fromEntries(val); + }, + Request(val) { + if (val instanceof impl.Request) { + return [val.method, val.url, val.headers, val.cf, val.body]; + } + }, + Response(val) { + if (val instanceof impl.Response) { + return [val.status, val.statusText, val.headers, val.cf, val.body]; + } + } + }; +} +function createHTTPRevivers(impl) { + return { + Headers(value) { + (0, import_node_assert.default)(typeof value === "object" && value !== null); + return new impl.Headers(value); + }, + Request(value) { + (0, import_node_assert.default)(Array.isArray(value)); + const [method, url14, headers, cf, body] = value; + (0, import_node_assert.default)(typeof method === "string"); + (0, import_node_assert.default)(typeof url14 === "string"); + (0, import_node_assert.default)(headers instanceof impl.Headers); + (0, import_node_assert.default)(body === null || impl.isReadableStream(body)); + return new impl.Request(url14, { + method, + headers, + cf, + // @ts-expect-error `duplex` is not required by `workerd` yet + duplex: body === null ? void 0 : "half", + body + }); + }, + Response(value) { + (0, import_node_assert.default)(Array.isArray(value)); + const [status, statusText, headers, cf, body] = value; + (0, import_node_assert.default)(typeof status === "number"); + (0, import_node_assert.default)(typeof statusText === "string"); + (0, import_node_assert.default)(headers instanceof impl.Headers); + (0, import_node_assert.default)(body === null || impl.isReadableStream(body)); + return new impl.Response(body, { + status, + statusText, + headers, + cf + }); + } + }; +} +function stringifyWithStreams(impl, value, reducers2, allowUnbufferedStream) { + let unbufferedStream; + const bufferPromises = []; + const streamReducers = { + ReadableStream(value2) { + if (impl.isReadableStream(value2)) { + if (allowUnbufferedStream && unbufferedStream === void 0) { + unbufferedStream = value2; + } else { + bufferPromises.push(impl.bufferReadableStream(value2)); + } + return true; + } + }, + Blob(value2) { + if (value2 instanceof impl.Blob) { + bufferPromises.push(value2.arrayBuffer()); + return true; + } + }, + ...reducers2 + }; + const stringifiedValue = stringify(value, streamReducers); + if (bufferPromises.length === 0) { + return { value: stringifiedValue, unbufferedStream }; + } + return Promise.all(bufferPromises).then((streamBuffers) => { + streamReducers.ReadableStream = function(value2) { + if (impl.isReadableStream(value2)) { + if (value2 === unbufferedStream) { + return true; + } else { + return streamBuffers.shift(); + } + } + }; + streamReducers.Blob = function(value2) { + if (value2 instanceof impl.Blob) { + const array = [streamBuffers.shift(), value2.type]; + if (value2 instanceof impl.File) { + array.push(value2.name, value2.lastModified); + } + return array; + } + }; + const stringifiedValue2 = stringify(value, streamReducers); + return { value: stringifiedValue2, unbufferedStream }; + }); +} +function parseWithReadableStreams(impl, stringified, revivers2) { + const streamRevivers = { + ReadableStream(value) { + if (value === true) { + (0, import_node_assert.default)(stringified.unbufferedStream !== void 0); + return stringified.unbufferedStream; + } + (0, import_node_assert.default)(value instanceof ArrayBuffer); + return impl.unbufferReadableStream(value); + }, + Blob(value) { + (0, import_node_assert.default)(Array.isArray(value)); + if (value.length === 2) { + const [buffer, type] = value; + (0, import_node_assert.default)(buffer instanceof ArrayBuffer); + (0, import_node_assert.default)(typeof type === "string"); + const opts = {}; + if (type !== "") + opts.type = type; + return new impl.Blob([buffer], opts); + } else { + (0, import_node_assert.default)(value.length === 4); + const [buffer, type, name, lastModified] = value; + (0, import_node_assert.default)(buffer instanceof ArrayBuffer); + (0, import_node_assert.default)(typeof type === "string"); + (0, import_node_assert.default)(typeof name === "string"); + (0, import_node_assert.default)(typeof lastModified === "number"); + const opts = { lastModified }; + if (type !== "") + opts.type = type; + return new impl.File([buffer], name, opts); + } + }, + ...revivers2 + }; + return parse(stringified.value, streamRevivers); +} + +// src/workers/core/routing.ts +function matchRoutes(routes, url14) { + for (const route of routes) { + if (route.protocol && route.protocol !== url14.protocol) + continue; + if (route.allowHostnamePrefix) { + if (!url14.hostname.endsWith(route.hostname)) + continue; + } else { + if (url14.hostname !== route.hostname) + continue; + } + const path23 = url14.pathname + url14.search; + if (route.allowPathSuffix) { + if (!path23.startsWith(route.path)) + continue; + } else { + if (path23 !== route.path) + continue; + } + return route.target; + } + return null; +} + +// src/workers/shared/constants.ts +var SharedHeaders = { + LOG_LEVEL: "MF-Log-Level" +}; +var SharedBindings = { + TEXT_NAMESPACE: "MINIFLARE_NAMESPACE", + DURABLE_OBJECT_NAMESPACE_OBJECT: "MINIFLARE_OBJECT", + MAYBE_SERVICE_BLOBS: "MINIFLARE_BLOBS", + MAYBE_SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK", + MAYBE_JSON_ENABLE_CONTROL_ENDPOINTS: "MINIFLARE_ENABLE_CONTROL_ENDPOINTS", + MAYBE_JSON_ENABLE_STICKY_BLOBS: "MINIFLARE_STICKY_BLOBS" +}; +var LogLevel = /* @__PURE__ */ ((LogLevel2) => { + LogLevel2[LogLevel2["NONE"] = 0] = "NONE"; + LogLevel2[LogLevel2["ERROR"] = 1] = "ERROR"; + LogLevel2[LogLevel2["WARN"] = 2] = "WARN"; + LogLevel2[LogLevel2["INFO"] = 3] = "INFO"; + LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG"; + LogLevel2[LogLevel2["VERBOSE"] = 5] = "VERBOSE"; + return LogLevel2; +})(LogLevel || {}); + +// src/workers/shared/data.ts +var import_node_buffer2 = require("node:buffer"); +function viewToBuffer(view) { + return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength); +} +function base64Encode(value) { + return import_node_buffer2.Buffer.from(value, "utf8").toString("base64"); +} +function base64Decode(encoded) { + return import_node_buffer2.Buffer.from(encoded, "base64").toString("utf8"); +} +var dotRegexp = /(^|\/|\\)(\.+)(\/|\\|$)/g; +var illegalRegexp = /[?<>*"'^/\\:|\x00-\x1f\x80-\x9f]/g; +var windowsReservedRegexp = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; +var leadingRegexp = /^[ /\\]+/; +var trailingRegexp = /[ /\\]+$/; +function dotReplacement(match, g1, g2, g3) { + return `${g1}${"".padStart(g2.length, "_")}${g3}`; +} +function underscoreReplacement(match) { + return "".padStart(match.length, "_"); +} +function sanitisePath(unsafe) { + return unsafe.replace(dotRegexp, dotReplacement).replace(dotRegexp, dotReplacement).replace(illegalRegexp, "_").replace(windowsReservedRegexp, "_").replace(leadingRegexp, underscoreReplacement).replace(trailingRegexp, underscoreReplacement).substring(0, 255); +} + +// src/workers/shared/matcher.ts +function testRegExps(matcher, value) { + for (const exclude of matcher.exclude) + if (exclude.test(value)) + return false; + for (const include of matcher.include) + if (include.test(value)) + return true; + return false; +} + +// src/workers/shared/range.ts +var rangePrefixRegexp = /^ *bytes *=/i; +var rangeRegexp = /^ *(?\d+)? *- *(?\d+)? *$/; +function parseRanges(rangeHeader, length) { + const prefixMatch = rangePrefixRegexp.exec(rangeHeader); + if (prefixMatch === null) + return; + rangeHeader = rangeHeader.substring(prefixMatch[0].length); + if (rangeHeader.trimStart() === "") + return []; + const ranges = rangeHeader.split(","); + const result = []; + for (const range of ranges) { + const match = rangeRegexp.exec(range); + if (match === null) + return; + const { start, end } = match.groups; + if (start !== void 0 && end !== void 0) { + const rangeStart = parseInt(start); + let rangeEnd = parseInt(end); + if (rangeStart > rangeEnd) + return; + if (rangeStart >= length) + return; + if (rangeEnd >= length) + rangeEnd = length - 1; + result.push({ start: rangeStart, end: rangeEnd }); + } else if (start !== void 0 && end === void 0) { + const rangeStart = parseInt(start); + if (rangeStart >= length) + return; + result.push({ start: rangeStart, end: length - 1 }); + } else if (start === void 0 && end !== void 0) { + const suffix = parseInt(end); + if (suffix >= length) + return []; + if (suffix === 0) + continue; + result.push({ start: length - suffix, end: length - 1 }); + } else { + return; + } + } + return result; +} + +// src/workers/shared/sync.ts +var import_node_assert2 = __toESM(require("node:assert")); +var DeferredPromise = class extends Promise { + resolve; + reject; + constructor(executor = () => { + }) { + let promiseResolve; + let promiseReject; + super((resolve, reject) => { + promiseResolve = resolve; + promiseReject = reject; + return executor(resolve, reject); + }); + this.resolve = promiseResolve; + this.reject = promiseReject; + } +}; +var Mutex = class { + locked = false; + resolveQueue = []; + drainQueue = []; + lock() { + if (!this.locked) { + this.locked = true; + return; + } + return new Promise((resolve) => this.resolveQueue.push(resolve)); + } + unlock() { + (0, import_node_assert2.default)(this.locked); + if (this.resolveQueue.length > 0) { + this.resolveQueue.shift()?.(); + } else { + this.locked = false; + let resolve; + while ((resolve = this.drainQueue.shift()) !== void 0) + resolve(); + } + } + get hasWaiting() { + return this.resolveQueue.length > 0; + } + async runWith(closure) { + const acquireAwaitable = this.lock(); + if (acquireAwaitable instanceof Promise) + await acquireAwaitable; + try { + const awaitable = closure(); + if (awaitable instanceof Promise) + return await awaitable; + return awaitable; + } finally { + this.unlock(); + } + } + async drained() { + if (this.resolveQueue.length === 0 && !this.locked) + return; + return new Promise((resolve) => this.drainQueue.push(resolve)); + } +}; +var WaitGroup = class { + counter = 0; + resolveQueue = []; + add() { + this.counter++; + } + done() { + (0, import_node_assert2.default)(this.counter > 0); + this.counter--; + if (this.counter === 0) { + let resolve; + while ((resolve = this.resolveQueue.shift()) !== void 0) + resolve(); + } + } + wait() { + if (this.counter === 0) + return Promise.resolve(); + return new Promise((resolve) => this.resolveQueue.push(resolve)); + } +}; + +// src/workers/shared/types.ts +function reduceError(e) { + return { + name: e?.name, + message: e?.message ?? String(e), + stack: e?.stack, + cause: e?.cause === void 0 ? void 0 : reduceError(e.cause) + }; +} +function maybeApply(f, maybeValue) { + return maybeValue === void 0 ? void 0 : f(maybeValue); +} + +// src/workers/kv/constants.ts +var KVLimits = { + MIN_CACHE_TTL: 60, + MAX_LIST_KEYS: 1e3, + MAX_KEY_SIZE: 512, + MAX_VALUE_SIZE: 25 * 1024 * 1024, + MAX_VALUE_SIZE_TEST: 1024, + MAX_METADATA_SIZE: 1024 +}; +var KVParams = { + URL_ENCODED: "urlencoded", + CACHE_TTL: "cache_ttl", + EXPIRATION: "expiration", + EXPIRATION_TTL: "expiration_ttl", + LIST_LIMIT: "key_count_limit", + LIST_PREFIX: "prefix", + LIST_CURSOR: "cursor" +}; +var KVHeaders = { + EXPIRATION: "CF-Expiration", + METADATA: "CF-KV-Metadata" +}; +var SiteBindings = { + KV_NAMESPACE_SITE: "__STATIC_CONTENT", + JSON_SITE_MANIFEST: "__STATIC_CONTENT_MANIFEST", + JSON_SITE_FILTER: "MINIFLARE_SITE_FILTER" +}; +var SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/"; +function encodeSitesKey(key) { + return SITES_NO_CACHE_PREFIX + encodeURIComponent(key); +} +function decodeSitesKey(key) { + return key.startsWith(SITES_NO_CACHE_PREFIX) ? decodeURIComponent(key.substring(SITES_NO_CACHE_PREFIX.length)) : key; +} +function isSitesRequest(request) { + const url14 = new URL(request.url); + return url14.pathname.startsWith(`/${SITES_NO_CACHE_PREFIX}`); +} +function serialiseRegExp(regExp) { + const str = regExp.toString(); + return str.substring(str.indexOf("/") + 1, str.lastIndexOf("/")); +} +function serialiseRegExps(matcher) { + return { + include: matcher.include.map(serialiseRegExp), + exclude: matcher.exclude.map(serialiseRegExp) + }; +} +function deserialiseRegExps(matcher) { + return { + include: matcher.include.map((regExp) => new RegExp(regExp)), + exclude: matcher.exclude.map((regExp) => new RegExp(regExp)) + }; +} +function serialiseSiteRegExps(siteRegExps) { + return { + include: siteRegExps.include && serialiseRegExps(siteRegExps.include), + exclude: siteRegExps.exclude && serialiseRegExps(siteRegExps.exclude) + }; +} +function deserialiseSiteRegExps(siteRegExps) { + return { + include: siteRegExps.include && deserialiseRegExps(siteRegExps.include), + exclude: siteRegExps.exclude && deserialiseRegExps(siteRegExps.exclude) + }; +} +function testSiteRegExps(regExps, key) { + if (regExps.include !== void 0) + return testRegExps(regExps.include, key); + if (regExps.exclude !== void 0) + return !testRegExps(regExps.exclude, key); + return true; +} + +// src/workers/queues/constants.ts +var QueueBindings = { + SERVICE_WORKER_PREFIX: "MINIFLARE_WORKER_", + MAYBE_JSON_QUEUE_PRODUCERS: "MINIFLARE_QUEUE_PRODUCERS", + MAYBE_JSON_QUEUE_CONSUMERS: "MINIFLARE_QUEUE_CONSUMERS" +}; + +// src/workers/shared/zod.worker.ts +var import_node_buffer3 = require("node:buffer"); +var import_zod = require("zod"); +var import_zod2 = require("zod"); +var HEX_REGEXP = /^[0-9a-f]*$/i; +var BASE64_REGEXP = /^[0-9a-z+/=]*$/i; +var HexDataSchema = import_zod.z.string().regex(HEX_REGEXP).transform((hex) => import_node_buffer3.Buffer.from(hex, "hex")); +var Base64DataSchema = import_zod.z.string().regex(BASE64_REGEXP).transform((base64) => import_node_buffer3.Buffer.from(base64, "base64")); + +// src/workers/queues/schemas.ts +var QueueMessageDelaySchema = import_zod2.z.number().int().min(0).max(43200).optional(); +var QueueProducerOptionsSchema = /* @__PURE__ */ import_zod2.z.object({ + // https://developers.cloudflare.com/queues/platform/configuration/#producer + queueName: import_zod2.z.string(), + deliveryDelay: QueueMessageDelaySchema +}); +var QueueProducerSchema = /* @__PURE__ */ import_zod2.z.intersection( + QueueProducerOptionsSchema, + import_zod2.z.object({ workerName: import_zod2.z.string() }) +); +var QueueProducersSchema = /* @__PURE__ */ import_zod2.z.record(QueueProducerSchema); +var QueueConsumerOptionsSchema = /* @__PURE__ */ import_zod2.z.object({ + // https://developers.cloudflare.com/queues/platform/configuration/#consumer + // https://developers.cloudflare.com/queues/platform/limits/ + maxBatchSize: import_zod2.z.number().min(0).max(100).optional(), + maxBatchTimeout: import_zod2.z.number().min(0).max(30).optional(), + // seconds + maxRetires: import_zod2.z.number().min(0).max(100).optional(), + deadLetterQueue: import_zod2.z.ostring(), + retryDelay: QueueMessageDelaySchema +}); +var QueueConsumerSchema = /* @__PURE__ */ import_zod2.z.intersection( + QueueConsumerOptionsSchema, + import_zod2.z.object({ workerName: import_zod2.z.string() }) +); +var QueueConsumersSchema = /* @__PURE__ */ import_zod2.z.record(QueueConsumerSchema); +var QueueContentTypeSchema = /* @__PURE__ */ import_zod2.z.enum(["text", "json", "bytes", "v8"]).default("v8"); +var QueueIncomingMessageSchema = /* @__PURE__ */ import_zod2.z.object({ + contentType: QueueContentTypeSchema, + delaySecs: QueueMessageDelaySchema, + body: Base64DataSchema, + // When enqueuing messages on dead-letter queues, we want to reuse the same ID + // and timestamp + id: import_zod2.z.ostring(), + timestamp: import_zod2.z.onumber() +}); +var QueuesBatchRequestSchema = /* @__PURE__ */ import_zod2.z.object({ + messages: import_zod2.z.array(QueueIncomingMessageSchema) +}); + +// src/http/request.ts +var import_undici2 = require("undici"); +var kCf = Symbol("kCf"); +var Request = class extends import_undici2.Request { + // We should be able to use a private `#cf` property here instead of a symbol + // here, but we need to set this on a clone, which would otherwise lead to a + // "Cannot write private member to an object whose class did not declare it" + // error. + [kCf]; + constructor(input, init2) { + super(input, init2); + this[kCf] = init2?.cf; + if (input instanceof Request) + this[kCf] ??= input.cf; + } + get cf() { + return this[kCf]; + } + // JSDoc comment so retained when bundling types with api-extractor + /** @ts-expect-error `clone` is actually defined as a method internally */ + clone() { + const request = super.clone(); + Object.setPrototypeOf(request, Request.prototype); + request[kCf] = this[kCf]; + return request; + } +}; + +// src/http/response.ts +var import_undici3 = require("undici"); +var kWebSocket = Symbol("kWebSocket"); +var Response = class extends import_undici3.Response { + // We should be able to use a private `#webSocket` property here instead of a + // symbol here, but `undici` calls `this.status` in its constructor, which + // causes a "Cannot read private member from an object whose class did not + // declare it" error. + [kWebSocket]; + // Override BaseResponse's static methods for building Responses to return + // our type instead. Ideally, we don't want to use `Object.setPrototypeOf`. + // Unfortunately, `error()` and `redirect()` set the internal header guard + // to "immutable". + static error() { + const response = import_undici3.Response.error(); + Object.setPrototypeOf(response, Response.prototype); + return response; + } + static redirect(url14, status) { + const response = import_undici3.Response.redirect(url14, status); + Object.setPrototypeOf(response, Response.prototype); + return response; + } + static json(data, init2) { + const body = JSON.stringify(data); + const response = new Response(body, init2); + response.headers.set("Content-Type", "application/json"); + return response; + } + constructor(body, init2) { + if (init2?.webSocket) { + if (init2.status !== 101) { + throw new RangeError( + "Responses with a WebSocket must have status code 101." + ); + } + init2 = { ...init2, status: 200 }; + } + super(body, init2); + this[kWebSocket] = init2?.webSocket ?? null; + } + // JSDoc comment so retained when bundling types with api-extractor + /** @ts-expect-error `status` is actually defined as a getter internally */ + get status() { + return this[kWebSocket] ? 101 : super.status; + } + get webSocket() { + return this[kWebSocket]; + } + // JSDoc comment so retained when bundling types with api-extractor + /** @ts-expect-error `clone` is actually defined as a method internally */ + clone() { + if (this[kWebSocket]) { + throw new TypeError("Cannot clone a response to a WebSocket handshake."); + } + const response = super.clone(); + Object.setPrototypeOf(response, Response.prototype); + return response; + } +}; + +// src/http/websocket.ts +var import_assert3 = __toESM(require("assert")); +var import_events = require("events"); +var import_ws = __toESM(require("ws")); + +// src/shared/colour.ts +var originalEnabled = $.enabled; +function _forceColour(enabled = originalEnabled) { + $.enabled = enabled; +} + +// src/shared/error.ts +var MiniflareError = class extends Error { + constructor(code, message, cause) { + super(message); + this.code = code; + this.cause = cause; + Object.setPrototypeOf(this, new.target.prototype); + this.name = `${new.target.name} [${code}]`; + } +}; +var MiniflareCoreError = class extends MiniflareError { +}; + +// src/shared/event.ts +var TypedEventTarget = class extends EventTarget { + addEventListener(type, listener, options) { + super.addEventListener( + type, + listener, + options + ); + } + removeEventListener(type, listener, options) { + super.removeEventListener( + type, + listener, + options + ); + } + dispatchEvent(event) { + return super.dispatchEvent(event); + } +}; + +// src/shared/log.ts +var import_path4 = __toESM(require("path")); +var cwd = process.cwd(); +var cwdNodeModules = import_path4.default.join(cwd, "node_modules"); +var LEVEL_PREFIX = { + [0 /* NONE */]: "", + [1 /* ERROR */]: "err", + [2 /* WARN */]: "wrn", + [3 /* INFO */]: "inf", + [4 /* DEBUG */]: "dbg", + [5 /* VERBOSE */]: "vrb" +}; +var LEVEL_COLOUR = { + [0 /* NONE */]: reset, + [1 /* ERROR */]: red, + [2 /* WARN */]: yellow, + [3 /* INFO */]: green, + [4 /* DEBUG */]: grey, + [5 /* VERBOSE */]: (input) => dim(grey(input)) +}; +function prefixError(prefix, e) { + if (e.stack) { + return new Proxy(e, { + get(target, propertyKey, receiver) { + const value = Reflect.get(target, propertyKey, receiver); + return propertyKey === "stack" ? `${prefix}: ${value}` : value; + } + }); + } + return e; +} +function dimInternalStackLine(line) { + if (line.startsWith(" at") && (!line.includes(cwd) || line.includes(cwdNodeModules))) { + return dim(line); + } + return line; +} +var Log = class { + constructor(level = 3 /* INFO */, opts = {}) { + this.level = level; + const prefix = opts.prefix ?? "mf"; + const suffix = opts.suffix ?? ""; + this.#prefix = prefix ? prefix + ":" : ""; + this.#suffix = suffix ? ":" + suffix : ""; + } + #prefix; + #suffix; + log(message) { + console.log(message); + } + logWithLevel(level, message) { + if (level <= this.level) { + const prefix = `[${this.#prefix}${LEVEL_PREFIX[level]}${this.#suffix}]`; + this.log(LEVEL_COLOUR[level](`${prefix} ${message}`)); + } + } + error(message) { + if (this.level < 1 /* ERROR */) { + } else if (message.stack) { + const lines = message.stack.split("\n").map(dimInternalStackLine); + this.logWithLevel(1 /* ERROR */, lines.join("\n")); + } else { + this.logWithLevel(1 /* ERROR */, message.toString()); + } + if (message.cause) { + this.error(prefixError("Cause", message.cause)); + } + } + warn(message) { + this.logWithLevel(2 /* WARN */, message); + } + info(message) { + this.logWithLevel(3 /* INFO */, message); + } + debug(message) { + this.logWithLevel(4 /* DEBUG */, message); + } + verbose(message) { + this.logWithLevel(5 /* VERBOSE */, message); + } +}; +var NoOpLog = class extends Log { + constructor() { + super(0 /* NONE */); + } + log() { + } + error(_message) { + } +}; +var ansiRegexpPattern = [ + "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", + "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))" +].join("|"); +var ansiRegexp = new RegExp(ansiRegexpPattern, "g"); +function stripAnsi(value) { + return value.replace(ansiRegexp, ""); +} + +// src/shared/matcher.ts +var import_glob_to_regexp = __toESM(require("glob-to-regexp")); +function globsToRegExps(globs = []) { + const include = []; + const exclude = []; + const opts = { globstar: true, flags: "g" }; + for (const glob of globs) { + if (glob.startsWith("!")) { + exclude.push(new RegExp((0, import_glob_to_regexp.default)(glob.slice(1), opts), "")); + } else { + include.push(new RegExp((0, import_glob_to_regexp.default)(glob, opts), "")); + } + } + return { include, exclude }; +} + +// src/shared/streams.ts +var import_web = require("stream/web"); +function prefixStream(prefix, stream) { + const identity = new import_web.TransformStream(); + const writer = identity.writable.getWriter(); + void writer.write(prefix).then(() => { + writer.releaseLock(); + return stream.pipeTo(identity.writable); + }).catch((error) => { + return writer.abort(error); + }); + return identity.readable; +} +async function readPrefix(stream, prefixLength) { + const chunks = []; + let chunksLength = 0; + for await (const chunk of stream.values({ preventCancel: true })) { + chunks.push(chunk); + chunksLength += chunk.byteLength; + if (chunksLength >= prefixLength) + break; + } + if (chunksLength < prefixLength) { + throw new RangeError( + `Expected ${prefixLength} byte prefix, but received ${chunksLength} byte stream` + ); + } + const atLeastPrefix = Buffer.concat(chunks, chunksLength); + const prefix = atLeastPrefix.subarray(0, prefixLength); + let rest = stream; + if (chunksLength > prefixLength) { + rest = prefixStream(atLeastPrefix.subarray(prefixLength), stream); + } + return [prefix, rest]; +} + +// src/shared/types.ts +var import_assert2 = __toESM(require("assert")); +var import_path5 = __toESM(require("path")); +var import_zod3 = require("zod"); +function zAwaitable(type) { + return type.or(import_zod3.z.promise(type)); +} +var LiteralSchema = import_zod3.z.union([ + import_zod3.z.string(), + import_zod3.z.number(), + import_zod3.z.boolean(), + import_zod3.z.null() +]); +var JsonSchema = import_zod3.z.lazy( + () => import_zod3.z.union([LiteralSchema, import_zod3.z.array(JsonSchema), import_zod3.z.record(JsonSchema)]) +); +var rootPath; +function parseWithRootPath(newRootPath, schema, data, params) { + rootPath = newRootPath; + try { + return schema.parse(data, params); + } finally { + rootPath = void 0; + } +} +var PathSchema = import_zod3.z.string().transform((p) => { + (0, import_assert2.default)( + rootPath !== void 0, + "Expected `PathSchema` to be parsed within `parseWithRootPath()`" + ); + return import_path5.default.resolve(rootPath, p); +}); +function _isCyclic(value, seen = /* @__PURE__ */ new Set()) { + if (typeof value !== "object" || value === null) + return false; + for (const child of Object.values(value)) { + if (seen.has(child)) + return true; + seen.add(child); + if (_isCyclic(child, seen)) + return true; + seen.delete(child); + } + return false; +} + +// src/http/websocket.ts +var MessageEvent = class extends Event { + data; + constructor(type, init2) { + super(type); + this.data = init2.data; + } +}; +var CloseEvent = class extends Event { + code; + reason; + wasClean; + constructor(type, init2) { + super(type); + this.code = init2?.code ?? 1005; + this.reason = init2?.reason ?? ""; + this.wasClean = init2?.wasClean ?? false; + } +}; +var ErrorEvent = class extends Event { + error; + constructor(type, init2) { + super(type); + this.error = init2?.error ?? null; + } +}; +var kPair = Symbol("kPair"); +var kAccepted = Symbol("kAccepted"); +var kCoupled = Symbol("kCoupled"); +var kClosedOutgoing = Symbol("kClosedOutgoing"); +var kClosedIncoming = Symbol("kClosedIncoming"); +var kSend = Symbol("kSend"); +var kClose = Symbol("kClose"); +var kError = Symbol("kError"); +var _dispatchQueue, _a, _b, _c, _d, _e, _queuingDispatchToPair, queuingDispatchToPair_fn; +var _WebSocket = class extends TypedEventTarget { + constructor() { + super(...arguments); + __privateAdd(this, _queuingDispatchToPair); + __privateAdd(this, _dispatchQueue, []); + __publicField(this, _a); + __publicField(this, _b, false); + __publicField(this, _c, false); + __publicField(this, _d, false); + __publicField(this, _e, false); + } + get readyState() { + if (this[kClosedOutgoing] && this[kClosedIncoming]) { + return _WebSocket.READY_STATE_CLOSED; + } else if (this[kClosedOutgoing] || this[kClosedIncoming]) { + return _WebSocket.READY_STATE_CLOSING; + } + return _WebSocket.READY_STATE_OPEN; + } + accept() { + if (this[kCoupled]) { + throw new TypeError( + "Can't accept() WebSocket that was already used in a response." + ); + } + if (this[kAccepted]) + return; + this[kAccepted] = true; + if (__privateGet(this, _dispatchQueue) !== void 0) { + for (const event of __privateGet(this, _dispatchQueue)) + this.dispatchEvent(event); + __privateSet(this, _dispatchQueue, void 0); + } + } + send(message) { + if (!this[kAccepted]) { + throw new TypeError( + "You must call accept() on this WebSocket before sending messages." + ); + } + this[kSend](message); + } + [(_a = kPair, _b = kAccepted, _c = kCoupled, _d = kClosedOutgoing, _e = kClosedIncoming, kSend)](message) { + if (this[kClosedOutgoing]) { + throw new TypeError("Can't call WebSocket send() after close()."); + } + const event = new MessageEvent("message", { data: message }); + void __privateMethod(this, _queuingDispatchToPair, queuingDispatchToPair_fn).call(this, event); + } + close(code, reason) { + if (code) { + const validCode = code >= 1e3 && code < 5e3 && code !== 1004 && code !== 1005 && code !== 1006 && code !== 1015; + if (!validCode) + throw new TypeError("Invalid WebSocket close code."); + } + if (reason !== void 0 && code === void 0) { + throw new TypeError( + "If you specify a WebSocket close reason, you must also specify a code." + ); + } + if (!this[kAccepted]) { + throw new TypeError( + "You must call accept() on this WebSocket before sending messages." + ); + } + this[kClose](code, reason); + } + [kClose](code, reason) { + if (this[kClosedOutgoing]) + throw new TypeError("WebSocket already closed"); + const pair = this[kPair]; + (0, import_assert3.default)(pair !== void 0); + this[kClosedOutgoing] = true; + pair[kClosedIncoming] = true; + const event = new CloseEvent("close", { code, reason }); + void __privateMethod(this, _queuingDispatchToPair, queuingDispatchToPair_fn).call(this, event); + } + [kError](error) { + const event = new ErrorEvent("error", { error }); + void __privateMethod(this, _queuingDispatchToPair, queuingDispatchToPair_fn).call(this, event); + } +}; +var WebSocket = _WebSocket; +_dispatchQueue = new WeakMap(); +_queuingDispatchToPair = new WeakSet(); +queuingDispatchToPair_fn = async function(event) { + const pair = this[kPair]; + (0, import_assert3.default)(pair !== void 0); + if (pair[kAccepted]) { + pair.dispatchEvent(event); + } else { + (0, import_assert3.default)(__privateGet(pair, _dispatchQueue) !== void 0); + __privateGet(pair, _dispatchQueue).push(event); + } +}; +// The Workers runtime prefixes these constants with `READY_STATE_`, unlike +// those in the spec: https://websockets.spec.whatwg.org/#interface-definition +__publicField(WebSocket, "READY_STATE_CONNECTING", 0); +__publicField(WebSocket, "READY_STATE_OPEN", 1); +__publicField(WebSocket, "READY_STATE_CLOSING", 2); +__publicField(WebSocket, "READY_STATE_CLOSED", 3); +var WebSocketPair = function() { + if (!(this instanceof WebSocketPair)) { + throw new TypeError( + "Failed to construct 'WebSocketPair': Please use the 'new' operator, this object constructor cannot be called as a function." + ); + } + this[0] = new WebSocket(); + this[1] = new WebSocket(); + this[0][kPair] = this[1]; + this[1][kPair] = this[0]; +}; +async function coupleWebSocket(ws, pair) { + if (pair[kCoupled]) { + throw new TypeError( + "Can't return WebSocket that was already used in a response." + ); + } + if (pair[kAccepted]) { + throw new TypeError( + "Can't return WebSocket in a Response after calling accept()." + ); + } + ws.on("message", (message, isBinary) => { + if (!pair[kClosedOutgoing]) { + pair[kSend](isBinary ? viewToBuffer(message) : message.toString()); + } + }); + ws.on("close", (code, reason) => { + if (!pair[kClosedOutgoing]) { + pair[kClose](code, reason.toString()); + } + }); + ws.on("error", (error) => { + pair[kError](error); + }); + pair.addEventListener("message", (e) => { + ws.send(e.data); + }); + pair.addEventListener("close", (e) => { + if (e.code === 1005) { + ws.close(); + } else if (e.code === 1006) { + ws.terminate(); + } else { + ws.close(e.code, e.reason); + } + }); + if (ws.readyState === import_ws.default.CONNECTING) { + await (0, import_events.once)(ws, "open"); + } else if (ws.readyState >= import_ws.default.CLOSING) { + throw new TypeError("Incoming WebSocket connection already closed."); + } + pair.accept(); + pair[kCoupled] = true; +} + +// src/http/fetch.ts +var ignored = ["transfer-encoding", "connection", "keep-alive", "expect"]; +function headersFromIncomingRequest(req) { + const entries = Object.entries(req.headers).filter( + (pair) => { + const [name, value] = pair; + return !ignored.includes(name) && value !== void 0; + } + ); + return new import_undici4.Headers(Object.fromEntries(entries)); +} +async function fetch2(input, init2) { + const requestInit = init2; + const request = new Request(input, requestInit); + if (request.method === "GET" && request.headers.get("upgrade") === "websocket") { + const url14 = new URL(request.url); + if (url14.protocol !== "http:" && url14.protocol !== "https:") { + throw new TypeError( + `Fetch API cannot load: ${url14.toString()}. +Make sure you're using http(s):// URLs for WebSocket requests via fetch.` + ); + } + url14.protocol = url14.protocol.replace("http", "ws"); + const headers = {}; + let protocols; + for (const [key, value] of request.headers.entries()) { + if (key.toLowerCase() === "sec-websocket-protocol") { + protocols = value.split(",").map((protocol) => protocol.trim()); + } else { + headers[key] = value; + } + } + let rejectUnauthorized; + if (requestInit.dispatcher instanceof DispatchFetchDispatcher) { + requestInit.dispatcher.addHeaders(headers, url14.pathname + url14.search); + rejectUnauthorized = { rejectUnauthorized: false }; + } + const ws = new import_ws2.default(url14, protocols, { + followRedirects: request.redirect === "follow", + headers, + ...rejectUnauthorized + }); + const responsePromise = new DeferredPromise(); + ws.once("upgrade", (req) => { + const headers2 = headersFromIncomingRequest(req); + const [worker, client] = Object.values(new WebSocketPair()); + const couplePromise = coupleWebSocket(ws, client); + const response2 = new Response(null, { + status: 101, + webSocket: worker, + headers: headers2 + }); + responsePromise.resolve(couplePromise.then(() => response2)); + }); + ws.once("unexpected-response", (_, req) => { + const headers2 = headersFromIncomingRequest(req); + const response2 = new Response(req, { + status: req.statusCode, + headers: headers2 + }); + responsePromise.resolve(response2); + }); + return responsePromise; + } + const response = await (0, import_undici4.fetch)(request, { + dispatcher: requestInit?.dispatcher + }); + return new Response(response.body, response); +} +function addHeader(headers, key, value) { + if (Array.isArray(headers)) + headers.push(key, value); + else + headers[key] = value; +} +var DispatchFetchDispatcher = class extends import_undici4.Dispatcher { + /** + * @param globalDispatcher Dispatcher to use for all non-runtime requests + * (rejects unauthorised certificates) + * @param runtimeDispatcher Dispatcher to use for runtime requests + * (permits unauthorised certificates) + * @param actualRuntimeOrigin Origin to send all runtime requests to + * @param userRuntimeOrigin Origin to treat as runtime request + * (initial URL passed by user to `dispatchFetch()`) + * @param cfBlob `request.cf` blob override for runtime requests + */ + constructor(globalDispatcher, runtimeDispatcher, actualRuntimeOrigin, userRuntimeOrigin, cfBlob) { + super(); + this.globalDispatcher = globalDispatcher; + this.runtimeDispatcher = runtimeDispatcher; + this.actualRuntimeOrigin = actualRuntimeOrigin; + this.userRuntimeOrigin = userRuntimeOrigin; + if (cfBlob !== void 0) + this.cfBlobJson = JSON.stringify(cfBlob); + } + cfBlobJson; + addHeaders(headers, path23) { + const originalURL = this.userRuntimeOrigin + path23; + addHeader(headers, CoreHeaders.ORIGINAL_URL, originalURL); + addHeader(headers, CoreHeaders.DISABLE_PRETTY_ERROR, "true"); + if (this.cfBlobJson !== void 0) { + addHeader(headers, CoreHeaders.CF_BLOB, this.cfBlobJson); + } + } + dispatch(options, handler) { + let origin = String(options.origin); + if (origin === this.userRuntimeOrigin) + origin = this.actualRuntimeOrigin; + if (origin === this.actualRuntimeOrigin) { + options.origin = origin; + let path23 = options.path; + if (options.query !== void 0) { + const url14 = new URL(path23, "http://placeholder/"); + for (const [key, value] of Object.entries(options.query)) { + url14.searchParams.append(key, value); + } + path23 = url14.pathname + url14.search; + } + options.headers ??= {}; + this.addHeaders(options.headers, path23); + return this.runtimeDispatcher.dispatch(options, handler); + } else { + return this.globalDispatcher.dispatch(options, handler); + } + } + async close(callback) { + await Promise.all([ + this.globalDispatcher.close(), + this.runtimeDispatcher.close() + ]); + callback?.(); + } + async destroy(errCallback, callback) { + let err = null; + if (typeof errCallback === "function") + callback = errCallback; + if (errCallback instanceof Error) + err = errCallback; + await Promise.all([ + this.globalDispatcher.destroy(err), + this.runtimeDispatcher.destroy(err) + ]); + callback?.(); + } + get isMockActive() { + return this.globalDispatcher.isMockActive ?? false; + } +}; + +// src/http/server.ts +var import_promises2 = __toESM(require("fs/promises")); + +// src/http/cert.ts +var KEY = ` +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIC+umAaVUbEfPqGA9M7b5zAP7tN2eLT1bu8U8gpbaKbsoAoGCCqGSM49 +AwEHoUQDQgAEtrIEgzogjrUHIvB4qgjg/cT7blhWuLUfSUp6H62NCo21NrVWgPtC +mCWw+vbGTBwIr/9X1S4UL1/f3zDICC7YSA== +-----END EC PRIVATE KEY----- +`; +var CERT = ` +-----BEGIN CERTIFICATE----- +MIICcDCCAhegAwIBAgIUE97EcbEWw3YZMN/ucGBSzJ/5qA4wCgYIKoZIzj0EAwIw +VTELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVRleGFzMQ8wDQYDVQQHDAZBdXN0aW4x +EzARBgNVBAoMCkNsb3VkZmxhcmUxEDAOBgNVBAsMB1dvcmtlcnMwIBcNMjMwNjIy +MTg1ODQ3WhgPMjEyMzA1MjkxODU4NDdaMFUxCzAJBgNVBAYTAlVTMQ4wDAYDVQQI +DAVUZXhhczEPMA0GA1UEBwwGQXVzdGluMRMwEQYDVQQKDApDbG91ZGZsYXJlMRAw +DgYDVQQLDAdXb3JrZXJzMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEtrIEgzog +jrUHIvB4qgjg/cT7blhWuLUfSUp6H62NCo21NrVWgPtCmCWw+vbGTBwIr/9X1S4U +L1/f3zDICC7YSKOBwjCBvzAdBgNVHQ4EFgQUSXahTksi00c6KhUECHIY4FLW7Sow +HwYDVR0jBBgwFoAUSXahTksi00c6KhUECHIY4FLW7SowDwYDVR0TAQH/BAUwAwEB +/zAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUw +CwYDVR0PBAQDAgL0MDEGA1UdJQQqMCgGCCsGAQUFBwMBBggrBgEFBQcDAgYIKwYB +BQUHAwMGCCsGAQUFBwMIMAoGCCqGSM49BAMCA0cAMEQCIE2qnXbKTHQ8wtwI+9XR +h4ivDyz7w7iGxn3+ccmj/CQqAiApdX/Iz/jGRzi04xFlE4GoPVG/zaMi64ckmIpE +ez/dHA== +-----END CERTIFICATE----- +`; + +// src/http/server.ts +var ENTRY_SOCKET_HTTP_OPTIONS = { + // Even though we inject a `cf` object in the entry worker, allow it to + // be customised via `dispatchFetch` + cfBlobHeader: CoreHeaders.CF_BLOB +}; +async function getEntrySocketHttpOptions(coreOpts) { + let privateKey = void 0; + let certificateChain = void 0; + if ((coreOpts.httpsKey || coreOpts.httpsKeyPath) && (coreOpts.httpsCert || coreOpts.httpsCertPath)) { + privateKey = await valueOrFile(coreOpts.httpsKey, coreOpts.httpsKeyPath); + certificateChain = await valueOrFile( + coreOpts.httpsCert, + coreOpts.httpsCertPath + ); + } else if (coreOpts.https) { + privateKey = KEY; + certificateChain = CERT; + } + if (privateKey && certificateChain) { + return { + https: { + options: ENTRY_SOCKET_HTTP_OPTIONS, + tlsOptions: { + keypair: { + privateKey, + certificateChain + } + } + } + }; + } else { + return { http: ENTRY_SOCKET_HTTP_OPTIONS }; + } +} +function valueOrFile(value, filePath) { + return value ?? (filePath && import_promises2.default.readFile(filePath, "utf8")); +} + +// src/http/helpers.ts +var import_os = require("os"); +function getAccessibleHosts(ipv4Only = false) { + const hosts = []; + Object.values((0, import_os.networkInterfaces)()).forEach((net2) => { + net2?.forEach(({ family, address }) => { + if (family === "IPv4" || family === 4) { + hosts.push(address); + } else if (!ipv4Only) { + hosts.push(address); + } + }); + }); + return hosts; +} + +// src/http/index.ts +var import_undici5 = require("undici"); + +// src/plugins/cache/index.ts +var import_promises4 = __toESM(require("fs/promises")); + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache.worker.ts +var import_fs3 = __toESM(require("fs")); +var import_path6 = __toESM(require("path")); +var import_url3 = __toESM(require("url")); +var contents3; +function cache_worker_default() { + if (contents3 !== void 0) + return contents3; + const filePath = import_path6.default.join(__dirname, "workers", "cache/cache.worker.js"); + contents3 = import_fs3.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url3.default.pathToFileURL(filePath); + return contents3; +} + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache-entry.worker.ts +var import_fs4 = __toESM(require("fs")); +var import_path7 = __toESM(require("path")); +var import_url4 = __toESM(require("url")); +var contents4; +function cache_entry_worker_default() { + if (contents4 !== void 0) + return contents4; + const filePath = import_path7.default.join(__dirname, "workers", "cache/cache-entry.worker.js"); + contents4 = import_fs4.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url4.default.pathToFileURL(filePath); + return contents4; +} + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache-entry-noop.worker.ts +var import_fs5 = __toESM(require("fs")); +var import_path8 = __toESM(require("path")); +var import_url5 = __toESM(require("url")); +var contents5; +function cache_entry_noop_worker_default() { + if (contents5 !== void 0) + return contents5; + const filePath = import_path8.default.join(__dirname, "workers", "cache/cache-entry-noop.worker.js"); + contents5 = import_fs5.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url5.default.pathToFileURL(filePath); + return contents5; +} + +// src/plugins/cache/index.ts +var import_zod5 = require("zod"); + +// src/plugins/shared/index.ts +var import_crypto = __toESM(require("crypto")); +var import_fs7 = require("fs"); +var import_promises3 = __toESM(require("fs/promises")); +var import_path10 = __toESM(require("path")); +var import_url8 = require("url"); +var import_zod4 = require("zod"); + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/object-entry.worker.ts +var import_fs6 = __toESM(require("fs")); +var import_path9 = __toESM(require("path")); +var import_url6 = __toESM(require("url")); +var contents6; +function object_entry_worker_default() { + if (contents6 !== void 0) + return contents6; + const filePath = import_path9.default.join(__dirname, "workers", "shared/object-entry.worker.js"); + contents6 = import_fs6.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url6.default.pathToFileURL(filePath); + return contents6; +} + +// src/plugins/shared/constants.ts +var SOCKET_ENTRY = "entry"; +var SOCKET_ENTRY_LOCAL = "entry:local"; +var SOCKET_DIRECT_PREFIX = "direct"; +function getDirectSocketName(workerIndex, entrypoint) { + return `${SOCKET_DIRECT_PREFIX}:${workerIndex}:${entrypoint}`; +} +var SERVICE_LOOPBACK = "loopback"; +var HOST_CAPNP_CONNECT = "miniflare-unsafe-internal-capnp-connect"; +var WORKER_BINDING_SERVICE_LOOPBACK = { + name: CoreBindings.SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } +}; +var WORKER_BINDING_ENABLE_CONTROL_ENDPOINTS = { + name: SharedBindings.MAYBE_JSON_ENABLE_CONTROL_ENDPOINTS, + json: "true" +}; +var WORKER_BINDING_ENABLE_STICKY_BLOBS = { + name: SharedBindings.MAYBE_JSON_ENABLE_STICKY_BLOBS, + json: "true" +}; +var enableControlEndpoints = false; +function getMiniflareObjectBindings(unsafeStickyBlobs) { + const result = []; + if (enableControlEndpoints) { + result.push(WORKER_BINDING_ENABLE_CONTROL_ENDPOINTS); + } + if (unsafeStickyBlobs) { + result.push(WORKER_BINDING_ENABLE_STICKY_BLOBS); + } + return result; +} +function _enableControlEndpoints() { + enableControlEndpoints = true; +} +function objectEntryWorker(durableObjectNamespace, namespace) { + return { + compatibilityDate: "2023-07-24", + modules: [ + { name: "object-entry.worker.js", esModule: object_entry_worker_default() } + ], + bindings: [ + { name: SharedBindings.TEXT_NAMESPACE, text: namespace }, + { + name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT, + durableObjectNamespace + } + ] + }; +} +var kUnsafeEphemeralUniqueKey = Symbol.for( + "miniflare.kUnsafeEphemeralUniqueKey" +); + +// src/plugins/shared/routing.ts +var import_url7 = require("url"); +var RouterError = class extends MiniflareError { +}; +function routeSpecificity(url14) { + const hostParts = url14.host.split("."); + let hostScore = hostParts.length; + if (hostParts[0] === "*") + hostScore -= 2; + const pathParts = url14.pathname.split("/"); + let pathScore = pathParts.length; + if (pathParts[pathParts.length - 1] === "*") + pathScore -= 2; + return hostScore * 26 + pathScore; +} +function parseRoutes(allRoutes) { + const routes = []; + for (const [target, targetRoutes] of allRoutes) { + for (const route of targetRoutes) { + const hasProtocol = /^[a-z0-9+\-.]+:\/\//i.test(route); + let urlInput = route; + if (!hasProtocol) + urlInput = `https://${urlInput}`; + const url14 = new import_url7.URL(urlInput); + const specificity = routeSpecificity(url14); + const protocol = hasProtocol ? url14.protocol : void 0; + const internationalisedAllowHostnamePrefix = url14.hostname.startsWith("xn--*"); + const allowHostnamePrefix = url14.hostname.startsWith("*") || internationalisedAllowHostnamePrefix; + const anyHostname = url14.hostname === "*"; + if (allowHostnamePrefix && !anyHostname) { + let hostname = url14.hostname; + if (internationalisedAllowHostnamePrefix) { + hostname = (0, import_url7.domainToUnicode)(hostname); + } + url14.hostname = hostname.substring(1); + } + const allowPathSuffix = url14.pathname.endsWith("*"); + if (allowPathSuffix) { + url14.pathname = url14.pathname.substring(0, url14.pathname.length - 1); + } + if (url14.search) { + throw new RouterError( + "ERR_QUERY_STRING", + `Route "${route}" for "${target}" contains a query string. This is not allowed.` + ); + } + if (url14.toString().includes("*") && !anyHostname) { + throw new RouterError( + "ERR_INFIX_WILDCARD", + `Route "${route}" for "${target}" contains an infix wildcard. This is not allowed.` + ); + } + routes.push({ + target, + route, + specificity, + protocol, + allowHostnamePrefix, + hostname: anyHostname ? "" : url14.hostname, + path: url14.pathname, + allowPathSuffix + }); + } + } + routes.sort((a, b) => { + if (a.specificity === b.specificity) { + return b.route.length - a.route.length; + } else { + return b.specificity - a.specificity; + } + }); + return routes; +} + +// src/plugins/shared/index.ts +var DEFAULT_PERSIST_ROOT = ".mf"; +var PersistenceSchema = import_zod4.z.union([import_zod4.z.boolean(), import_zod4.z.string().url(), PathSchema]).optional(); +var kProxyNodeBinding = Symbol("kProxyNodeBinding"); +function namespaceKeys(namespaces) { + if (Array.isArray(namespaces)) { + return namespaces; + } else if (namespaces !== void 0) { + return Object.keys(namespaces); + } else { + return []; + } +} +function namespaceEntries(namespaces) { + if (Array.isArray(namespaces)) { + return namespaces.map((bindingName) => [bindingName, bindingName]); + } else if (namespaces !== void 0) { + return Object.entries(namespaces); + } else { + return []; + } +} +function maybeParseURL(url14) { + if (typeof url14 !== "string" || import_path10.default.isAbsolute(url14)) + return; + try { + return new URL(url14); + } catch { + } +} +function getPersistPath(pluginName, tmpPath, persist) { + const memoryishPath = import_path10.default.join(tmpPath, pluginName); + if (persist === void 0 || persist === false) { + return memoryishPath; + } + const url14 = maybeParseURL(persist); + if (url14 !== void 0) { + if (url14.protocol === "memory:") { + return memoryishPath; + } else if (url14.protocol === "file:") { + return (0, import_url8.fileURLToPath)(url14); + } + throw new MiniflareCoreError( + "ERR_PERSIST_UNSUPPORTED", + `Unsupported "${url14.protocol}" persistence protocol for storage: ${url14.href}` + ); + } + return persist === true ? import_path10.default.join(DEFAULT_PERSIST_ROOT, pluginName) : persist; +} +function durableObjectNamespaceIdFromName(uniqueKey, name) { + const key = import_crypto.default.createHash("sha256").update(uniqueKey).digest(); + const nameHmac = import_crypto.default.createHmac("sha256", key).update(name).digest().subarray(0, 16); + const hmac = import_crypto.default.createHmac("sha256", key).update(nameHmac).digest().subarray(0, 16); + return Buffer.concat([nameHmac, hmac]).toString("hex"); +} +async function migrateDatabase(log, uniqueKey, persistPath, namespace) { + const sanitisedNamespace = sanitisePath(namespace); + const previousDir = import_path10.default.join(persistPath, sanitisedNamespace); + const previousPath = import_path10.default.join(previousDir, "db.sqlite"); + const previousWalPath = import_path10.default.join(previousDir, "db.sqlite-wal"); + if (!(0, import_fs7.existsSync)(previousPath)) + return; + const id = durableObjectNamespaceIdFromName(uniqueKey, namespace); + const newDir = import_path10.default.join(persistPath, uniqueKey); + const newPath = import_path10.default.join(newDir, `${id}.sqlite`); + const newWalPath = import_path10.default.join(newDir, `${id}.sqlite-wal`); + if ((0, import_fs7.existsSync)(newPath)) { + log.debug( + `Not migrating ${previousPath} to ${newPath} as it already exists` + ); + return; + } + log.debug(`Migrating ${previousPath} to ${newPath}...`); + await import_promises3.default.mkdir(newDir, { recursive: true }); + try { + await import_promises3.default.copyFile(previousPath, newPath); + if ((0, import_fs7.existsSync)(previousWalPath)) { + await import_promises3.default.copyFile(previousWalPath, newWalPath); + } + await import_promises3.default.unlink(previousPath); + await import_promises3.default.unlink(previousWalPath); + } catch (e) { + log.warn(`Error migrating ${previousPath} to ${newPath}: ${e}`); + } +} + +// src/plugins/cache/index.ts +var CacheOptionsSchema = import_zod5.z.object({ + cache: import_zod5.z.boolean().optional(), + cacheWarnUsage: import_zod5.z.boolean().optional() +}); +var CacheSharedOptionsSchema = import_zod5.z.object({ + cachePersist: PersistenceSchema +}); +var CACHE_PLUGIN_NAME = "cache"; +var CACHE_STORAGE_SERVICE_NAME = `${CACHE_PLUGIN_NAME}:storage`; +var CACHE_SERVICE_PREFIX = `${CACHE_PLUGIN_NAME}:cache`; +var CACHE_OBJECT_CLASS_NAME = "CacheObject"; +var CACHE_OBJECT = { + serviceName: CACHE_SERVICE_PREFIX, + className: CACHE_OBJECT_CLASS_NAME +}; +function getCacheServiceName(workerIndex) { + return `${CACHE_PLUGIN_NAME}:${workerIndex}`; +} +var CACHE_PLUGIN = { + options: CacheOptionsSchema, + sharedOptions: CacheSharedOptionsSchema, + getBindings() { + return []; + }, + getNodeBindings() { + return {}; + }, + async getServices({ + sharedOptions, + options, + workerIndex, + tmpPath, + unsafeStickyBlobs + }) { + const cache = options.cache ?? true; + const cacheWarnUsage = options.cacheWarnUsage ?? false; + let entryWorker; + if (cache) { + entryWorker = { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { name: "cache-entry.worker.js", esModule: cache_entry_worker_default() } + ], + bindings: [ + { + name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT, + durableObjectNamespace: CACHE_OBJECT + }, + { + name: CacheBindings.MAYBE_JSON_CACHE_WARN_USAGE, + json: JSON.stringify(cacheWarnUsage) + } + ] + }; + } else { + entryWorker = { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { + name: "cache-entry-noop.worker.js", + esModule: cache_entry_noop_worker_default() + } + ] + }; + } + const services = [ + { name: getCacheServiceName(workerIndex), worker: entryWorker } + ]; + if (cache) { + const uniqueKey = `miniflare-${CACHE_OBJECT_CLASS_NAME}`; + const persist = sharedOptions.cachePersist; + const persistPath = getPersistPath(CACHE_PLUGIN_NAME, tmpPath, persist); + await import_promises4.default.mkdir(persistPath, { recursive: true }); + const storageService = { + name: CACHE_STORAGE_SERVICE_NAME, + disk: { path: persistPath, writable: true } + }; + const objectService = { + name: CACHE_SERVICE_PREFIX, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { + name: "cache.worker.js", + esModule: cache_worker_default() + } + ], + durableObjectNamespaces: [ + { + className: CACHE_OBJECT_CLASS_NAME, + uniqueKey + } + ], + // Store Durable Object SQL databases in persist path + durableObjectStorage: { localDisk: CACHE_STORAGE_SERVICE_NAME }, + // Bind blob disk directory service to object + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_BLOBS, + service: { name: CACHE_STORAGE_SERVICE_NAME } + }, + { + name: SharedBindings.MAYBE_SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } + }, + ...getMiniflareObjectBindings(unsafeStickyBlobs) + ] + } + }; + services.push(storageService, objectService); + } + return services; + }, + getPersistPath({ cachePersist }, tmpPath) { + return getPersistPath(CACHE_PLUGIN_NAME, tmpPath, cachePersist); + } +}; + +// src/plugins/core/index.ts +var import_assert9 = __toESM(require("assert")); +var import_fs11 = require("fs"); +var import_promises6 = __toESM(require("fs/promises")); +var import_path14 = __toESM(require("path")); +var import_stream2 = require("stream"); +var import_tls = __toESM(require("tls")); +var import_util3 = require("util"); +var import_undici8 = require("undici"); + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/core/entry.worker.ts +var import_fs8 = __toESM(require("fs")); +var import_path11 = __toESM(require("path")); +var import_url9 = __toESM(require("url")); +var contents7; +function entry_worker_default() { + if (contents7 !== void 0) + return contents7; + const filePath = import_path11.default.join(__dirname, "workers", "core/entry.worker.js"); + contents7 = import_fs8.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url9.default.pathToFileURL(filePath); + return contents7; +} + +// src/plugins/core/index.ts +var import_zod11 = require("zod"); + +// src/runtime/index.ts +var import_assert4 = __toESM(require("assert")); +var import_child_process = __toESM(require("child_process")); +var import_events2 = require("events"); +var import_readline = __toESM(require("readline")); +var import_stream = require("stream"); +var import_workerd2 = __toESM(require("workerd")); +var import_zod6 = require("zod"); + +// src/runtime/config/index.ts +var import_capnp_ts = require("capnp-ts"); + +// src/runtime/config/workerd.ts +var import_workerd_capnp = __toESM(require_workerd_capnp()); +var kVoid = Symbol("kVoid"); + +// src/runtime/config/index.ts +var import_workerd_capnp2 = __toESM(require_workerd_capnp()); +function capitalize(str) { + return str.length > 0 ? str[0].toUpperCase() + str.substring(1) : str; +} +function encodeCapnpStruct(obj, struct) { + const anyStruct = struct; + for (const [key, value] of Object.entries(obj)) { + const capitalized = capitalize(key); + if (value instanceof Uint8Array) { + const newData = anyStruct[`init${capitalized}`](value.byteLength); + newData.copyBuffer(value); + } else if (Array.isArray(value)) { + const newList = anyStruct[`init${capitalized}`](value.length); + for (let i = 0; i < value.length; i++) { + if (typeof value[i] === "object") { + encodeCapnpStruct(value[i], newList.get(i)); + } else { + newList.set(i, value[i]); + } + } + } else if (typeof value === "object") { + const newStruct = anyStruct[`init${capitalized}`](); + encodeCapnpStruct(value, newStruct); + } else if (value === kVoid) { + anyStruct[`set${capitalized}`](); + } else if (value !== void 0) { + anyStruct[`set${capitalized}`](value); + } + } +} +function serializeConfig(config) { + const message = new import_capnp_ts.Message(); + const struct = message.initRoot(import_workerd_capnp2.Config); + encodeCapnpStruct(config, struct); + return Buffer.from(message.toArrayBuffer()); +} + +// src/runtime/index.ts +var ControlMessageSchema = import_zod6.z.discriminatedUnion("event", [ + import_zod6.z.object({ + event: import_zod6.z.literal("listen"), + socket: import_zod6.z.string(), + port: import_zod6.z.number() + }), + import_zod6.z.object({ + event: import_zod6.z.literal("listen-inspector"), + port: import_zod6.z.number() + }) +]); +var kInspectorSocket = Symbol("kInspectorSocket"); +async function waitForPorts(stream, options) { + if (options?.signal?.aborted) + return; + const lines = import_readline.default.createInterface(stream); + const abortListener = () => lines.close(); + options?.signal?.addEventListener("abort", abortListener, { once: true }); + const requiredSockets = Array.from(options.requiredSockets); + const socketPorts = /* @__PURE__ */ new Map(); + try { + for await (const line of lines) { + const message = ControlMessageSchema.safeParse(JSON.parse(line)); + if (!message.success) + continue; + const data = message.data; + const socket = data.event === "listen-inspector" ? kInspectorSocket : data.socket; + const index = requiredSockets.indexOf(socket); + if (index === -1) + continue; + socketPorts.set(socket, data.port); + requiredSockets.splice(index, 1); + if (requiredSockets.length === 0) + return socketPorts; + } + } finally { + options?.signal?.removeEventListener("abort", abortListener); + } +} +function waitForExit(process2) { + return new Promise((resolve) => { + process2.once("exit", () => resolve()); + }); +} +function pipeOutput(stdout, stderr) { + import_readline.default.createInterface(stdout).on("line", (data) => console.log(data)); + import_readline.default.createInterface(stderr).on("line", (data) => console.error(red(data))); +} +function getRuntimeCommand() { + return process.env.MINIFLARE_WORKERD_PATH ?? import_workerd2.default; +} +function getRuntimeArgs(options) { + const args = [ + "serve", + // Required to use binary capnp config + "--binary", + // Required to use compatibility flags without a default-on date, + // (e.g. "streams_enable_constructors"), see https://github.com/cloudflare/workerd/pull/21 + "--experimental", + `--socket-addr=${SOCKET_ENTRY}=${options.entryAddress}`, + `--external-addr=${SERVICE_LOOPBACK}=${options.loopbackAddress}`, + // Configure extra pipe for receiving control messages (e.g. when ready) + "--control-fd=3", + // Read config from stdin + "-" + ]; + if (options.inspectorAddress !== void 0) { + args.push(`--inspector-addr=${options.inspectorAddress}`); + } + if (options.verbose) { + args.push("--verbose"); + } + return args; +} +var Runtime = class { + #process; + #processExitPromise; + async updateConfig(configBuffer, options) { + await this.dispose(); + const command = getRuntimeCommand(); + const args = getRuntimeArgs(options); + const FORCE_COLOR2 = $.enabled ? "1" : "0"; + const runtimeProcess = import_child_process.default.spawn(command, args, { + stdio: ["pipe", "pipe", "pipe", "pipe"], + env: { ...process.env, FORCE_COLOR: FORCE_COLOR2 } + }); + this.#process = runtimeProcess; + this.#processExitPromise = waitForExit(runtimeProcess); + const handleRuntimeStdio = options.handleRuntimeStdio ?? pipeOutput; + handleRuntimeStdio(runtimeProcess.stdout, runtimeProcess.stderr); + const controlPipe = runtimeProcess.stdio[3]; + (0, import_assert4.default)(controlPipe instanceof import_stream.Readable); + runtimeProcess.stdin.write(configBuffer); + runtimeProcess.stdin.end(); + await (0, import_events2.once)(runtimeProcess.stdin, "finish"); + return waitForPorts(controlPipe, options); + } + dispose() { + this.#process?.kill("SIGKILL"); + return this.#processExitPromise; + } +}; + +// src/plugins/do/index.ts +var import_promises5 = __toESM(require("fs/promises")); +var import_zod7 = require("zod"); +var DurableObjectsOptionsSchema = import_zod7.z.object({ + durableObjects: import_zod7.z.record( + import_zod7.z.union([ + import_zod7.z.string(), + import_zod7.z.object({ + className: import_zod7.z.string(), + scriptName: import_zod7.z.string().optional(), + // Allow `uniqueKey` to be customised. We use in Wrangler when setting + // up stub Durable Objects that proxy requests to Durable Objects in + // another `workerd` process, to ensure the IDs created by the stub + // object can be used by the real object too. + unsafeUniqueKey: import_zod7.z.union([import_zod7.z.string(), import_zod7.z.literal(kUnsafeEphemeralUniqueKey)]).optional(), + // Prevents the Durable Object being evicted. + unsafePreventEviction: import_zod7.z.boolean().optional() + }) + ]) + ).optional() +}); +var DurableObjectsSharedOptionsSchema = import_zod7.z.object({ + durableObjectsPersist: PersistenceSchema +}); +function normaliseDurableObject(designator) { + const isObject = typeof designator === "object"; + const className = isObject ? designator.className : designator; + const serviceName = isObject && designator.scriptName !== void 0 ? getUserServiceName(designator.scriptName) : void 0; + const unsafeUniqueKey = isObject ? designator.unsafeUniqueKey : void 0; + const unsafePreventEviction = isObject ? designator.unsafePreventEviction : void 0; + return { className, serviceName, unsafeUniqueKey, unsafePreventEviction }; +} +var DURABLE_OBJECTS_PLUGIN_NAME = "do"; +var DURABLE_OBJECTS_STORAGE_SERVICE_NAME = `${DURABLE_OBJECTS_PLUGIN_NAME}:storage`; +var DURABLE_OBJECTS_PLUGIN = { + options: DurableObjectsOptionsSchema, + sharedOptions: DurableObjectsSharedOptionsSchema, + getBindings(options) { + return Object.entries(options.durableObjects ?? {}).map( + ([name, klass]) => { + const { className, serviceName } = normaliseDurableObject(klass); + return { + name, + durableObjectNamespace: { className, serviceName } + }; + } + ); + }, + getNodeBindings(options) { + const objects = Object.keys(options.durableObjects ?? {}); + return Object.fromEntries(objects.map((name) => [name, kProxyNodeBinding])); + }, + async getServices({ + sharedOptions, + tmpPath, + durableObjectClassNames, + unsafeEphemeralDurableObjects + }) { + let hasDurableObjects = false; + for (const classNames of durableObjectClassNames.values()) { + if (classNames.size > 0) { + hasDurableObjects = true; + break; + } + } + if (!hasDurableObjects) + return; + if (unsafeEphemeralDurableObjects) + return; + const storagePath = getPersistPath( + DURABLE_OBJECTS_PLUGIN_NAME, + tmpPath, + sharedOptions.durableObjectsPersist + ); + await import_promises5.default.mkdir(storagePath, { recursive: true }); + return [ + { + // Note this service will be de-duped by name if multiple Workers create + // it. Each Worker will have the same `sharedOptions` though, so this + // isn't a problem. + name: DURABLE_OBJECTS_STORAGE_SERVICE_NAME, + disk: { path: storagePath, writable: true } + } + ]; + }, + getPersistPath({ durableObjectsPersist }, tmpPath) { + return getPersistPath( + DURABLE_OBJECTS_PLUGIN_NAME, + tmpPath, + durableObjectsPersist + ); + } +}; + +// src/plugins/core/constants.ts +var CORE_PLUGIN_NAME = "core"; +var SERVICE_ENTRY = `${CORE_PLUGIN_NAME}:entry`; +var SERVICE_USER_PREFIX = `${CORE_PLUGIN_NAME}:user`; +var SERVICE_BUILTIN_PREFIX = `${CORE_PLUGIN_NAME}:builtin`; +var SERVICE_CUSTOM_PREFIX = `${CORE_PLUGIN_NAME}:custom`; +function getUserServiceName(workerName = "") { + return `${SERVICE_USER_PREFIX}:${workerName}`; +} +var CUSTOM_SERVICE_KNOWN_OUTBOUND = "outbound"; +function getBuiltinServiceName(workerIndex, kind, bindingName) { + return `${SERVICE_BUILTIN_PREFIX}:${workerIndex}:${kind}${bindingName}`; +} +function getCustomServiceName(workerIndex, kind, bindingName) { + return `${SERVICE_CUSTOM_PREFIX}:${workerIndex}:${kind}${bindingName}`; +} + +// src/plugins/core/modules.ts +var import_assert5 = __toESM(require("assert")); +var import_fs9 = require("fs"); +var import_module = require("module"); +var import_path12 = __toESM(require("path")); +var import_url10 = require("url"); +var import_util = require("util"); +var import_acorn = require("acorn"); +var import_acorn_walk = require("acorn-walk"); +var import_zod8 = require("zod"); +var SUGGEST_BUNDLE = "If you're trying to import an npm package, you'll need to bundle your Worker first."; +var SUGGEST_NODE = "If you're trying to import a Node.js built-in module, or an npm package that uses Node.js built-ins, you'll either need to:\n- Bundle your Worker, configuring your bundler to polyfill Node.js built-ins\n- Configure your bundler to load Workers-compatible builds by changing the main fields/conditions\n- Enable the `nodejs_compat` compatibility flag and use the `NodeJsCompatModule` module type\n- Find an alternative package that doesn't require Node.js built-ins"; +var builtinModulesWithPrefix = import_module.builtinModules.concat( + import_module.builtinModules.map((module2) => `node:${module2}`) +); +function buildStringScriptPath(workerIndex) { + return `script:${workerIndex}`; +} +var stringScriptRegexp = /^script:(\d+)$/; +function maybeGetStringScriptPathIndex(scriptPath) { + const match = stringScriptRegexp.exec(scriptPath); + return match === null ? void 0 : parseInt(match[1]); +} +var ModuleRuleTypeSchema = import_zod8.z.enum([ + "ESModule", + "CommonJS", + "NodeJsCompatModule", + "Text", + "Data", + "CompiledWasm", + "PythonModule", + "PythonRequirement" +]); +var ModuleRuleSchema = import_zod8.z.object({ + type: ModuleRuleTypeSchema, + include: import_zod8.z.string().array(), + fallthrough: import_zod8.z.boolean().optional() +}); +var ModuleDefinitionSchema = import_zod8.z.object({ + type: ModuleRuleTypeSchema, + path: PathSchema, + contents: import_zod8.z.string().or(import_zod8.z.instanceof(Uint8Array)).optional() +}); +var SourceOptionsSchema = import_zod8.z.union([ + import_zod8.z.object({ + // Manually defined modules + // (used by Wrangler which has its own module collection code) + modules: import_zod8.z.array(ModuleDefinitionSchema), + // `modules` "name"s will be their paths relative to this value. + // This ensures file paths in stack traces are correct. + modulesRoot: PathSchema.optional() + }), + import_zod8.z.object({ + script: import_zod8.z.string(), + // Optional script path for resolving modules, and stack traces file names + scriptPath: PathSchema.optional(), + // Automatically collect modules by parsing `script` if `true`, or treat as + // service-worker if `false` + modules: import_zod8.z.boolean().optional(), + // How to interpret automatically collected modules + modulesRules: import_zod8.z.array(ModuleRuleSchema).optional(), + // `modules` "name"s will be their paths relative to this value. + // This ensures file paths in stack traces are correct. + modulesRoot: PathSchema.optional() + }), + import_zod8.z.object({ + scriptPath: PathSchema, + // Automatically collect modules by parsing `scriptPath` if `true`, or treat + // as service-worker if `false` + modules: import_zod8.z.boolean().optional(), + // How to interpret automatically collected modules + modulesRules: import_zod8.z.array(ModuleRuleSchema).optional(), + // `modules` "name"s will be their paths relative to this value. + // This ensures file paths in stack traces are correct. + modulesRoot: PathSchema.optional() + }) +]); +var DEFAULT_MODULE_RULES = [ + { type: "ESModule", include: ["**/*.mjs"] }, + { type: "CommonJS", include: ["**/*.js", "**/*.cjs"] } +]; +function compileModuleRules(rules) { + const compiledRules = []; + const finalisedTypes = /* @__PURE__ */ new Set(); + for (const rule of rules) { + if (finalisedTypes.has(rule.type)) + continue; + compiledRules.push({ + type: rule.type, + include: globsToRegExps(rule.include) + }); + if (!rule.fallthrough) + finalisedTypes.add(rule.type); + } + return compiledRules; +} +function moduleName(modulesRoot, modulePath) { + const name = import_path12.default.relative(modulesRoot, modulePath); + return import_path12.default.sep === "\\" ? name.replaceAll("\\", "/") : name; +} +function withSourceURL(script, scriptPath) { + if (script.lastIndexOf("//# sourceURL=") !== -1) + return script; + let scriptURL = scriptPath; + if (maybeGetStringScriptPathIndex(scriptPath) === void 0) { + scriptURL = (0, import_url10.pathToFileURL)(scriptPath); + } + const sourceURL = ` +//# sourceURL=${scriptURL} +`; + return script + sourceURL; +} +function getResolveErrorPrefix(referencingPath) { + const relative = import_path12.default.relative("", referencingPath); + return `Unable to resolve "${relative}" dependency`; +} +var ModuleLocator = class { + constructor(modulesRoot, additionalModuleNames, rules = [], compatibilityFlags) { + this.modulesRoot = modulesRoot; + this.additionalModuleNames = additionalModuleNames; + rules = rules.concat(DEFAULT_MODULE_RULES); + this.#compiledRules = compileModuleRules(rules); + this.#nodejsCompat = compatibilityFlags?.includes("nodejs_compat") ?? false; + } + #compiledRules; + #nodejsCompat; + #visitedPaths = /* @__PURE__ */ new Set(); + modules = []; + visitEntrypoint(code, modulePath) { + if (this.#visitedPaths.has(modulePath)) + return; + this.#visitedPaths.add(modulePath); + this.#visitJavaScriptModule(code, modulePath, "ESModule"); + } + #visitJavaScriptModule(code, modulePath, type) { + const name = moduleName(this.modulesRoot, modulePath); + const module2 = createJavaScriptModule(code, name, modulePath, type); + this.modules.push(module2); + const isESM = type === "ESModule"; + let root; + try { + root = (0, import_acorn.parse)(code, { + ecmaVersion: "latest", + sourceType: isESM ? "module" : "script", + locations: true + }); + } catch (e) { + let loc = ""; + if (e.loc?.line !== void 0) { + loc += `:${e.loc.line}`; + if (e.loc.column !== void 0) + loc += `:${e.loc.column}`; + } + throw new MiniflareCoreError( + "ERR_MODULE_PARSE", + `Unable to parse "${name}": ${e.message ?? e} + at ${modulePath}${loc}` + ); + } + const visitors = { + ImportDeclaration: (node) => { + this.#visitModule(modulePath, name, type, node.source); + }, + ExportNamedDeclaration: (node) => { + if (node.source != null) { + this.#visitModule(modulePath, name, type, node.source); + } + }, + ExportAllDeclaration: (node) => { + this.#visitModule(modulePath, name, type, node.source); + }, + ImportExpression: (node) => { + this.#visitModule(modulePath, name, type, node.source); + }, + CallExpression: isESM ? void 0 : (node) => { + const argument = node.arguments[0]; + if (node.callee.type === "Identifier" && node.callee.name === "require" && argument !== void 0) { + this.#visitModule(modulePath, name, type, argument); + } + } + }; + (0, import_acorn_walk.simple)(root, visitors); + } + #visitModule(referencingPath, referencingName, referencingType, specExpression) { + if (specExpression.type !== "Literal" || typeof specExpression.value !== "string") { + const modules = this.modules.map((mod) => { + const def = convertWorkerModule(mod); + return ` { type: "${def.type}", path: "${def.path}" }`; + }); + const modulesConfig = ` new Miniflare({ + ..., + modules: [ +${modules.join(",\n")}, + ... + ] + })`; + const prefix = getResolveErrorPrefix(referencingPath); + let message = `${prefix}: dynamic module specifiers are unsupported. +You must manually define your modules when constructing Miniflare: +${dim(modulesConfig)}`; + if (specExpression.loc != null) { + const { line, column } = specExpression.loc.start; + message += ` + at ${referencingPath}:${line}:${column}`; + } + throw new MiniflareCoreError("ERR_MODULE_DYNAMIC_SPEC", message); + } + const spec = specExpression.value; + const isNodeJsCompatModule = referencingType === "NodeJsCompatModule"; + if (this.#nodejsCompat && spec.startsWith("node:") || spec.startsWith("cloudflare:") || spec.startsWith("workerd:") || isNodeJsCompatModule && builtinModulesWithPrefix.includes(spec) || this.additionalModuleNames.includes(spec)) { + return; + } + if (maybeGetStringScriptPathIndex(referencingName) !== void 0) { + const prefix = getResolveErrorPrefix(referencingPath); + throw new MiniflareCoreError( + "ERR_MODULE_STRING_SCRIPT", + `${prefix}: imports are unsupported in string \`script\` without defined \`scriptPath\`` + ); + } + const identifier = import_path12.default.resolve(import_path12.default.dirname(referencingPath), spec); + const name = moduleName(this.modulesRoot, identifier); + if (this.#visitedPaths.has(identifier)) + return; + this.#visitedPaths.add(identifier); + const rule = this.#compiledRules.find( + (rule2) => testRegExps(rule2.include, identifier) + ); + if (rule === void 0) { + const prefix = getResolveErrorPrefix(referencingPath); + const isBuiltin = builtinModulesWithPrefix.includes(spec); + const suggestion = isBuiltin ? SUGGEST_NODE : SUGGEST_BUNDLE; + throw new MiniflareCoreError( + "ERR_MODULE_RULE", + `${prefix} "${spec}": no matching module rules. +${suggestion}` + ); + } + const data = (0, import_fs9.readFileSync)(identifier); + switch (rule.type) { + case "ESModule": + case "CommonJS": + case "NodeJsCompatModule": + const code = data.toString("utf8"); + this.#visitJavaScriptModule(code, identifier, rule.type); + break; + case "Text": + this.modules.push({ name, text: data.toString("utf8") }); + break; + case "Data": + this.modules.push({ name, data }); + break; + case "CompiledWasm": + this.modules.push({ name, wasm: data }); + break; + case "PythonModule": + this.modules.push({ name, pythonModule: data.toString("utf-8") }); + break; + case "PythonRequirement": + this.modules.push({ name, pythonRequirement: data.toString("utf-8") }); + break; + default: + const exhaustive = rule.type; + import_assert5.default.fail(`Unreachable: ${exhaustive} modules are unsupported`); + } + } +}; +function createJavaScriptModule(code, name, modulePath, type) { + code = withSourceURL(code, modulePath); + if (type === "ESModule") { + return { name, esModule: code }; + } else if (type === "CommonJS") { + return { name, commonJsModule: code }; + } else if (type === "NodeJsCompatModule") { + return { name, nodeJsCompatModule: code }; + } + const exhaustive = type; + import_assert5.default.fail(`Unreachable: ${exhaustive} JavaScript modules are unsupported`); +} +var encoder = new import_util.TextEncoder(); +var decoder = new import_util.TextDecoder(); +function contentsToString(contents14) { + return typeof contents14 === "string" ? contents14 : decoder.decode(contents14); +} +function contentsToArray(contents14) { + return typeof contents14 === "string" ? encoder.encode(contents14) : contents14; +} +function convertModuleDefinition(modulesRoot, def) { + const name = moduleName(modulesRoot, def.path); + const contents14 = def.contents ?? (0, import_fs9.readFileSync)(def.path); + switch (def.type) { + case "ESModule": + case "CommonJS": + case "NodeJsCompatModule": + return createJavaScriptModule( + contentsToString(contents14), + name, + import_path12.default.resolve(modulesRoot, def.path), + def.type + ); + case "Text": + return { name, text: contentsToString(contents14) }; + case "Data": + return { name, data: contentsToArray(contents14) }; + case "CompiledWasm": + return { name, wasm: contentsToArray(contents14) }; + case "PythonModule": + return { name, pythonModule: contentsToString(contents14) }; + case "PythonRequirement": + return { name, pythonRequirement: contentsToString(contents14) }; + default: + const exhaustive = def.type; + import_assert5.default.fail(`Unreachable: ${exhaustive} modules are unsupported`); + } +} +function convertWorkerModule(mod) { + const path23 = mod.name; + (0, import_assert5.default)(path23 !== void 0); + const m = mod; + if ("esModule" in m) + return { path: path23, type: "ESModule" }; + else if ("commonJsModule" in m) + return { path: path23, type: "CommonJS" }; + else if ("nodeJsCompatModule" in m) + return { path: path23, type: "NodeJsCompatModule" }; + else if ("text" in m) + return { path: path23, type: "Text" }; + else if ("data" in m) + return { path: path23, type: "Data" }; + else if ("wasm" in m) + return { path: path23, type: "CompiledWasm" }; + else if ("pythonModule" in m) + return { path: path23, type: "PythonModule" }; + else if ("pythonRequirement" in m) + return { path: path23, type: "PythonRequirement" }; + (0, import_assert5.default)( + !("json" in m || "fallbackService" in m), + "Unreachable: json or fallbackService modules aren't generated" + ); + const exhaustive = m; + import_assert5.default.fail( + `Unreachable: [${Object.keys(exhaustive).join( + ", " + )}] modules are unsupported` + ); +} + +// src/plugins/core/proxy/client.ts +var import_assert8 = __toESM(require("assert")); +var import_crypto2 = __toESM(require("crypto")); +var import_web4 = require("stream/web"); +var import_util2 = __toESM(require("util")); +var import_undici7 = require("undici"); + +// src/plugins/core/proxy/fetch-sync.ts +var import_assert7 = __toESM(require("assert")); +var import_web2 = require("stream/web"); +var import_worker_threads = require("worker_threads"); + +// src/plugins/core/errors/index.ts +var import_fs10 = __toESM(require("fs")); +var import_path13 = __toESM(require("path")); +var import_url11 = require("url"); +var import_zod9 = require("zod"); + +// src/plugins/core/errors/sourcemap.ts +var import_assert6 = __toESM(require("assert")); + +// src/plugins/core/errors/callsite.ts +function parseStack(stack) { + return stack.split("\n").slice(1).map(parseCallSite).filter((site) => site !== void 0); +} +function parseCallSite(line) { + const lineMatch = line.match( + /at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/ + ); + if (!lineMatch) { + return; + } + let object = null; + let method = null; + let functionName = null; + let typeName = null; + let methodName = null; + const isNative = lineMatch[5] === "native"; + if (lineMatch[1]) { + functionName = lineMatch[1]; + let methodStart = functionName.lastIndexOf("."); + if (functionName[methodStart - 1] == ".") + methodStart--; + if (methodStart > 0) { + object = functionName.substring(0, methodStart); + method = functionName.substring(methodStart + 1); + const objectEnd = object.indexOf(".Module"); + if (objectEnd > 0) { + functionName = functionName.substring(objectEnd + 1); + object = object.substring(0, objectEnd); + } + } + } + if (method) { + typeName = object; + methodName = method; + } + if (method === "") { + methodName = null; + functionName = null; + } + return new CallSite({ + typeName, + functionName, + methodName, + fileName: lineMatch[2] || null, + lineNumber: parseInt(lineMatch[3]) || null, + columnNumber: parseInt(lineMatch[4]) || null, + native: isNative + }); +} +var CallSite = class { + constructor(opts) { + this.opts = opts; + } + getThis() { + return null; + } + getTypeName() { + return this.opts.typeName; + } + // eslint-disable-next-line @typescript-eslint/ban-types + getFunction() { + return void 0; + } + getFunctionName() { + return this.opts.functionName; + } + getMethodName() { + return this.opts.methodName; + } + getFileName() { + return this.opts.fileName ?? void 0; + } + getScriptNameOrSourceURL() { + return this.opts.fileName; + } + getLineNumber() { + return this.opts.lineNumber; + } + getColumnNumber() { + return this.opts.columnNumber; + } + getEvalOrigin() { + return void 0; + } + isToplevel() { + return false; + } + isEval() { + return false; + } + isNative() { + return this.opts.native; + } + isConstructor() { + return false; + } + isAsync() { + return false; + } + isPromiseAll() { + return false; + } + isPromiseAny() { + return false; + } + getPromiseIndex() { + return null; + } +}; + +// src/plugins/core/errors/sourcemap.ts +function getFreshSourceMapSupport() { + const resolvedSupportPath = require.resolve("@cspotcode/source-map-support"); + const originalSymbolFor = Symbol.for; + const originalSupport = require.cache[resolvedSupportPath]; + try { + Symbol.for = (key) => { + import_assert6.default.strictEqual(key, "source-map-support/sharedData"); + return Symbol(key); + }; + delete require.cache[resolvedSupportPath]; + return require(resolvedSupportPath); + } finally { + Symbol.for = originalSymbolFor; + require.cache[resolvedSupportPath] = originalSupport; + } +} +var sourceMapInstallBaseOptions = { + environment: "node", + // Don't add Node `uncaughtException` handler + handleUncaughtExceptions: false, + // Don't hook Node `require` function + hookRequire: false, + redirectConflictingLibrary: false, + // Make sure we're using fresh copies of files (i.e. between `setOptions()`) + emptyCacheBetweenOperations: true, + // Always remove existing retrievers when calling `install()`, we should be + // specifying them each time we want to source map + overrideRetrieveFile: true, + overrideRetrieveSourceMap: true +}; +var sourceMapper; +function getSourceMapper() { + if (sourceMapper !== void 0) + return sourceMapper; + const support = getFreshSourceMapSupport(); + const originalPrepareStackTrace = Error.prepareStackTrace; + support.install(sourceMapInstallBaseOptions); + const prepareStackTrace = Error.prepareStackTrace; + (0, import_assert6.default)(prepareStackTrace !== void 0); + Error.prepareStackTrace = originalPrepareStackTrace; + sourceMapper = (retrieveSourceMap, error) => { + support.install({ + ...sourceMapInstallBaseOptions, + retrieveFile(_file) { + return ""; + }, + retrieveSourceMap + }); + const callSites = parseStack(error.stack ?? ""); + return prepareStackTrace(error, callSites); + }; + return sourceMapper; +} + +// src/plugins/core/errors/index.ts +function maybeGetDiskFile(filePath) { + try { + const contents14 = import_fs10.default.readFileSync(filePath, "utf8"); + return { path: filePath, contents: contents14 }; + } catch (e) { + if (e.code !== "ENOENT") + throw e; + } +} +function maybeGetFile(workerSrcOpts, fileSpecifier) { + const maybeUrl = maybeParseURL(fileSpecifier); + if (maybeUrl !== void 0 && maybeUrl.protocol === "file:") { + const filePath = (0, import_url11.fileURLToPath)(maybeUrl); + for (const srcOpts of workerSrcOpts) { + if (Array.isArray(srcOpts.modules)) { + const modulesRoot = srcOpts.modulesRoot ?? ""; + for (const module2 of srcOpts.modules) { + if (module2.contents !== void 0 && import_path13.default.resolve(modulesRoot, module2.path) === filePath) { + const contents14 = contentsToString(module2.contents); + return { path: filePath, contents: contents14 }; + } + } + } else if ("script" in srcOpts && "scriptPath" in srcOpts && srcOpts.script !== void 0 && srcOpts.scriptPath !== void 0) { + const modulesRoot = srcOpts.modules && srcOpts.modulesRoot || ""; + if (import_path13.default.resolve(modulesRoot, srcOpts.scriptPath) === filePath) { + return { path: filePath, contents: srcOpts.script }; + } + } + } + return maybeGetDiskFile(filePath); + } + const workerIndex = maybeGetStringScriptPathIndex(fileSpecifier); + if (workerIndex !== void 0) { + const srcOpts = workerSrcOpts[workerIndex]; + if ("script" in srcOpts && srcOpts.script !== void 0) { + return { contents: srcOpts.script }; + } + } +} +function getSourceMappedStack(workerSrcOpts, error) { + function retrieveSourceMap(fileSpecifier) { + const sourceFile = maybeGetFile(workerSrcOpts, fileSpecifier); + if (sourceFile?.path === void 0) + return null; + const sourceMapRegexp = /# sourceMappingURL=(.+)/g; + const matches = [...sourceFile.contents.matchAll(sourceMapRegexp)]; + if (matches.length === 0) + return null; + const sourceMapMatch = matches[matches.length - 1]; + const root = import_path13.default.dirname(sourceFile.path); + const sourceMapPath = import_path13.default.resolve(root, sourceMapMatch[1]); + const sourceMapFile = maybeGetDiskFile(sourceMapPath); + if (sourceMapFile === void 0) + return null; + return { map: sourceMapFile.contents, url: sourceMapFile.path }; + } + return getSourceMapper()(retrieveSourceMap, error); +} +var JsonErrorSchema = import_zod9.z.lazy( + () => import_zod9.z.object({ + message: import_zod9.z.string().optional(), + name: import_zod9.z.string().optional(), + stack: import_zod9.z.string().optional(), + cause: JsonErrorSchema.optional() + }) +); +var ALLOWED_ERROR_SUBCLASS_CONSTRUCTORS = [ + EvalError, + RangeError, + ReferenceError, + SyntaxError, + TypeError, + URIError +]; +function reviveError(workerSrcOpts, jsonError) { + let cause; + if (jsonError.cause !== void 0) { + cause = reviveError(workerSrcOpts, jsonError.cause); + } + let ctor = Error; + if (jsonError.name !== void 0 && jsonError.name in globalThis) { + const maybeCtor = globalThis[jsonError.name]; + if (ALLOWED_ERROR_SUBCLASS_CONSTRUCTORS.includes(maybeCtor)) { + ctor = maybeCtor; + } + } + const error = new ctor(jsonError.message, { cause }); + if (jsonError.name !== void 0) + error.name = jsonError.name; + error.stack = jsonError.stack; + error.stack = getSourceMappedStack(workerSrcOpts, error); + return error; +} +async function handlePrettyErrorRequest(log, workerSrcOpts, request) { + const caught = JsonErrorSchema.parse(await request.json()); + const error = reviveError(workerSrcOpts, caught); + log.error(error); + const accept = request.headers.get("Accept")?.toLowerCase() ?? ""; + const userAgent = request.headers.get("User-Agent")?.toLowerCase() ?? ""; + const acceptsPrettyError = !userAgent.includes("curl/") && (accept.includes("text/html") || accept.includes("*/*") || accept.includes("text/*")); + if (!acceptsPrettyError) { + return new Response(error.stack, { status: 500 }); + } + const Youch = require("youch"); + const youch = new Youch(error.cause ?? error, { + url: request.cf?.prettyErrorOriginalUrl ?? request.url, + method: request.method, + headers: Object.fromEntries(request.headers) + }); + youch.addLink(() => { + return [ + '\u{1F4DA} Workers Docs', + '\u{1F4AC} Workers Discord' + ].join(""); + }); + return new Response(await youch.toHTML(), { + status: 500, + headers: { "Content-Type": "text/html;charset=utf-8" } + }); +} + +// src/plugins/core/proxy/fetch-sync.ts +var DECODER = new TextDecoder(); +var WORKER_SCRIPT = ( + /* javascript */ + ` +const { createRequire } = require("module"); +const { workerData } = require("worker_threads"); + +// Not using parentPort here so we can call receiveMessageOnPort() in host +const { notifyHandle, port, filename } = workerData; + +// When running Miniflare from Jest, regular 'require("undici")' will fail here +// with "Error: Cannot find module 'undici'". Instead we need to create a +// 'require' using the '__filename' of the host... :( +const actualRequire = createRequire(filename); +const { Pool, fetch } = actualRequire("undici"); + +let dispatcherUrl; +let dispatcher; + +port.addEventListener("message", async (event) => { + const { id, method, url, headers, body } = event.data; + if (dispatcherUrl !== url) { + dispatcherUrl = url; + dispatcher = new Pool(url, { + connect: { rejectUnauthorized: false }, + }); + } + headers["${CoreHeaders.OP_SYNC}"] = "true"; + try { + // body cannot be a ReadableStream, so no need to specify duplex + const response = await fetch(url, { method, headers, body, dispatcher }); + const responseBody = response.headers.get("${CoreHeaders.OP_RESULT_TYPE}") === "ReadableStream" + ? response.body + : await response.arrayBuffer(); + const transferList = responseBody === null ? undefined : [responseBody]; + port.postMessage( + { + id, + response: { + status: response.status, + headers: Object.fromEntries(response.headers), + body: responseBody, + } + }, + transferList + ); + } catch (error) { + try { + port.postMessage({ id, error }); + } catch { + // If error failed to serialise, post simplified version + port.postMessage({ id, error: new Error(String(error)) }); + } + } + Atomics.store(notifyHandle, /* index */ 0, /* value */ 1); + Atomics.notify(notifyHandle, /* index */ 0); +}); +` +); +var SynchronousFetcher = class { + #channel; + #notifyHandle; + #worker; + #nextId = 0; + constructor() { + this.#channel = new import_worker_threads.MessageChannel(); + this.#notifyHandle = new Int32Array(new SharedArrayBuffer(4)); + } + #ensureWorker() { + if (this.#worker !== void 0) + return; + this.#worker = new import_worker_threads.Worker(WORKER_SCRIPT, { + eval: true, + workerData: { + notifyHandle: this.#notifyHandle, + port: this.#channel.port2, + filename: __filename + }, + transferList: [this.#channel.port2] + }); + } + fetch(url14, init2) { + this.#ensureWorker(); + Atomics.store( + this.#notifyHandle, + /* index */ + 0, + /* value */ + 0 + ); + const id = this.#nextId++; + this.#channel.port1.postMessage({ + id, + method: init2.method, + url: url14.toString(), + headers: init2.headers, + body: init2.body + }); + Atomics.wait( + this.#notifyHandle, + /* index */ + 0, + /* value */ + 0 + ); + const message = (0, import_worker_threads.receiveMessageOnPort)( + this.#channel.port1 + )?.message; + (0, import_assert7.default)(message?.id === id); + if ("response" in message) { + const { status, headers: rawHeaders, body } = message.response; + const headers = new import_undici5.Headers(rawHeaders); + const stack = headers.get(CoreHeaders.ERROR_STACK); + if (status === 500 && stack !== null && body !== null) { + (0, import_assert7.default)(!(body instanceof import_web2.ReadableStream)); + const caught = JsonErrorSchema.parse(JSON.parse(DECODER.decode(body))); + throw reviveError([], caught); + } + return { status, headers, body }; + } else { + throw message.error; + } + } + async dispose() { + await this.#worker?.terminate(); + } +}; + +// src/plugins/core/proxy/types.ts +var import_buffer = require("buffer"); +var import_consumers = require("stream/consumers"); +var import_web3 = require("stream/web"); +var import_undici6 = require("undici"); +var NODE_PLATFORM_IMPL = { + // Node's implementation of these classes don't quite match Workers', + // but they're close enough for us + Blob: import_buffer.Blob, + File: import_undici6.File, + Headers: import_undici6.Headers, + Request, + Response, + isReadableStream(value) { + return value instanceof import_web3.ReadableStream; + }, + bufferReadableStream(stream) { + return (0, import_consumers.arrayBuffer)(stream); + }, + unbufferReadableStream(buffer) { + return new import_buffer.Blob([new Uint8Array(buffer)]).stream(); + } +}; + +// src/plugins/core/proxy/client.ts +var kAddress = Symbol("kAddress"); +var kName = Symbol("kName"); +function isNativeTarget(value) { + return typeof value === "object" && value !== null && kAddress in value; +} +var TARGET_GLOBAL = { + [kAddress]: ProxyAddresses.GLOBAL, + [kName]: "global" +}; +var TARGET_ENV = { + [kAddress]: ProxyAddresses.ENV, + [kName]: "env" +}; +var reducers = { + ...structuredSerializableReducers, + ...createHTTPReducers(NODE_PLATFORM_IMPL), + Native(value) { + if (isNativeTarget(value)) + return [value[kAddress], value[kName]]; + } +}; +var revivers = { + ...structuredSerializableRevivers, + ...createHTTPRevivers(NODE_PLATFORM_IMPL) + // `Native` reviver depends on `ProxyStubHandler` methods +}; +var PROXY_SECRET = import_crypto2.default.randomBytes(16); +var PROXY_SECRET_HEX = PROXY_SECRET.toString("hex"); +function isClientError(status) { + return 400 <= status && status < 500; +} +var ProxyClient = class { + #bridge; + constructor(runtimeEntryURL, dispatchFetch) { + this.#bridge = new ProxyClientBridge(runtimeEntryURL, dispatchFetch); + } + // Lazily initialise proxies as required + #globalProxy; + #envProxy; + get global() { + return this.#globalProxy ??= this.#bridge.getProxy(TARGET_GLOBAL); + } + get env() { + return this.#envProxy ??= this.#bridge.getProxy(TARGET_ENV); + } + poisonProxies() { + this.#bridge.poisonProxies(); + this.#globalProxy = void 0; + this.#envProxy = void 0; + } + setRuntimeEntryURL(runtimeEntryURL) { + this.#bridge.url = runtimeEntryURL; + } + dispose() { + return this.#bridge.dispose(); + } +}; +var ProxyClientBridge = class { + constructor(url14, dispatchFetch) { + this.url = url14; + this.dispatchFetch = dispatchFetch; + this.#finalizationRegistry = new FinalizationRegistry(this.#finalizeProxy); + } + // Each proxy stub is initialised with the version stored here. Whenever + // `poisonProxies()` is called, this version is incremented. Before the + // proxy makes any request to `workerd`, it checks the version number here + // matches its own internal version, and throws if not. + #version = 0; + // Whenever the `ProxyServer` returns a native target, it adds a strong + // reference to the "heap" in the singleton object. This prevents the object + // being garbage collected. To solve this, we register the native target + // proxies on the client in a `FinalizationRegistry`. When the proxies get + // garbage collected, we let the `ProxyServer` know it can release the strong + // "heap" reference, as we'll never be able to access it again. Importantly, + // we need to unregister all proxies from the registry when we poison them, + // as the references will be invalid, and a new object with the same address + // may be added to the "heap". + #finalizationRegistry; + // Garbage collection passes will free lots of objects at once. Rather than + // sending a `DELETE` request for each address, we batch finalisations within + // 100ms of each other into one request. This ensures we don't create *lots* + // of TCP connections to `workerd` in `dispatchFetch()` for all the concurrent + // requests. + #finalizeBatch = []; + #finalizeBatchTimeout; + sync = new SynchronousFetcher(); + get version() { + return this.#version; + } + #finalizeProxy = (held) => { + this.#finalizeBatch.push(held); + clearTimeout(this.#finalizeBatchTimeout); + this.#finalizeBatchTimeout = setTimeout(this.#finalizeProxyBatch, 100); + }; + #finalizeProxyBatch = async () => { + const addresses = []; + for (const held of this.#finalizeBatch.splice(0)) { + if (held.version === this.#version) + addresses.push(held.address); + } + if (addresses.length === 0) + return; + try { + await this.dispatchFetch(this.url, { + method: "DELETE", + headers: { + [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX, + [CoreHeaders.OP]: ProxyOps.FREE, + [CoreHeaders.OP_TARGET]: addresses.join(",") + } + }); + } catch { + } + }; + getProxy(target) { + const handler = new ProxyStubHandler(this, target); + const proxy = new Proxy( + { [import_util2.default.inspect.custom]: handler.inspect }, + handler + ); + const held = { + address: target[kAddress], + version: this.#version + }; + this.#finalizationRegistry.register(proxy, held, this); + return proxy; + } + poisonProxies() { + this.#version++; + this.#finalizationRegistry.unregister(this); + } + dispose() { + this.poisonProxies(); + return this.sync.dispose(); + } +}; +var ProxyStubHandler = class { + constructor(bridge, target) { + this.bridge = bridge; + this.target = target; + this.#version = bridge.version; + this.#stringifiedTarget = stringify(this.target, reducers); + } + #version; + #stringifiedTarget; + #knownValues = /* @__PURE__ */ new Map(); + #knownDescriptors = /* @__PURE__ */ new Map(); + #knownOwnKeys; + revivers = { + ...revivers, + Native: (value) => { + (0, import_assert8.default)(Array.isArray(value)); + const [address, name] = value; + (0, import_assert8.default)(typeof address === "number"); + (0, import_assert8.default)(typeof name === "string"); + const target = { [kAddress]: address, [kName]: name }; + if (name === "Promise") { + const resPromise = this.bridge.dispatchFetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX, + [CoreHeaders.OP]: ProxyOps.GET, + // GET without key just gets target + [CoreHeaders.OP_TARGET]: stringify(target, reducers) + } + }); + return this.#parseAsyncResponse(resPromise); + } else { + return this.bridge.getProxy(target); + } + } + }; + get #poisoned() { + return this.#version !== this.bridge.version; + } + #assertSafe() { + if (this.#poisoned) { + throw new Error( + "Attempted to use poisoned stub. Stubs to runtime objects must be re-created after calling `Miniflare#setOptions()` or `Miniflare#dispose()`." + ); + } + } + inspect = (depth, options) => { + const details = { name: this.target[kName], poisoned: this.#poisoned }; + return `ProxyStub ${import_util2.default.inspect(details, options)}`; + }; + #maybeThrow(res, result, caller) { + if (res.status === 500) { + if (typeof result === "object" && result !== null) { + Error.captureStackTrace(result, caller); + } + throw result; + } else { + (0, import_assert8.default)(res.status === 200); + return result; + } + } + async #parseAsyncResponse(resPromise) { + const res = await resPromise; + (0, import_assert8.default)(!isClientError(res.status)); + const typeHeader = res.headers.get(CoreHeaders.OP_RESULT_TYPE); + if (typeHeader === "Promise, ReadableStream") + return res.body; + (0, import_assert8.default)(typeHeader === "Promise"); + let stringifiedResult; + let unbufferedStream; + const stringifiedSizeHeader = res.headers.get( + CoreHeaders.OP_STRINGIFIED_SIZE + ); + if (stringifiedSizeHeader === null) { + stringifiedResult = await res.text(); + } else { + const stringifiedSize = parseInt(stringifiedSizeHeader); + (0, import_assert8.default)(!Number.isNaN(stringifiedSize)); + (0, import_assert8.default)(res.body !== null); + const [buffer, rest] = await readPrefix(res.body, stringifiedSize); + stringifiedResult = buffer.toString(); + unbufferedStream = rest.pipeThrough(new import_web4.TransformStream()); + } + const result = parseWithReadableStreams( + NODE_PLATFORM_IMPL, + { value: stringifiedResult, unbufferedStream }, + this.revivers + ); + return this.#maybeThrow(res, result, this.#parseAsyncResponse); + } + #parseSyncResponse(syncRes, caller) { + (0, import_assert8.default)(!isClientError(syncRes.status)); + (0, import_assert8.default)(syncRes.body !== null); + (0, import_assert8.default)(syncRes.headers.get(CoreHeaders.OP_STRINGIFIED_SIZE) === null); + if (syncRes.body instanceof import_web4.ReadableStream) + return syncRes.body; + const stringifiedResult = DECODER.decode(syncRes.body); + const result = parseWithReadableStreams( + NODE_PLATFORM_IMPL, + { value: stringifiedResult }, + this.revivers + ); + return this.#maybeThrow(syncRes, result, caller); + } + get(_target, key, _receiver) { + this.#assertSafe(); + if (key === kAddress) + return this.target[kAddress]; + if (key === kName) + return this.target[kName]; + if (typeof key === "symbol" || key === "then") + return void 0; + const maybeKnown = this.#knownValues.get(key); + if (maybeKnown !== void 0) + return maybeKnown; + const syncRes = this.bridge.sync.fetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX, + [CoreHeaders.OP]: ProxyOps.GET, + [CoreHeaders.OP_TARGET]: this.#stringifiedTarget, + [CoreHeaders.OP_KEY]: key + } + }); + let result; + if (syncRes.headers.get(CoreHeaders.OP_RESULT_TYPE) === "Function") { + result = this.#createFunction(key); + } else { + result = this.#parseSyncResponse(syncRes, this.get); + } + if ( + // Optimisation: if this property is a function, we assume constant + // prototypes of proxied objects, so it's never going to change + typeof result === "function" || // Optimisation: if this property is a reference, we assume it's never + // going to change. This allows us to reuse the known cache of nested + // objects on multiple access (e.g. reusing `env["..."]` proxy if + // `getR2Bucket()` is called on the same bucket multiple times). + isNativeTarget(result) || // Once a `ReadableStream` sent across proxy, we won't be able to read it + // again in the server, so reuse the same stream for future accesses + // (e.g. accessing `R2ObjectBody#body` multiple times) + result instanceof import_web4.ReadableStream + ) { + this.#knownValues.set(key, result); + } + return result; + } + has(target, key) { + return this.get(target, key, void 0) !== void 0; + } + getOwnPropertyDescriptor(target, key) { + this.#assertSafe(); + if (typeof key === "symbol") + return void 0; + const maybeKnown = this.#knownDescriptors.get(key); + if (maybeKnown !== void 0) + return maybeKnown; + const syncRes = this.bridge.sync.fetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX, + [CoreHeaders.OP]: ProxyOps.GET_OWN_DESCRIPTOR, + [CoreHeaders.OP_KEY]: key, + [CoreHeaders.OP_TARGET]: this.#stringifiedTarget + } + }); + const result = this.#parseSyncResponse( + syncRes, + this.getOwnPropertyDescriptor + ); + this.#knownDescriptors.set(key, result); + return result; + } + ownKeys(_target) { + this.#assertSafe(); + if (this.#knownOwnKeys !== void 0) + return this.#knownOwnKeys; + const syncRes = this.bridge.sync.fetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX, + [CoreHeaders.OP]: ProxyOps.GET_OWN_KEYS, + [CoreHeaders.OP_TARGET]: this.#stringifiedTarget + } + }); + const result = this.#parseSyncResponse(syncRes, this.ownKeys); + this.#knownOwnKeys = result; + return result; + } + getPrototypeOf(_target) { + this.#assertSafe(); + return null; + } + #createFunction(key) { + let knownAsync = false; + const func = { + [key]: (...args) => { + const result = this.#call(key, knownAsync, args, func); + if (!knownAsync && result instanceof Promise) + knownAsync = true; + return result; + } + }[key]; + return func; + } + #call(key, knownAsync, args, caller) { + this.#assertSafe(); + const targetName = this.target[kName]; + if (isFetcherFetch(targetName, key)) + return this.#fetcherFetchCall(args); + const stringified = stringifyWithStreams( + NODE_PLATFORM_IMPL, + args, + reducers, + /* allowUnbufferedStream */ + true + ); + if (knownAsync || // We assume every call with `ReadableStream`/`Blob` arguments is async. + // Note that you can't consume `ReadableStream`/`Blob` synchronously: if + // you tried a similar trick to `SynchronousFetcher`, blocking the main + // thread with `Atomics.wait()` would prevent chunks being read. This + // assumption doesn't hold for `Blob`s and `FormData#{append,set}()`, but + // we should never expose proxies for those APIs to users. + stringified instanceof Promise || // (instanceof Promise if buffered `ReadableStream`/`Blob`s) + stringified.unbufferedStream !== void 0) { + return this.#asyncCall(key, stringified); + } else { + const result = this.#syncCall(key, stringified.value, caller); + if (isR2ObjectWriteHttpMetadata(targetName, key)) { + const arg = args[0]; + (0, import_assert8.default)(arg instanceof import_undici7.Headers); + (0, import_assert8.default)(result instanceof import_undici7.Headers); + for (const [key2, value] of result) + arg.set(key2, value); + return; + } + return result; + } + } + #syncCall(key, stringifiedValue, caller) { + const argsSize = Buffer.byteLength(stringifiedValue).toString(); + const syncRes = this.bridge.sync.fetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX, + [CoreHeaders.OP]: ProxyOps.CALL, + [CoreHeaders.OP_TARGET]: this.#stringifiedTarget, + [CoreHeaders.OP_KEY]: key, + [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize, + "Content-Length": argsSize + }, + body: stringifiedValue + }); + return this.#parseSyncResponse(syncRes, caller); + } + async #asyncCall(key, stringifiedAwaitable) { + const stringified = await stringifiedAwaitable; + let resPromise; + if (stringified.unbufferedStream === void 0) { + const argsSize = Buffer.byteLength(stringified.value).toString(); + resPromise = this.bridge.dispatchFetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX, + [CoreHeaders.OP]: ProxyOps.CALL, + [CoreHeaders.OP_TARGET]: this.#stringifiedTarget, + [CoreHeaders.OP_KEY]: key, + [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize, + "Content-Length": argsSize + }, + body: stringified.value + }); + } else { + const encodedArgs = Buffer.from(stringified.value); + const argsSize = encodedArgs.byteLength.toString(); + const body = prefixStream(encodedArgs, stringified.unbufferedStream); + resPromise = this.bridge.dispatchFetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX, + [CoreHeaders.OP]: ProxyOps.CALL, + [CoreHeaders.OP_TARGET]: this.#stringifiedTarget, + [CoreHeaders.OP_KEY]: key, + [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize + }, + duplex: "half", + body + }); + } + return this.#parseAsyncResponse(resPromise); + } + #fetcherFetchCall(args) { + const request = new Request(...args); + request.headers.set(CoreHeaders.OP_SECRET, PROXY_SECRET_HEX); + request.headers.set(CoreHeaders.OP, ProxyOps.CALL); + request.headers.set(CoreHeaders.OP_TARGET, this.#stringifiedTarget); + request.headers.set(CoreHeaders.OP_KEY, "fetch"); + return this.bridge.dispatchFetch(request); + } +}; + +// src/plugins/core/services.ts +var import_zod10 = require("zod"); +var kCurrentWorker = Symbol.for("miniflare.kCurrentWorker"); +var HttpOptionsHeaderSchema = import_zod10.z.object({ + name: import_zod10.z.string(), + // name should be required + value: import_zod10.z.ostring() + // If omitted, the header will be removed +}); +var HttpOptionsSchema = import_zod10.z.object({ + style: import_zod10.z.nativeEnum(import_workerd_capnp.HttpOptions_Style).optional(), + forwardedProtoHeader: import_zod10.z.ostring(), + cfBlobHeader: import_zod10.z.ostring(), + injectRequestHeaders: HttpOptionsHeaderSchema.array().optional(), + injectResponseHeaders: HttpOptionsHeaderSchema.array().optional() +}).transform((options) => ({ + ...options, + capnpConnectHost: HOST_CAPNP_CONNECT +})); +var TlsOptionsKeypairSchema = import_zod10.z.object({ + privateKey: import_zod10.z.ostring(), + certificateChain: import_zod10.z.ostring() +}); +var TlsOptionsSchema = import_zod10.z.object({ + keypair: TlsOptionsKeypairSchema.optional(), + requireClientCerts: import_zod10.z.oboolean(), + trustBrowserCas: import_zod10.z.oboolean(), + trustedCertificates: import_zod10.z.string().array().optional(), + minVersion: import_zod10.z.nativeEnum(import_workerd_capnp.TlsOptions_Version).optional(), + cipherList: import_zod10.z.ostring() +}); +var NetworkSchema = import_zod10.z.object({ + allow: import_zod10.z.string().array().optional(), + deny: import_zod10.z.string().array().optional(), + tlsOptions: TlsOptionsSchema.optional() +}); +var ExternalServerSchema = import_zod10.z.intersection( + import_zod10.z.object({ address: import_zod10.z.string() }), + // address should be required + import_zod10.z.union([ + import_zod10.z.object({ http: import_zod10.z.optional(HttpOptionsSchema) }), + import_zod10.z.object({ + https: import_zod10.z.optional( + import_zod10.z.object({ + options: HttpOptionsSchema.optional(), + tlsOptions: TlsOptionsSchema.optional(), + certificateHost: import_zod10.z.ostring() + }) + ) + }) + ]) +); +var DiskDirectorySchema = import_zod10.z.object({ + path: import_zod10.z.string(), + // path should be required + writable: import_zod10.z.oboolean() +}); +var ServiceFetchSchema = import_zod10.z.custom((v) => typeof v === "function"); +var ServiceDesignatorSchema = import_zod10.z.union([ + import_zod10.z.string(), + import_zod10.z.literal(kCurrentWorker), + import_zod10.z.object({ + name: import_zod10.z.union([import_zod10.z.string(), import_zod10.z.literal(kCurrentWorker)]), + entrypoint: import_zod10.z.ostring() + }), + import_zod10.z.object({ network: NetworkSchema }), + import_zod10.z.object({ external: ExternalServerSchema }), + import_zod10.z.object({ disk: DiskDirectorySchema }), + ServiceFetchSchema +]); + +// src/plugins/core/index.ts +var trustedCertificates = process.platform === "win32" ? Array.from(import_tls.default.rootCertificates) : []; +if (process.env.NODE_EXTRA_CA_CERTS !== void 0) { + try { + const extra = (0, import_fs11.readFileSync)(process.env.NODE_EXTRA_CA_CERTS, "utf8"); + const pemBegin = "-----BEGIN"; + for (const cert of extra.split(pemBegin)) { + if (cert.trim() !== "") + trustedCertificates.push(pemBegin + cert); + } + } catch { + } +} +var encoder2 = new import_util3.TextEncoder(); +var numericCompare = new Intl.Collator(void 0, { numeric: true }).compare; +function createFetchMock() { + return new import_undici8.MockAgent(); +} +var WrappedBindingSchema = import_zod11.z.object({ + scriptName: import_zod11.z.string(), + entrypoint: import_zod11.z.string().optional(), + bindings: import_zod11.z.record(JsonSchema).optional() +}); +var UnusableStringSchema = import_zod11.z.string().transform(() => void 0); +var UnsafeDirectSocketSchema = import_zod11.z.object({ + host: import_zod11.z.ostring(), + port: import_zod11.z.onumber(), + entrypoint: import_zod11.z.ostring(), + proxy: import_zod11.z.oboolean() +}); +var CoreOptionsSchemaInput = import_zod11.z.intersection( + SourceOptionsSchema, + import_zod11.z.object({ + name: import_zod11.z.string().optional(), + rootPath: UnusableStringSchema.optional(), + compatibilityDate: import_zod11.z.string().optional(), + compatibilityFlags: import_zod11.z.string().array().optional(), + routes: import_zod11.z.string().array().optional(), + bindings: import_zod11.z.record(JsonSchema).optional(), + wasmBindings: import_zod11.z.record(PathSchema).optional(), + textBlobBindings: import_zod11.z.record(PathSchema).optional(), + dataBlobBindings: import_zod11.z.record(PathSchema).optional(), + serviceBindings: import_zod11.z.record(ServiceDesignatorSchema).optional(), + wrappedBindings: import_zod11.z.record(import_zod11.z.union([import_zod11.z.string(), WrappedBindingSchema])).optional(), + outboundService: ServiceDesignatorSchema.optional(), + fetchMock: import_zod11.z.instanceof(import_undici8.MockAgent).optional(), + // TODO(soon): remove this in favour of per-object `unsafeUniqueKey: kEphemeralUniqueKey` + unsafeEphemeralDurableObjects: import_zod11.z.boolean().optional(), + unsafeDirectSockets: UnsafeDirectSocketSchema.array().optional(), + unsafeEvalBinding: import_zod11.z.string().optional(), + unsafeUseModuleFallbackService: import_zod11.z.boolean().optional() + }) +); +var CoreOptionsSchema = CoreOptionsSchemaInput.transform((value) => { + const fetchMock = value.fetchMock; + if (fetchMock !== void 0) { + if (value.outboundService !== void 0) { + throw new MiniflareCoreError( + "ERR_MULTIPLE_OUTBOUNDS", + "Only one of `outboundService` or `fetchMock` may be specified per worker" + ); + } + value.outboundService = (req) => fetch2(req, { dispatcher: fetchMock }); + } + return value; +}); +var CoreSharedOptionsSchema = import_zod11.z.object({ + rootPath: UnusableStringSchema.optional(), + host: import_zod11.z.string().optional(), + port: import_zod11.z.number().optional(), + https: import_zod11.z.boolean().optional(), + httpsKey: import_zod11.z.string().optional(), + httpsKeyPath: import_zod11.z.string().optional(), + httpsCert: import_zod11.z.string().optional(), + httpsCertPath: import_zod11.z.string().optional(), + inspectorPort: import_zod11.z.number().optional(), + verbose: import_zod11.z.boolean().optional(), + log: import_zod11.z.instanceof(Log).optional(), + handleRuntimeStdio: import_zod11.z.function(import_zod11.z.tuple([import_zod11.z.instanceof(import_stream2.Readable), import_zod11.z.instanceof(import_stream2.Readable)])).optional(), + upstream: import_zod11.z.string().optional(), + // TODO: add back validation of cf object + cf: import_zod11.z.union([import_zod11.z.boolean(), import_zod11.z.string(), import_zod11.z.record(import_zod11.z.any())]).optional(), + liveReload: import_zod11.z.boolean().optional(), + // This is a shared secret between a proxy server and miniflare that can be + // passed in a header to prove that the request came from the proxy and not + // some malicious attacker. + unsafeProxySharedSecret: import_zod11.z.string().optional(), + unsafeModuleFallbackService: ServiceFetchSchema.optional(), + // Keep blobs when deleting/overwriting keys, required for stacked storage + unsafeStickyBlobs: import_zod11.z.boolean().optional() +}); +var CORE_PLUGIN_NAME2 = "core"; +var LIVE_RELOAD_SCRIPT_TEMPLATE = (port) => ``; +var SCRIPT_CUSTOM_SERVICE = `addEventListener("fetch", (event) => { + const request = new Request(event.request); + request.headers.set("${CoreHeaders.CUSTOM_SERVICE}", ${CoreBindings.TEXT_CUSTOM_SERVICE}); + request.headers.set("${CoreHeaders.ORIGINAL_URL}", request.url); + event.respondWith(${CoreBindings.SERVICE_LOOPBACK}.fetch(request)); +})`; +function getCustomServiceDesignator(refererName, workerIndex, kind, name, service) { + let serviceName; + let entrypoint; + if (typeof service === "function") { + serviceName = getCustomServiceName(workerIndex, kind, name); + } else if (typeof service === "object") { + if ("name" in service) { + if (service.name === kCurrentWorker) { + serviceName = getUserServiceName(refererName); + } else { + serviceName = getUserServiceName(service.name); + } + entrypoint = service.entrypoint; + } else { + serviceName = getBuiltinServiceName(workerIndex, kind, name); + } + } else if (service === kCurrentWorker) { + serviceName = getUserServiceName(refererName); + } else { + serviceName = getUserServiceName(service); + } + return { name: serviceName, entrypoint }; +} +function maybeGetCustomServiceService(workerIndex, kind, name, service) { + if (typeof service === "function") { + return { + name: getCustomServiceName(workerIndex, kind, name), + worker: { + serviceWorkerScript: SCRIPT_CUSTOM_SERVICE, + compatibilityDate: "2022-09-01", + bindings: [ + { + name: CoreBindings.TEXT_CUSTOM_SERVICE, + text: `${workerIndex}/${kind}${name}` + }, + WORKER_BINDING_SERVICE_LOOPBACK + ] + } + }; + } else if (typeof service === "object" && !("name" in service)) { + return { + name: getBuiltinServiceName(workerIndex, kind, name), + ...service + }; + } +} +var FALLBACK_COMPATIBILITY_DATE = "2000-01-01"; +function getCurrentCompatibilityDate() { + const now = new Date().toISOString(); + return now.substring(0, now.indexOf("T")); +} +function validateCompatibilityDate(log, compatibilityDate) { + if (numericCompare(compatibilityDate, getCurrentCompatibilityDate()) > 0) { + throw new MiniflareCoreError( + "ERR_FUTURE_COMPATIBILITY_DATE", + `Compatibility date "${compatibilityDate}" is in the future and unsupported` + ); + } else if (numericCompare(compatibilityDate, import_workerd2.compatibilityDate) > 0) { + log.warn( + [ + "The latest compatibility date supported by the installed Cloudflare Workers Runtime is ", + bold(`"${import_workerd2.compatibilityDate}"`), + ",\nbut you've requested ", + bold(`"${compatibilityDate}"`), + ". Falling back to ", + bold(`"${import_workerd2.compatibilityDate}"`), + "..." + ].join("") + ); + return import_workerd2.compatibilityDate; + } + return compatibilityDate; +} +function buildJsonBindings(bindings) { + return Object.entries(bindings).map(([name, value]) => ({ + name, + json: JSON.stringify(value) + })); +} +var WRAPPED_MODULE_PREFIX = "miniflare-internal:wrapped:"; +function workerNameToWrappedModule(workerName) { + return WRAPPED_MODULE_PREFIX + workerName; +} +function maybeWrappedModuleToWorkerName(name) { + if (name.startsWith(WRAPPED_MODULE_PREFIX)) { + return name.substring(WRAPPED_MODULE_PREFIX.length); + } +} +var CORE_PLUGIN = { + options: CoreOptionsSchema, + sharedOptions: CoreSharedOptionsSchema, + getBindings(options, workerIndex) { + const bindings = []; + if (options.bindings !== void 0) { + bindings.push(...buildJsonBindings(options.bindings)); + } + if (options.wasmBindings !== void 0) { + bindings.push( + ...Object.entries(options.wasmBindings).map( + ([name, path23]) => import_promises6.default.readFile(path23).then((wasmModule) => ({ name, wasmModule })) + ) + ); + } + if (options.textBlobBindings !== void 0) { + bindings.push( + ...Object.entries(options.textBlobBindings).map( + ([name, path23]) => import_promises6.default.readFile(path23, "utf8").then((text) => ({ name, text })) + ) + ); + } + if (options.dataBlobBindings !== void 0) { + bindings.push( + ...Object.entries(options.dataBlobBindings).map( + ([name, path23]) => import_promises6.default.readFile(path23).then((data) => ({ name, data })) + ) + ); + } + if (options.serviceBindings !== void 0) { + bindings.push( + ...Object.entries(options.serviceBindings).map(([name, service]) => { + return { + name, + service: getCustomServiceDesignator( + /* referrer */ + options.name, + workerIndex, + "#" /* UNKNOWN */, + name, + service + ) + }; + }) + ); + } + if (options.wrappedBindings !== void 0) { + bindings.push( + ...Object.entries(options.wrappedBindings).map(([name, designator]) => { + const isObject = typeof designator === "object"; + const scriptName = isObject ? designator.scriptName : designator; + const entrypoint = isObject ? designator.entrypoint : void 0; + const bindings2 = isObject ? designator.bindings : void 0; + const moduleName2 = workerNameToWrappedModule(scriptName); + const innerBindings = bindings2 === void 0 ? [] : buildJsonBindings(bindings2); + return { + name, + wrapped: { moduleName: moduleName2, entrypoint, innerBindings } + }; + }) + ); + } + if (options.unsafeEvalBinding !== void 0) { + bindings.push({ + name: options.unsafeEvalBinding, + unsafeEval: kVoid + }); + } + return Promise.all(bindings); + }, + async getNodeBindings(options) { + const bindingEntries2 = []; + if (options.bindings !== void 0) { + bindingEntries2.push( + ...Object.entries(options.bindings).map(([name, value]) => [ + name, + JSON.parse(JSON.stringify(value)) + ]) + ); + } + if (options.wasmBindings !== void 0) { + bindingEntries2.push( + ...Object.entries(options.wasmBindings).map( + ([name, path23]) => import_promises6.default.readFile(path23).then((buffer) => [name, new WebAssembly.Module(buffer)]) + ) + ); + } + if (options.textBlobBindings !== void 0) { + bindingEntries2.push( + ...Object.entries(options.textBlobBindings).map( + ([name, path23]) => import_promises6.default.readFile(path23, "utf8").then((text) => [name, text]) + ) + ); + } + if (options.dataBlobBindings !== void 0) { + bindingEntries2.push( + ...Object.entries(options.dataBlobBindings).map( + ([name, path23]) => import_promises6.default.readFile(path23).then((buffer) => [name, viewToBuffer(buffer)]) + ) + ); + } + if (options.serviceBindings !== void 0) { + bindingEntries2.push( + ...Object.keys(options.serviceBindings).map((name) => [ + name, + kProxyNodeBinding + ]) + ); + } + if (options.wrappedBindings !== void 0) { + bindingEntries2.push( + ...Object.keys(options.wrappedBindings).map((name) => [ + name, + kProxyNodeBinding + ]) + ); + } + return Object.fromEntries(await Promise.all(bindingEntries2)); + }, + async getServices({ + log, + options, + sharedOptions, + workerBindings, + workerIndex, + wrappedBindingNames, + durableObjectClassNames, + additionalModules, + loopbackPort + }) { + const additionalModuleNames = additionalModules.map(({ name: name2 }) => name2); + const workerScript = getWorkerScript( + options, + workerIndex, + additionalModuleNames + ); + if ("modules" in workerScript) { + const subDirs = new Set( + workerScript.modules.map(({ name: name2 }) => import_path14.default.posix.dirname(name2)) + ); + subDirs.delete("."); + for (const module2 of additionalModules) { + workerScript.modules.push(module2); + for (const subDir of subDirs) { + const relativePath = import_path14.default.posix.relative(subDir, module2.name); + const relativePathString = JSON.stringify(relativePath); + workerScript.modules.push({ + name: import_path14.default.posix.join(subDir, module2.name), + // TODO(someday): if we ever have additional modules without + // default exports, this may be a problem. For now, our only + // additional module is `__STATIC_CONTENT_MANIFEST` so it's fine. + // If needed, we could look for instances of `export default` or + // `as default` in the module's code as a heuristic. + esModule: `export * from ${relativePathString}; export { default } from ${relativePathString};` + }); + } + } + } + const name = options.name ?? ""; + const serviceName = getUserServiceName(options.name); + const classNames = durableObjectClassNames.get(serviceName); + const classNamesEntries = Array.from(classNames ?? []); + const compatibilityDate = validateCompatibilityDate( + log, + options.compatibilityDate ?? FALLBACK_COMPATIBILITY_DATE + ); + const isWrappedBinding = wrappedBindingNames.has(name); + const services = []; + const extensions = []; + if (isWrappedBinding) { + let invalidWrapped2 = function(reason) { + const message = `Cannot use ${stringName} for wrapped binding because ${reason}`; + throw new MiniflareCoreError("ERR_INVALID_WRAPPED", message); + }; + var invalidWrapped = invalidWrapped2; + const stringName = JSON.stringify(name); + if (workerIndex === 0) { + invalidWrapped2( + `it's the entrypoint. +Ensure ${stringName} isn't the first entry in the \`workers\` array.` + ); + } + if (!("modules" in workerScript)) { + invalidWrapped2( + `it's a service worker. +Ensure ${stringName} sets \`modules\` to \`true\` or an array of modules` + ); + } + if (workerScript.modules.length !== 1) { + invalidWrapped2( + `it isn't a single module. +Ensure ${stringName} doesn't include unbundled \`import\`s.` + ); + } + const firstModule = workerScript.modules[0]; + if (!("esModule" in firstModule)) { + invalidWrapped2("it isn't a single ES module"); + } + if (options.compatibilityDate !== void 0) { + invalidWrapped2( + "it defines a compatibility date.\nWrapped bindings use the compatibility date of the worker with the binding." + ); + } + if (options.compatibilityFlags?.length) { + invalidWrapped2( + "it defines compatibility flags.\nWrapped bindings use the compatibility flags of the worker with the binding." + ); + } + if (options.outboundService !== void 0) { + invalidWrapped2( + "it defines an outbound service.\nWrapped bindings use the outbound service of the worker with the binding." + ); + } + extensions.push({ + modules: [ + { + name: workerNameToWrappedModule(name), + esModule: firstModule.esModule, + internal: true + } + ] + }); + } else { + services.push({ + name: serviceName, + worker: { + ...workerScript, + compatibilityDate, + compatibilityFlags: options.compatibilityFlags, + bindings: workerBindings, + durableObjectNamespaces: classNamesEntries.map( + ([className, { unsafeUniqueKey, unsafePreventEviction }]) => { + if (unsafeUniqueKey === kUnsafeEphemeralUniqueKey) { + return { + className, + ephemeralLocal: kVoid, + preventEviction: unsafePreventEviction + }; + } else { + return { + className, + // This `uniqueKey` will (among other things) be used as part of the + // path when persisting to the file-system. `-` is invalid in + // JavaScript class names, but safe on filesystems (incl. Windows). + uniqueKey: unsafeUniqueKey ?? `${options.name ?? ""}-${className}`, + preventEviction: unsafePreventEviction + }; + } + } + ), + durableObjectStorage: classNamesEntries.length === 0 ? void 0 : options.unsafeEphemeralDurableObjects ? { inMemory: kVoid } : { localDisk: DURABLE_OBJECTS_STORAGE_SERVICE_NAME }, + globalOutbound: options.outboundService === void 0 ? void 0 : getCustomServiceDesignator( + /* referrer */ + options.name, + workerIndex, + "$" /* KNOWN */, + CUSTOM_SERVICE_KNOWN_OUTBOUND, + options.outboundService + ), + cacheApiOutbound: { name: getCacheServiceName(workerIndex) }, + moduleFallback: options.unsafeUseModuleFallbackService && sharedOptions.unsafeModuleFallbackService !== void 0 ? `localhost:${loopbackPort}` : void 0 + } + }); + } + if (options.serviceBindings !== void 0) { + for (const [name2, service] of Object.entries(options.serviceBindings)) { + const maybeService = maybeGetCustomServiceService( + workerIndex, + "#" /* UNKNOWN */, + name2, + service + ); + if (maybeService !== void 0) + services.push(maybeService); + } + } + if (options.outboundService !== void 0) { + const maybeService = maybeGetCustomServiceService( + workerIndex, + "$" /* KNOWN */, + CUSTOM_SERVICE_KNOWN_OUTBOUND, + options.outboundService + ); + if (maybeService !== void 0) + services.push(maybeService); + } + return { services, extensions }; + } +}; +function getGlobalServices({ + sharedOptions, + allWorkerRoutes, + fallbackWorkerName, + loopbackPort, + log, + proxyBindings +}) { + const workerNames = [...allWorkerRoutes.keys()]; + const routes = parseRoutes(allWorkerRoutes); + const serviceEntryBindings = [ + WORKER_BINDING_SERVICE_LOOPBACK, + // For converting stack-traces to pretty-error pages + { name: CoreBindings.JSON_ROUTES, json: JSON.stringify(routes) }, + { name: CoreBindings.JSON_CF_BLOB, json: JSON.stringify(sharedOptions.cf) }, + { name: CoreBindings.JSON_LOG_LEVEL, json: JSON.stringify(log.level) }, + { + name: CoreBindings.SERVICE_USER_FALLBACK, + service: { name: getUserServiceName(fallbackWorkerName) } + }, + ...workerNames.map((name) => ({ + name: CoreBindings.SERVICE_USER_ROUTE_PREFIX + name, + service: { name: getUserServiceName(name) } + })), + { + name: CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY, + durableObjectNamespace: { className: "ProxyServer" } + }, + { + name: CoreBindings.DATA_PROXY_SECRET, + data: PROXY_SECRET + }, + // Add `proxyBindings` here, they'll be added to the `ProxyServer` `env` + ...proxyBindings + ]; + if (sharedOptions.upstream !== void 0) { + serviceEntryBindings.push({ + name: CoreBindings.TEXT_UPSTREAM_URL, + text: sharedOptions.upstream + }); + } + if (sharedOptions.unsafeProxySharedSecret !== void 0) { + serviceEntryBindings.push({ + name: CoreBindings.DATA_PROXY_SHARED_SECRET, + data: encoder2.encode(sharedOptions.unsafeProxySharedSecret) + }); + } + if (sharedOptions.liveReload) { + const liveReloadScript = LIVE_RELOAD_SCRIPT_TEMPLATE(loopbackPort); + serviceEntryBindings.push({ + name: CoreBindings.DATA_LIVE_RELOAD_SCRIPT, + data: encoder2.encode(liveReloadScript) + }); + } + return [ + { + name: SERVICE_LOOPBACK, + external: { http: { cfBlobHeader: CoreHeaders.CF_BLOB } } + }, + { + name: SERVICE_ENTRY, + worker: { + modules: [{ name: "entry.worker.js", esModule: entry_worker_default() }], + compatibilityDate: "2023-04-04", + compatibilityFlags: [ + "nodejs_compat", + "service_binding_extra_handlers", + "brotli_content_encoding", + "rpc" + ], + bindings: serviceEntryBindings, + durableObjectNamespaces: [ + { + className: "ProxyServer", + uniqueKey: `${SERVICE_ENTRY}-ProxyServer`, + // `ProxyServer` relies on a singleton object containing of "heap" + // mapping addresses to native references. If the singleton object + // were evicted, addresses would be invalidated. Therefore, we + // prevent eviction to ensure heap addresses stay valid for the + // lifetime of the `workerd` process + preventEviction: true + } + ], + // `ProxyServer` doesn't make use of Durable Object storage + durableObjectStorage: { inMemory: kVoid }, + // Always use the entrypoints cache implementation for proxying. This + // means if the entrypoint disables caching, proxied cache operations + // will be no-ops. Note we always require at least one worker to be set. + cacheApiOutbound: { name: "cache:0" } + } + }, + { + name: "internet", + network: { + // Allow access to private/public addresses: + // https://github.com/cloudflare/miniflare/issues/412 + allow: ["public", "private"], + deny: [], + tlsOptions: { + trustBrowserCas: true, + trustedCertificates + } + } + } + ]; +} +function getWorkerScript(options, workerIndex, additionalModuleNames) { + const modulesRoot = import_path14.default.resolve( + ("modulesRoot" in options ? options.modulesRoot : void 0) ?? "" + ); + if (Array.isArray(options.modules)) { + return { + modules: options.modules.map( + (module2) => convertModuleDefinition(modulesRoot, module2) + ) + }; + } + let code; + if ("script" in options && options.script !== void 0) { + code = options.script; + } else if ("scriptPath" in options && options.scriptPath !== void 0) { + code = (0, import_fs11.readFileSync)(options.scriptPath, "utf8"); + } else { + import_assert9.default.fail("Unreachable: Workers must have code"); + } + const scriptPath = options.scriptPath ?? buildStringScriptPath(workerIndex); + if (options.modules) { + const locator = new ModuleLocator( + modulesRoot, + additionalModuleNames, + options.modulesRules, + options.compatibilityFlags + ); + locator.visitEntrypoint(code, scriptPath); + return { modules: locator.modules }; + } else { + code = withSourceURL(code, scriptPath); + return { serviceWorkerScript: code }; + } +} + +// src/plugins/d1/index.ts +var import_promises7 = __toESM(require("fs/promises")); + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/d1/database.worker.ts +var import_fs12 = __toESM(require("fs")); +var import_path15 = __toESM(require("path")); +var import_url12 = __toESM(require("url")); +var contents8; +function database_worker_default() { + if (contents8 !== void 0) + return contents8; + const filePath = import_path15.default.join(__dirname, "workers", "d1/database.worker.js"); + contents8 = import_fs12.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url12.default.pathToFileURL(filePath); + return contents8; +} + +// src/plugins/d1/index.ts +var import_zod12 = require("zod"); +var D1OptionsSchema = import_zod12.z.object({ + d1Databases: import_zod12.z.union([import_zod12.z.record(import_zod12.z.string()), import_zod12.z.string().array()]).optional() +}); +var D1SharedOptionsSchema = import_zod12.z.object({ + d1Persist: PersistenceSchema +}); +var D1_PLUGIN_NAME = "d1"; +var D1_STORAGE_SERVICE_NAME = `${D1_PLUGIN_NAME}:storage`; +var D1_DATABASE_SERVICE_PREFIX = `${D1_PLUGIN_NAME}:db`; +var D1_DATABASE_OBJECT_CLASS_NAME = "D1DatabaseObject"; +var D1_DATABASE_OBJECT = { + serviceName: D1_DATABASE_SERVICE_PREFIX, + className: D1_DATABASE_OBJECT_CLASS_NAME +}; +var D1_PLUGIN = { + options: D1OptionsSchema, + sharedOptions: D1SharedOptionsSchema, + getBindings(options) { + const databases = namespaceEntries(options.d1Databases); + return databases.map(([name, id]) => { + const binding = name.startsWith("__D1_BETA__") ? ( + // Used before Wrangler 3.3 + { + service: { name: `${D1_DATABASE_SERVICE_PREFIX}:${id}` } + } + ) : ( + // Used after Wrangler 3.3 + { + wrapped: { + moduleName: "cloudflare-internal:d1-api", + innerBindings: [ + { + name: "fetcher", + service: { name: `${D1_DATABASE_SERVICE_PREFIX}:${id}` } + } + ] + } + } + ); + return { name, ...binding }; + }); + }, + getNodeBindings(options) { + const databases = namespaceKeys(options.d1Databases); + return Object.fromEntries( + databases.map((name) => [name, kProxyNodeBinding]) + ); + }, + async getServices({ + options, + sharedOptions, + tmpPath, + log, + unsafeStickyBlobs + }) { + const persist = sharedOptions.d1Persist; + const databases = namespaceEntries(options.d1Databases); + const services = databases.map(([_, id]) => ({ + name: `${D1_DATABASE_SERVICE_PREFIX}:${id}`, + worker: objectEntryWorker(D1_DATABASE_OBJECT, id) + })); + if (databases.length > 0) { + const uniqueKey = `miniflare-${D1_DATABASE_OBJECT_CLASS_NAME}`; + const persistPath = getPersistPath(D1_PLUGIN_NAME, tmpPath, persist); + await import_promises7.default.mkdir(persistPath, { recursive: true }); + const storageService = { + name: D1_STORAGE_SERVICE_NAME, + disk: { path: persistPath, writable: true } + }; + const objectService = { + name: D1_DATABASE_SERVICE_PREFIX, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { + name: "database.worker.js", + esModule: database_worker_default() + } + ], + durableObjectNamespaces: [ + { + className: D1_DATABASE_OBJECT_CLASS_NAME, + uniqueKey + } + ], + // Store Durable Object SQL databases in persist path + durableObjectStorage: { localDisk: D1_STORAGE_SERVICE_NAME }, + // Bind blob disk directory service to object + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_BLOBS, + service: { name: D1_STORAGE_SERVICE_NAME } + }, + { + name: SharedBindings.MAYBE_SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } + }, + ...getMiniflareObjectBindings(unsafeStickyBlobs) + ] + } + }; + services.push(storageService, objectService); + for (const database of databases) { + await migrateDatabase(log, uniqueKey, persistPath, database[1]); + } + } + return services; + }, + getPersistPath({ d1Persist }, tmpPath) { + return getPersistPath(D1_PLUGIN_NAME, tmpPath, d1Persist); + } +}; + +// src/plugins/hyperdrive/index.ts +var import_node_assert3 = __toESM(require("node:assert")); +var import_zod13 = require("zod"); +var HYPERDRIVE_PLUGIN_NAME = "hyperdrive"; +function hasPostgresProtocol(url14) { + return url14.protocol === "postgresql:" || url14.protocol === "postgres:"; +} +function getPort(url14) { + if (url14.port !== "") + return url14.port; + if (hasPostgresProtocol(url14)) + return "5432"; + import_node_assert3.default.fail(`Expected known protocol, got ${url14.protocol}`); +} +var HyperdriveSchema = import_zod13.z.union([import_zod13.z.string().url(), import_zod13.z.instanceof(URL)]).transform((url14, ctx) => { + if (typeof url14 === "string") + url14 = new URL(url14); + if (url14.protocol === "") { + ctx.addIssue({ + code: import_zod13.z.ZodIssueCode.custom, + message: "You must specify the database protocol - e.g. 'postgresql'." + }); + } else if (!hasPostgresProtocol(url14)) { + ctx.addIssue({ + code: import_zod13.z.ZodIssueCode.custom, + message: "Only PostgreSQL or PostgreSQL compatible databases are currently supported." + }); + } + if (url14.host === "") { + ctx.addIssue({ + code: import_zod13.z.ZodIssueCode.custom, + message: "You must provide a hostname or IP address in your connection string - e.g. 'user:password@database-hostname.example.com:5432/databasename" + }); + } + if (url14.pathname === "") { + ctx.addIssue({ + code: import_zod13.z.ZodIssueCode.custom, + message: "You must provide a database name as the path component - e.g. /postgres" + }); + } + if (url14.username === "") { + ctx.addIssue({ + code: import_zod13.z.ZodIssueCode.custom, + message: "You must provide a username - e.g. 'user:password@database.example.com:port/databasename'" + }); + } + if (url14.password === "") { + ctx.addIssue({ + code: import_zod13.z.ZodIssueCode.custom, + message: "You must provide a password - e.g. 'user:password@database.example.com:port/databasename' " + }); + } + return url14; +}); +var HyperdriveInputOptionsSchema = import_zod13.z.object({ + hyperdrives: import_zod13.z.record(import_zod13.z.string(), HyperdriveSchema).optional() +}); +var HYPERDRIVE_PLUGIN = { + options: HyperdriveInputOptionsSchema, + getBindings(options) { + return Object.entries(options.hyperdrives ?? {}).map( + ([name, url14]) => { + const database = url14.pathname.replace("/", ""); + const scheme = url14.protocol.replace(":", ""); + return { + name, + hyperdrive: { + designator: { + name: `${HYPERDRIVE_PLUGIN_NAME}:${name}` + }, + database: decodeURIComponent(database), + user: decodeURIComponent(url14.username), + password: decodeURIComponent(url14.password), + scheme + } + }; + } + ); + }, + getNodeBindings() { + return {}; + }, + async getServices({ options }) { + return Object.entries(options.hyperdrives ?? {}).map( + ([name, url14]) => ({ + name: `${HYPERDRIVE_PLUGIN_NAME}:${name}`, + external: { + address: `${url14.hostname}:${getPort(url14)}`, + tcp: {} + } + }) + ); + } +}; + +// src/plugins/kv/index.ts +var import_promises9 = __toESM(require("fs/promises")); + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/kv/namespace.worker.ts +var import_fs13 = __toESM(require("fs")); +var import_path16 = __toESM(require("path")); +var import_url13 = __toESM(require("url")); +var contents9; +function namespace_worker_default() { + if (contents9 !== void 0) + return contents9; + const filePath = import_path16.default.join(__dirname, "workers", "kv/namespace.worker.js"); + contents9 = import_fs13.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url13.default.pathToFileURL(filePath); + return contents9; +} + +// src/plugins/kv/index.ts +var import_zod14 = require("zod"); + +// src/plugins/kv/constants.ts +var KV_PLUGIN_NAME = "kv"; + +// src/plugins/kv/sites.ts +var import_assert10 = __toESM(require("assert")); +var import_promises8 = __toESM(require("fs/promises")); +var import_path18 = __toESM(require("path")); + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/kv/sites.worker.ts +var import_fs14 = __toESM(require("fs")); +var import_path17 = __toESM(require("path")); +var import_url14 = __toESM(require("url")); +var contents10; +function sites_worker_default() { + if (contents10 !== void 0) + return contents10; + const filePath = import_path17.default.join(__dirname, "workers", "kv/sites.worker.js"); + contents10 = import_fs14.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url14.default.pathToFileURL(filePath); + return contents10; +} + +// src/plugins/kv/sites.ts +async function* listKeysInDirectoryInner(rootPath2, currentPath) { + const fileEntries = await import_promises8.default.readdir(currentPath, { withFileTypes: true }); + for (const fileEntry of fileEntries) { + const filePath = import_path18.default.posix.join(currentPath, fileEntry.name); + if (fileEntry.isDirectory()) { + yield* listKeysInDirectoryInner(rootPath2, filePath); + } else { + yield filePath.substring(rootPath2.length + 1); + } + } +} +function listKeysInDirectory(rootPath2) { + rootPath2 = import_path18.default.resolve(rootPath2); + return listKeysInDirectoryInner(rootPath2, rootPath2); +} +var sitesRegExpsCache = /* @__PURE__ */ new WeakMap(); +var SERVICE_NAMESPACE_SITE = `${KV_PLUGIN_NAME}:site`; +async function buildStaticContentManifest(sitePath, siteRegExps) { + const staticContentManifest = {}; + for await (const key of listKeysInDirectory(sitePath)) { + if (testSiteRegExps(siteRegExps, key)) { + staticContentManifest[key] = encodeSitesKey(key); + } + } + return staticContentManifest; +} +async function getSitesBindings(options) { + const siteRegExps = { + include: options.siteInclude && globsToRegExps(options.siteInclude), + exclude: options.siteExclude && globsToRegExps(options.siteExclude) + }; + sitesRegExpsCache.set(options, siteRegExps); + const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest( + options.sitePath, + siteRegExps + ); + return [ + { + name: SiteBindings.KV_NAMESPACE_SITE, + kvNamespace: { name: SERVICE_NAMESPACE_SITE } + }, + { + name: SiteBindings.JSON_SITE_MANIFEST, + json: JSON.stringify(__STATIC_CONTENT_MANIFEST) + } + ]; +} +async function getSitesNodeBindings(options) { + const siteRegExps = sitesRegExpsCache.get(options); + (0, import_assert10.default)(siteRegExps !== void 0); + const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest( + options.sitePath, + siteRegExps + ); + return { + [SiteBindings.KV_NAMESPACE_SITE]: kProxyNodeBinding, + [SiteBindings.JSON_SITE_MANIFEST]: __STATIC_CONTENT_MANIFEST + }; +} +function getSitesServices(options) { + const siteRegExps = sitesRegExpsCache.get(options); + (0, import_assert10.default)(siteRegExps !== void 0); + const serialisedSiteRegExps = serialiseSiteRegExps(siteRegExps); + const persist = import_path18.default.resolve(options.sitePath); + const storageServiceName = `${SERVICE_NAMESPACE_SITE}:storage`; + const storageService = { + name: storageServiceName, + disk: { path: persist, writable: true } + }; + const namespaceService = { + name: SERVICE_NAMESPACE_SITE, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat"], + modules: [ + { + name: "site.worker.js", + esModule: sites_worker_default() + } + ], + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_BLOBS, + service: { name: storageServiceName } + }, + { + name: SiteBindings.JSON_SITE_FILTER, + json: JSON.stringify(serialisedSiteRegExps) + } + ] + } + }; + return [storageService, namespaceService]; +} + +// src/plugins/kv/index.ts +var KVOptionsSchema = import_zod14.z.object({ + kvNamespaces: import_zod14.z.union([import_zod14.z.record(import_zod14.z.string()), import_zod14.z.string().array()]).optional(), + // Workers Sites + sitePath: PathSchema.optional(), + siteInclude: import_zod14.z.string().array().optional(), + siteExclude: import_zod14.z.string().array().optional() +}); +var KVSharedOptionsSchema = import_zod14.z.object({ + kvPersist: PersistenceSchema +}); +var SERVICE_NAMESPACE_PREFIX = `${KV_PLUGIN_NAME}:ns`; +var KV_STORAGE_SERVICE_NAME = `${KV_PLUGIN_NAME}:storage`; +var KV_NAMESPACE_OBJECT_CLASS_NAME = "KVNamespaceObject"; +var KV_NAMESPACE_OBJECT = { + serviceName: SERVICE_NAMESPACE_PREFIX, + className: KV_NAMESPACE_OBJECT_CLASS_NAME +}; +function isWorkersSitesEnabled(options) { + return options.sitePath !== void 0; +} +var KV_PLUGIN = { + options: KVOptionsSchema, + sharedOptions: KVSharedOptionsSchema, + async getBindings(options) { + const namespaces = namespaceEntries(options.kvNamespaces); + const bindings = namespaces.map(([name, id]) => ({ + name, + kvNamespace: { name: `${SERVICE_NAMESPACE_PREFIX}:${id}` } + })); + if (isWorkersSitesEnabled(options)) { + bindings.push(...await getSitesBindings(options)); + } + return bindings; + }, + async getNodeBindings(options) { + const namespaces = namespaceKeys(options.kvNamespaces); + const bindings = Object.fromEntries( + namespaces.map((name) => [name, kProxyNodeBinding]) + ); + if (isWorkersSitesEnabled(options)) { + Object.assign(bindings, await getSitesNodeBindings(options)); + } + return bindings; + }, + async getServices({ + options, + sharedOptions, + tmpPath, + log, + unsafeStickyBlobs + }) { + const persist = sharedOptions.kvPersist; + const namespaces = namespaceEntries(options.kvNamespaces); + const services = namespaces.map(([_, id]) => ({ + name: `${SERVICE_NAMESPACE_PREFIX}:${id}`, + worker: objectEntryWorker(KV_NAMESPACE_OBJECT, id) + })); + if (services.length > 0) { + const uniqueKey = `miniflare-${KV_NAMESPACE_OBJECT_CLASS_NAME}`; + const persistPath = getPersistPath(KV_PLUGIN_NAME, tmpPath, persist); + await import_promises9.default.mkdir(persistPath, { recursive: true }); + const storageService = { + name: KV_STORAGE_SERVICE_NAME, + disk: { path: persistPath, writable: true } + }; + const objectService = { + name: SERVICE_NAMESPACE_PREFIX, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { + name: "namespace.worker.js", + esModule: namespace_worker_default() + } + ], + durableObjectNamespaces: [ + { className: KV_NAMESPACE_OBJECT_CLASS_NAME, uniqueKey } + ], + // Store Durable Object SQL databases in persist path + durableObjectStorage: { localDisk: KV_STORAGE_SERVICE_NAME }, + // Bind blob disk directory service to object + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_BLOBS, + service: { name: KV_STORAGE_SERVICE_NAME } + }, + { + name: SharedBindings.MAYBE_SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } + }, + ...getMiniflareObjectBindings(unsafeStickyBlobs) + ] + } + }; + services.push(storageService, objectService); + for (const namespace of namespaces) { + await migrateDatabase(log, uniqueKey, persistPath, namespace[1]); + } + } + if (isWorkersSitesEnabled(options)) { + services.push(...getSitesServices(options)); + } + return services; + }, + getPersistPath({ kvPersist }, tmpPath) { + return getPersistPath(KV_PLUGIN_NAME, tmpPath, kvPersist); + } +}; + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/queues/broker.worker.ts +var import_fs15 = __toESM(require("fs")); +var import_path19 = __toESM(require("path")); +var import_url15 = __toESM(require("url")); +var contents11; +function broker_worker_default() { + if (contents11 !== void 0) + return contents11; + const filePath = import_path19.default.join(__dirname, "workers", "queues/broker.worker.js"); + contents11 = import_fs15.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url15.default.pathToFileURL(filePath); + return contents11; +} + +// src/plugins/queues/index.ts +var import_zod15 = require("zod"); + +// src/plugins/queues/errors.ts +var QueuesError = class extends MiniflareError { +}; + +// src/plugins/queues/index.ts +var QueuesOptionsSchema = import_zod15.z.object({ + queueProducers: import_zod15.z.union([import_zod15.z.record(QueueProducerOptionsSchema), import_zod15.z.string().array(), import_zod15.z.record(import_zod15.z.string())]).optional(), + queueConsumers: import_zod15.z.union([import_zod15.z.record(QueueConsumerOptionsSchema), import_zod15.z.string().array()]).optional() +}); +var QUEUES_PLUGIN_NAME = "queues"; +var SERVICE_QUEUE_PREFIX = `${QUEUES_PLUGIN_NAME}:queue`; +var QUEUE_BROKER_OBJECT_CLASS_NAME = "QueueBrokerObject"; +var QUEUE_BROKER_OBJECT = { + serviceName: SERVICE_QUEUE_PREFIX, + className: QUEUE_BROKER_OBJECT_CLASS_NAME +}; +var QUEUES_PLUGIN = { + options: QueuesOptionsSchema, + getBindings(options) { + const queues = bindingEntries(options.queueProducers); + return queues.map(([name, id]) => ({ + name, + queue: { name: `${SERVICE_QUEUE_PREFIX}:${id}` } + })); + }, + getNodeBindings(options) { + const queues = bindingKeys(options.queueProducers); + return Object.fromEntries(queues.map((name) => [name, kProxyNodeBinding])); + }, + async getServices({ + options, + workerNames, + queueProducers: allQueueProducers, + queueConsumers: allQueueConsumers, + unsafeStickyBlobs + }) { + const queues = bindingEntries(options.queueProducers); + if (queues.length === 0) + return []; + const services = queues.map(([_, id]) => ({ + name: `${SERVICE_QUEUE_PREFIX}:${id}`, + worker: objectEntryWorker(QUEUE_BROKER_OBJECT, id) + })); + const uniqueKey = `miniflare-${QUEUE_BROKER_OBJECT_CLASS_NAME}`; + const objectService = { + name: SERVICE_QUEUE_PREFIX, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: [ + "nodejs_compat", + "experimental", + "service_binding_extra_handlers" + ], + modules: [ + { name: "broker.worker.js", esModule: broker_worker_default() } + ], + durableObjectNamespaces: [ + { className: QUEUE_BROKER_OBJECT_CLASS_NAME, uniqueKey } + ], + // Miniflare's Queue broker is in-memory only at the moment + durableObjectStorage: { inMemory: kVoid }, + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } + }, + ...getMiniflareObjectBindings(unsafeStickyBlobs), + { + name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT, + durableObjectNamespace: { + className: QUEUE_BROKER_OBJECT_CLASS_NAME + } + }, + { + name: QueueBindings.MAYBE_JSON_QUEUE_PRODUCERS, + json: JSON.stringify(Object.fromEntries(allQueueProducers)) + }, + { + name: QueueBindings.MAYBE_JSON_QUEUE_CONSUMERS, + json: JSON.stringify(Object.fromEntries(allQueueConsumers)) + }, + ...workerNames.map((name) => ({ + name: QueueBindings.SERVICE_WORKER_PREFIX + name, + service: { name: getUserServiceName(name) } + })) + ] + } + }; + services.push(objectService); + return services; + } +}; +function bindingEntries(namespaces) { + if (Array.isArray(namespaces)) { + return namespaces.map((bindingName) => [bindingName, bindingName]); + } else if (namespaces !== void 0) { + return Object.entries(namespaces).map(([name, opts]) => [name, typeof opts === "string" ? opts : opts.queueName]); + } else { + return []; + } +} +function bindingKeys(namespaces) { + if (Array.isArray(namespaces)) { + return namespaces; + } else if (namespaces !== void 0) { + return Object.keys(namespaces); + } else { + return []; + } +} + +// src/plugins/r2/index.ts +var import_promises10 = __toESM(require("fs/promises")); + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/r2/bucket.worker.ts +var import_fs16 = __toESM(require("fs")); +var import_path20 = __toESM(require("path")); +var import_url16 = __toESM(require("url")); +var contents12; +function bucket_worker_default() { + if (contents12 !== void 0) + return contents12; + const filePath = import_path20.default.join(__dirname, "workers", "r2/bucket.worker.js"); + contents12 = import_fs16.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url16.default.pathToFileURL(filePath); + return contents12; +} + +// src/plugins/r2/index.ts +var import_zod16 = require("zod"); +var R2OptionsSchema = import_zod16.z.object({ + r2Buckets: import_zod16.z.union([import_zod16.z.record(import_zod16.z.string()), import_zod16.z.string().array()]).optional() +}); +var R2SharedOptionsSchema = import_zod16.z.object({ + r2Persist: PersistenceSchema +}); +var R2_PLUGIN_NAME = "r2"; +var R2_STORAGE_SERVICE_NAME = `${R2_PLUGIN_NAME}:storage`; +var R2_BUCKET_SERVICE_PREFIX = `${R2_PLUGIN_NAME}:bucket`; +var R2_BUCKET_OBJECT_CLASS_NAME = "R2BucketObject"; +var R2_BUCKET_OBJECT = { + serviceName: R2_BUCKET_SERVICE_PREFIX, + className: R2_BUCKET_OBJECT_CLASS_NAME +}; +var R2_PLUGIN = { + options: R2OptionsSchema, + sharedOptions: R2SharedOptionsSchema, + getBindings(options) { + const buckets = namespaceEntries(options.r2Buckets); + return buckets.map(([name, id]) => ({ + name, + r2Bucket: { name: `${R2_BUCKET_SERVICE_PREFIX}:${id}` } + })); + }, + getNodeBindings(options) { + const buckets = namespaceKeys(options.r2Buckets); + return Object.fromEntries(buckets.map((name) => [name, kProxyNodeBinding])); + }, + async getServices({ + options, + sharedOptions, + tmpPath, + log, + unsafeStickyBlobs + }) { + const persist = sharedOptions.r2Persist; + const buckets = namespaceEntries(options.r2Buckets); + const services = buckets.map(([_, id]) => ({ + name: `${R2_BUCKET_SERVICE_PREFIX}:${id}`, + worker: objectEntryWorker(R2_BUCKET_OBJECT, id) + })); + if (buckets.length > 0) { + const uniqueKey = `miniflare-${R2_BUCKET_OBJECT_CLASS_NAME}`; + const persistPath = getPersistPath(R2_PLUGIN_NAME, tmpPath, persist); + await import_promises10.default.mkdir(persistPath, { recursive: true }); + const storageService = { + name: R2_STORAGE_SERVICE_NAME, + disk: { path: persistPath, writable: true } + }; + const objectService = { + name: R2_BUCKET_SERVICE_PREFIX, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { + name: "bucket.worker.js", + esModule: bucket_worker_default() + } + ], + durableObjectNamespaces: [ + { + className: R2_BUCKET_OBJECT_CLASS_NAME, + uniqueKey + } + ], + // Store Durable Object SQL databases in persist path + durableObjectStorage: { localDisk: R2_STORAGE_SERVICE_NAME }, + // Bind blob disk directory service to object + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_BLOBS, + service: { name: R2_STORAGE_SERVICE_NAME } + }, + { + name: SharedBindings.MAYBE_SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } + }, + ...getMiniflareObjectBindings(unsafeStickyBlobs) + ] + } + }; + services.push(storageService, objectService); + for (const bucket of buckets) { + await migrateDatabase(log, uniqueKey, persistPath, bucket[1]); + } + } + return services; + }, + getPersistPath({ r2Persist }, tmpPath) { + return getPersistPath(R2_PLUGIN_NAME, tmpPath, r2Persist); + } +}; + +// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/ratelimit/ratelimit.worker.ts +var import_fs17 = __toESM(require("fs")); +var import_path21 = __toESM(require("path")); +var import_url17 = __toESM(require("url")); +var contents13; +function ratelimit_worker_default() { + if (contents13 !== void 0) + return contents13; + const filePath = import_path21.default.join(__dirname, "workers", "ratelimit/ratelimit.worker.js"); + contents13 = import_fs17.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url17.default.pathToFileURL(filePath); + return contents13; +} + +// src/plugins/ratelimit/index.ts +var import_zod17 = require("zod"); +var PeriodType = /* @__PURE__ */ ((PeriodType2) => { + PeriodType2[PeriodType2["TENSECONDS"] = 10] = "TENSECONDS"; + PeriodType2[PeriodType2["MINUTE"] = 60] = "MINUTE"; + return PeriodType2; +})(PeriodType || {}); +var RatelimitConfigSchema = import_zod17.z.object({ + simple: import_zod17.z.object({ + limit: import_zod17.z.number().gt(0), + // may relax this to be any number in the future + period: import_zod17.z.nativeEnum(PeriodType).optional() + }) +}); +var RatelimitOptionsSchema = import_zod17.z.object({ + ratelimits: import_zod17.z.record(RatelimitConfigSchema).optional() +}); +var RATELIMIT_PLUGIN_NAME = "ratelimit"; +var SERVICE_RATELIMIT_PREFIX = `${RATELIMIT_PLUGIN_NAME}`; +var SERVICE_RATELIMIT_MODULE = `cloudflare-internal:${SERVICE_RATELIMIT_PREFIX}:module`; +function buildJsonBindings2(bindings) { + return Object.entries(bindings).map(([name, value]) => ({ + name, + json: JSON.stringify(value) + })); +} +var RATELIMIT_PLUGIN = { + options: RatelimitOptionsSchema, + getBindings(options) { + if (!options.ratelimits) { + return []; + } + const bindings = Object.entries(options.ratelimits).map( + ([name, config]) => ({ + name, + wrapped: { + moduleName: SERVICE_RATELIMIT_MODULE, + innerBindings: buildJsonBindings2({ + namespaceId: name, + limit: config.simple.limit, + period: config.simple.period + }) + } + }) + ); + return bindings; + }, + getNodeBindings(options) { + if (!options.ratelimits) { + return {}; + } + return Object.fromEntries( + Object.keys(options.ratelimits).map((name) => [name, kProxyNodeBinding]) + ); + }, + async getServices({ options }) { + if (!options.ratelimits) { + return []; + } + return { + services: [], + extensions: [ + { + modules: [ + { + name: SERVICE_RATELIMIT_MODULE, + esModule: ratelimit_worker_default(), + internal: true + } + ] + } + ] + }; + } +}; + +// src/plugins/index.ts +var PLUGINS = { + [CORE_PLUGIN_NAME2]: CORE_PLUGIN, + [CACHE_PLUGIN_NAME]: CACHE_PLUGIN, + [D1_PLUGIN_NAME]: D1_PLUGIN, + [DURABLE_OBJECTS_PLUGIN_NAME]: DURABLE_OBJECTS_PLUGIN, + [KV_PLUGIN_NAME]: KV_PLUGIN, + [QUEUES_PLUGIN_NAME]: QUEUES_PLUGIN, + [R2_PLUGIN_NAME]: R2_PLUGIN, + [HYPERDRIVE_PLUGIN_NAME]: HYPERDRIVE_PLUGIN, + [RATELIMIT_PLUGIN_NAME]: RATELIMIT_PLUGIN +}; +var PLUGIN_ENTRIES = Object.entries(PLUGINS); + +// src/zod-format.ts +var import_assert11 = __toESM(require("assert")); +var import_util4 = __toESM(require("util")); +var kMessages = Symbol("kMessages"); +var kActual = Symbol("kActual"); +var kGroupId = Symbol("kGroupId"); +var groupColours = [ + yellow, + /* (green) */ + cyan, + blue, + magenta, + green +]; +var GroupCountsMap = Map; +function isAnnotation(value) { + return typeof value === "object" && value !== null && kMessages in value && kActual in value; +} +function isRecord(value) { + return typeof value === "object" && value !== null; +} +function arrayShallowEqual(a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (a[i] !== b[i]) + return false; + return true; +} +function issueEqual(a, b) { + return a.message === b.message && arrayShallowEqual(a.path, b.path); +} +function hasMultipleDistinctMessages(issues, atDepth) { + let firstIssue; + for (const issue of issues) { + if (issue.path.length < atDepth) + continue; + if (firstIssue === void 0) + firstIssue = issue; + else if (!issueEqual(firstIssue, issue)) + return true; + } + return false; +} +function annotate(groupCounts, annotated, input, issue, path23, groupId) { + if (path23.length === 0) { + if (issue.code === "invalid_union") { + const unionIssues = issue.unionErrors.flatMap(({ issues }) => issues); + let newGroupId; + const multipleDistinct = hasMultipleDistinctMessages( + unionIssues, + // For this check, we only include messages that are deeper than our + // current level, so we don't include messages we'd ignore if we grouped + issue.path.length + 1 + ); + if (isRecord(input) && multipleDistinct) { + newGroupId = groupCounts.size; + groupCounts.set(newGroupId, 0); + } + for (const unionIssue of unionIssues) { + const unionPath = unionIssue.path.slice(issue.path.length); + if (multipleDistinct && unionPath.length === 0) + continue; + annotated = annotate( + groupCounts, + annotated, + input, + unionIssue, + unionPath, + newGroupId + ); + } + return annotated; + } + const message = issue.message; + if (annotated !== void 0) { + if (isAnnotation(annotated) && !annotated[kMessages].includes(message)) { + annotated[kMessages].push(message); + } + return annotated; + } + if (groupId !== void 0) { + const current = groupCounts.get(groupId); + (0, import_assert11.default)(current !== void 0); + groupCounts.set(groupId, current + 1); + } + return { + [kMessages]: [message], + [kActual]: input, + [kGroupId]: groupId + }; + } + const [head, ...tail] = path23; + (0, import_assert11.default)(isRecord(input), "Expected object/array input for nested issue"); + if (annotated === void 0) { + if (Array.isArray(input)) { + annotated = new Array(input.length); + } else { + const entries = Object.keys(input).map((key) => [key, void 0]); + annotated = Object.fromEntries(entries); + } + } + (0, import_assert11.default)(isRecord(annotated), "Expected object/array for nested issue"); + annotated[head] = annotate( + groupCounts, + annotated[head], + input[head], + issue, + tail, + groupId + ); + return annotated; +} +function print(inspectOptions, groupCounts, annotated, indent = "", extras) { + const prefix = extras?.prefix ?? ""; + const suffix = extras?.suffix ?? ""; + if (isAnnotation(annotated)) { + const prefixIndent = indent + " ".repeat(prefix.length); + const actual = import_util4.default.inspect(annotated[kActual], inspectOptions); + const actualIndented = actual.split("\n").map((line, i) => i > 0 ? prefixIndent + line : line).join("\n"); + let messageColour = red; + let messagePrefix = prefixIndent + "^"; + let groupOr = ""; + if (annotated[kGroupId] !== void 0) { + messageColour = groupColours[annotated[kGroupId] % groupColours.length]; + messagePrefix += annotated[kGroupId] + 1; + const remaining = groupCounts.get(annotated[kGroupId]); + (0, import_assert11.default)(remaining !== void 0); + if (remaining > 1) + groupOr = " *or*"; + groupCounts.set(annotated[kGroupId], remaining - 1); + } + messagePrefix += " "; + const messageIndent = " ".repeat(messagePrefix.length); + const messageIndented = annotated[kMessages].flatMap((m) => m.split("\n")).map((line, i) => i > 0 ? messageIndent + line : line).join("\n"); + const error = messageColour(`${messagePrefix}${messageIndented}${groupOr}`); + return `${indent}${dim(prefix)}${actualIndented}${dim(suffix)} +${error}`; + } else if (Array.isArray(annotated)) { + let result = `${indent}${dim(`${prefix}[`)} +`; + const arrayIndent = indent + " "; + for (let i = 0; i < annotated.length; i++) { + const value = annotated[i]; + if (value === void 0 && (i === 0 || annotated[i - 1] !== void 0)) { + result += `${arrayIndent}${dim("...,")} +`; + } + if (value !== void 0) { + result += print(inspectOptions, groupCounts, value, arrayIndent, { + prefix: `/* [${i}] */ `, + suffix: "," + }); + result += "\n"; + } + } + result += `${indent}${dim(`]${suffix}`)}`; + return result; + } else if (isRecord(annotated)) { + let result = `${indent}${dim(`${prefix}{`)} +`; + const objectIndent = indent + " "; + const entries = Object.entries(annotated); + for (let i = 0; i < entries.length; i++) { + const [key, value] = entries[i]; + if (value === void 0 && (i === 0 || entries[i - 1][1] !== void 0)) { + result += `${objectIndent}${dim("...,")} +`; + } + if (value !== void 0) { + result += print(inspectOptions, groupCounts, value, objectIndent, { + prefix: `${key}: `, + suffix: "," + }); + result += "\n"; + } + } + result += `${indent}${dim(`}${suffix}`)}`; + return result; + } + return ""; +} +function formatZodError(error, input) { + const sortedIssues = Array.from(error.issues).sort((a, b) => { + if (a.code !== b.code) { + if (a.code === "invalid_union") + return -1; + if (b.code === "invalid_union") + return 1; + } + return 0; + }); + let annotated; + const groupCounts = new GroupCountsMap(); + for (const issue of sortedIssues) { + annotated = annotate(groupCounts, annotated, input, issue, issue.path); + } + const inspectOptions = { + depth: 0, + colors: $.enabled + }; + return print(inspectOptions, groupCounts, annotated); +} + +// src/merge.ts +var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0"); +function isPlainObject(value) { + const proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames; +} +function convertWorkerOptionsArrayToObject(key, array) { + const _ = array; + if (key === "queueConsumers") { + const object = Object.fromEntries( + array.map((item) => [item, {}]) + ); + return object; + } else { + const object = Object.fromEntries(array.map((item) => [item, item])); + return object; + } +} +function mergeWorkerOptions(a, b) { + const aRecord = a; + for (const [key, bValue] of Object.entries(b)) { + const aValue = aRecord[key]; + if (aValue === void 0) { + aRecord[key] = bValue; + continue; + } + const aIsArray = Array.isArray(aValue); + const bIsArray = Array.isArray(bValue); + const aIsObject = isPlainObject(aValue); + const bIsObject = isPlainObject(bValue); + if (aIsArray && bIsArray) { + aRecord[key] = Array.from(new Set(aValue.concat(bValue))); + } else if (aIsArray && bIsObject) { + const aNewValue = convertWorkerOptionsArrayToObject( + // Must be an array/record key if `aValue` & `bValue` are array/record + key, + aValue + ); + Object.assign(aNewValue, bValue); + aRecord[key] = aNewValue; + } else if (aIsObject && bIsArray) { + const bNewValue = convertWorkerOptionsArrayToObject( + // Must be an array/record key if `aValue` & `bValue` are array/record + key, + bValue + ); + Object.assign(aValue, bNewValue); + } else if (aIsObject && bIsObject) { + Object.assign(aValue, bValue); + } else { + aRecord[key] = bValue; + } + } + return a; +} + +// src/index.ts +var DEFAULT_HOST = "127.0.0.1"; +function getURLSafeHost(host) { + return import_net.default.isIPv6(host) ? `[${host}]` : host; +} +function maybeGetLocallyAccessibleHost(h) { + if (h === "localhost") + return "localhost"; + if (h === "127.0.0.1" || h === "*" || h === "0.0.0.0" || h === "::") { + return "127.0.0.1"; + } + if (h === "::1") + return "[::1]"; +} +function getServerPort(server) { + const address = server.address(); + (0, import_assert12.default)(address !== null && typeof address === "object"); + return address.port; +} +function hasMultipleWorkers(opts) { + return typeof opts === "object" && opts !== null && "workers" in opts && Array.isArray(opts.workers); +} +function getRootPath(opts) { + if (typeof opts === "object" && opts !== null && "rootPath" in opts && typeof opts.rootPath === "string") { + return opts.rootPath; + } else { + return ""; + } +} +function validateOptions(opts) { + const sharedOpts = opts; + const multipleWorkers = hasMultipleWorkers(opts); + const workerOpts = multipleWorkers ? opts.workers : [opts]; + if (workerOpts.length === 0) { + throw new MiniflareCoreError("ERR_NO_WORKERS", "No workers defined"); + } + const pluginSharedOpts = {}; + const pluginWorkerOpts = Array.from(Array(workerOpts.length)).map( + () => ({}) + ); + const sharedRootPath = multipleWorkers ? getRootPath(sharedOpts) : ""; + const workerRootPaths = workerOpts.map( + (opts2) => import_path22.default.resolve(sharedRootPath, getRootPath(opts2)) + ); + try { + for (const [key, plugin] of PLUGIN_ENTRIES) { + pluginSharedOpts[key] = plugin.sharedOptions === void 0 ? void 0 : parseWithRootPath(sharedRootPath, plugin.sharedOptions, sharedOpts); + for (let i = 0; i < workerOpts.length; i++) { + const optionsPath = multipleWorkers ? ["workers", i] : void 0; + pluginWorkerOpts[i][key] = parseWithRootPath( + workerRootPaths[i], + plugin.options, + workerOpts[i], + { path: optionsPath } + ); + } + } + } catch (e) { + if (e instanceof import_zod19.z.ZodError) { + let formatted; + try { + formatted = formatZodError(e, opts); + } catch (formatError) { + const title = "[Miniflare] Validation Error Format Failure"; + const message = [ + "### Input", + "```", + import_util5.default.inspect(opts, { depth: null }), + "```", + "", + "### Validation Error", + "```", + e.stack, + "```", + "", + "### Format Error", + "```", + typeof formatError === "object" && formatError !== null && "stack" in formatError && typeof formatError.stack === "string" ? formatError.stack : String(formatError), + "```" + ].join("\n"); + const githubIssueUrl = new URL( + "https://github.com/cloudflare/miniflare/issues/new" + ); + githubIssueUrl.searchParams.set("title", title); + githubIssueUrl.searchParams.set("body", message); + formatted = [ + "Unable to format validation error.", + "Please open the following URL in your browser to create a GitHub issue:", + githubIssueUrl, + "", + message, + "" + ].join("\n"); + } + const error = new MiniflareCoreError( + "ERR_VALIDATION", + `Unexpected options passed to \`new Miniflare()\` constructor: +${formatted}` + ); + Object.defineProperty(error, "cause", { get: () => e }); + throw error; + } + throw e; + } + const names = /* @__PURE__ */ new Set(); + for (const opts2 of pluginWorkerOpts) { + const name = opts2.core.name ?? ""; + if (names.has(name)) { + throw new MiniflareCoreError( + "ERR_DUPLICATE_NAME", + name === "" ? "Multiple workers defined without a `name`" : `Multiple workers defined with the same \`name\`: "${name}"` + ); + } + names.add(name); + } + return [pluginSharedOpts, pluginWorkerOpts]; +} +function getDurableObjectClassNames(allWorkerOpts) { + const serviceClassNames = /* @__PURE__ */ new Map(); + for (const workerOpts of allWorkerOpts) { + const workerServiceName = getUserServiceName(workerOpts.core.name); + for (const designator of Object.values( + workerOpts.do.durableObjects ?? {} + )) { + const { + className, + // Fallback to current worker service if name not defined + serviceName = workerServiceName, + unsafeUniqueKey, + unsafePreventEviction + } = normaliseDurableObject(designator); + let classNames = serviceClassNames.get(serviceName); + if (classNames === void 0) { + classNames = /* @__PURE__ */ new Map(); + serviceClassNames.set(serviceName, classNames); + } + if (classNames.has(className)) { + const existingInfo = classNames.get(className); + if (existingInfo?.unsafeUniqueKey !== unsafeUniqueKey) { + throw new MiniflareCoreError( + "ERR_DIFFERENT_UNIQUE_KEYS", + `Multiple unsafe unique keys defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify( + unsafeUniqueKey + )} and ${JSON.stringify(existingInfo?.unsafeUniqueKey)}` + ); + } + if (existingInfo?.unsafePreventEviction !== unsafePreventEviction) { + throw new MiniflareCoreError( + "ERR_DIFFERENT_PREVENT_EVICTION", + `Multiple unsafe prevent eviction values defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify( + unsafePreventEviction + )} and ${JSON.stringify(existingInfo?.unsafePreventEviction)}` + ); + } + } else { + classNames.set(className, { unsafeUniqueKey, unsafePreventEviction }); + } + } + } + return serviceClassNames; +} +function invalidWrappedAsBound(name, bindingType) { + const stringName = JSON.stringify(name); + throw new MiniflareCoreError( + "ERR_INVALID_WRAPPED", + `Cannot use ${stringName} for wrapped binding because it is bound to with ${bindingType} bindings. +Ensure other workers don't define ${bindingType} bindings to ${stringName}.` + ); +} +function getWrappedBindingNames(allWorkerOpts, durableObjectClassNames) { + const wrappedBindingWorkerNames = /* @__PURE__ */ new Set(); + for (const workerOpts of allWorkerOpts) { + for (const designator of Object.values( + workerOpts.core.wrappedBindings ?? {} + )) { + const scriptName = typeof designator === "object" ? designator.scriptName : designator; + if (durableObjectClassNames.has(getUserServiceName(scriptName))) { + invalidWrappedAsBound(scriptName, "Durable Object"); + } + wrappedBindingWorkerNames.add(scriptName); + } + } + for (const workerOpts of allWorkerOpts) { + for (const designator of Object.values( + workerOpts.core.serviceBindings ?? {} + )) { + if (typeof designator !== "string") + continue; + if (wrappedBindingWorkerNames.has(designator)) { + invalidWrappedAsBound(designator, "service"); + } + } + } + return wrappedBindingWorkerNames; +} +function getQueueProducers(allWorkerOpts) { + const queueProducers = /* @__PURE__ */ new Map(); + for (const workerOpts of allWorkerOpts) { + const workerName = workerOpts.core.name ?? ""; + let workerProducers = workerOpts.queues.queueProducers; + if (workerProducers !== void 0) { + if (Array.isArray(workerProducers)) { + workerProducers = Object.fromEntries( + workerProducers.map((bindingName) => [bindingName, { queueName: bindingName }]) + ); + } + for (const [bindingName, opts] of Object.entries(workerProducers)) { + queueProducers.set(bindingName, { workerName, ...opts }); + } + } + } + return queueProducers; +} +function getQueueConsumers(allWorkerOpts) { + const queueConsumers = /* @__PURE__ */ new Map(); + for (const workerOpts of allWorkerOpts) { + const workerName = workerOpts.core.name ?? ""; + let workerConsumers = workerOpts.queues.queueConsumers; + if (workerConsumers !== void 0) { + if (Array.isArray(workerConsumers)) { + workerConsumers = Object.fromEntries( + workerConsumers.map((queueName) => [queueName, {}]) + ); + } + for (const [queueName, opts] of Object.entries(workerConsumers)) { + const existingConsumer = queueConsumers.get(queueName); + if (existingConsumer !== void 0) { + throw new QueuesError( + "ERR_MULTIPLE_CONSUMERS", + `Multiple consumers defined for queue "${queueName}": "${existingConsumer.workerName}" and "${workerName}"` + ); + } + queueConsumers.set(queueName, { workerName, ...opts }); + } + } + } + for (const [queueName, consumer] of queueConsumers) { + if (consumer.deadLetterQueue === queueName) { + throw new QueuesError( + "ERR_DEAD_LETTER_QUEUE_CYCLE", + `Dead letter queue for queue "${queueName}" cannot be itself` + ); + } + } + return queueConsumers; +} +function getWorkerRoutes(allWorkerOpts, wrappedBindingNames) { + const allRoutes = /* @__PURE__ */ new Map(); + for (const workerOpts of allWorkerOpts) { + const name = workerOpts.core.name ?? ""; + if (wrappedBindingNames.has(name)) + continue; + (0, import_assert12.default)(!allRoutes.has(name)); + allRoutes.set(name, workerOpts.core.routes ?? []); + } + return allRoutes; +} +function getProxyBindingName(plugin, worker, binding) { + return [ + CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY, + plugin, + worker, + binding + ].join(":"); +} +function isNativeTargetBinding(binding) { + return !("json" in binding || "wasmModule" in binding || "text" in binding || "data" in binding); +} +function buildProxyBinding(plugin, worker, binding) { + (0, import_assert12.default)(binding.name !== void 0); + const name = getProxyBindingName(plugin, worker, binding.name); + const proxyBinding = { ...binding, name }; + if ("durableObjectNamespace" in proxyBinding && proxyBinding.durableObjectNamespace !== void 0) { + proxyBinding.durableObjectNamespace.serviceName ??= getUserServiceName(worker); + } + return proxyBinding; +} +function getInternalDurableObjectProxyBindings(plugin, service) { + if (!("worker" in service)) + return; + (0, import_assert12.default)(service.worker !== void 0); + const serviceName = service.name; + (0, import_assert12.default)(serviceName !== void 0); + return service.worker.durableObjectNamespaces?.map(({ className }) => { + (0, import_assert12.default)(className !== void 0); + return { + name: getProxyBindingName(`${plugin}-internal`, serviceName, className), + durableObjectNamespace: { serviceName, className } + }; + }); +} +var restrictedUndiciHeaders = [ + // From Miniflare 2: + // https://github.com/cloudflare/miniflare/blob/9c135599dc21fe69080ada17fce6153692793bf1/packages/core/src/standards/http.ts#L129-L132 + "transfer-encoding", + "connection", + "keep-alive", + "expect" +]; +var restrictedWebSocketUpgradeHeaders = [ + "upgrade", + "connection", + "sec-websocket-accept" +]; +function _transformsForContentEncoding(encoding) { + const encoders = []; + if (!encoding) + return encoders; + const codings = encoding.toLowerCase().split(",").map((x) => x.trim()); + for (const coding of codings) { + if (/(x-)?gzip/.test(coding)) { + encoders.push(import_zlib.default.createGzip()); + } else if (/(x-)?deflate/.test(coding)) { + encoders.push(import_zlib.default.createDeflate()); + } else if (coding === "br") { + encoders.push(import_zlib.default.createBrotliCompress()); + } else { + encoders.length = 0; + break; + } + } + return encoders; +} +async function writeResponse(response, res) { + const headers = {}; + for (const entry of response.headers) { + const key = entry[0].toLowerCase(); + const value = entry[1]; + if (key === "set-cookie") { + headers[key] = response.headers.getSetCookie(); + } else { + headers[key] = value; + } + } + const encoding = headers["content-encoding"]?.toString(); + const encoders = _transformsForContentEncoding(encoding); + if (encoders.length > 0) { + delete headers["content-length"]; + } + res.writeHead(response.status, response.statusText, headers); + let initialStream = res; + for (let i = encoders.length - 1; i >= 0; i--) { + encoders[i].pipe(initialStream); + initialStream = encoders[i]; + } + if (response.body) { + for await (const chunk of response.body) { + if (chunk) + initialStream.write(chunk); + } + } + initialStream.end(); +} +function safeReadableStreamFrom(iterable) { + let iterator; + return new import_web5.ReadableStream({ + async start() { + iterator = iterable[Symbol.asyncIterator](); + }, + // @ts-expect-error `pull` may return anything + async pull(controller) { + try { + const { done, value } = await iterator.next(); + if (done) { + queueMicrotask(() => controller.close()); + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value); + controller.enqueue(new Uint8Array(buf)); + } + } catch { + queueMicrotask(() => controller.close()); + } + return controller.desiredSize > 0; + }, + async cancel() { + await iterator.return?.(); + } + }); +} +var maybeInstanceRegistry; +function _initialiseInstanceRegistry() { + return maybeInstanceRegistry = /* @__PURE__ */ new Map(); +} +var Miniflare2 = class { + #previousSharedOpts; + #previousWorkerOpts; + #sharedOpts; + #workerOpts; + #log; + #runtime; + #removeExitHook; + #runtimeEntryURL; + #socketPorts; + #runtimeDispatcher; + #proxyClient; + #cfObject = {}; + // Path to temporary directory for use as scratch space/"in-memory" Durable + // Object storage. Note this may not exist, it's up to the consumers to + // create this if needed. Deleted on `dispose()`. + #tmpPath; + // Mutual exclusion lock for runtime operations (i.e. initialisation and + // updating config). This essentially puts initialisation and future updates + // in a queue, ensuring they're performed in calling order. + #runtimeMutex; + // Store `#init()` `Promise`, so we can propagate initialisation errors in + // `ready`. We would have no way of catching these otherwise. + #initPromise; + // Aborted when dispose() is called + #disposeController; + #loopbackServer; + #loopbackHost; + #liveReloadServer; + #webSocketServer; + #webSocketExtraHeaders; + constructor(opts) { + const [sharedOpts, workerOpts] = validateOptions(opts); + this.#sharedOpts = sharedOpts; + this.#workerOpts = workerOpts; + if (maybeInstanceRegistry !== void 0) { + const object = { name: "Miniflare", stack: "" }; + Error.captureStackTrace(object, Miniflare2); + maybeInstanceRegistry.set(this, object.stack); + } + this.#log = this.#sharedOpts.core.log ?? new NoOpLog(); + this.#liveReloadServer = new import_ws3.WebSocketServer({ noServer: true }); + this.#webSocketServer = new import_ws3.WebSocketServer({ + noServer: true, + // Disable automatic handling of `Sec-WebSocket-Protocol` header, + // Cloudflare Workers require users to include this header themselves in + // `Response`s: https://github.com/cloudflare/miniflare/issues/179 + handleProtocols: () => false + }); + this.#webSocketExtraHeaders = /* @__PURE__ */ new WeakMap(); + this.#webSocketServer.on("headers", (headers, req) => { + const extra = this.#webSocketExtraHeaders.get(req); + this.#webSocketExtraHeaders.delete(req); + if (extra) { + for (const [key, value] of extra) { + if (!restrictedWebSocketUpgradeHeaders.includes(key.toLowerCase())) { + headers.push(`${key}: ${value}`); + } + } + } + }); + this.#tmpPath = import_path22.default.join( + import_os2.default.tmpdir(), + `miniflare-${import_crypto3.default.randomBytes(16).toString("hex")}` + ); + this.#runtime = new Runtime(); + this.#removeExitHook = (0, import_exit_hook.default)(() => { + void this.#runtime?.dispose(); + try { + import_fs18.default.rmSync(this.#tmpPath, { force: true, recursive: true }); + } catch (e) { + this.#log.debug(`Unable to remove temporary directory: ${String(e)}`); + } + }); + this.#disposeController = new AbortController(); + this.#runtimeMutex = new Mutex(); + this.#initPromise = this.#runtimeMutex.runWith(() => this.#assembleAndUpdateConfig()).catch((e) => { + maybeInstanceRegistry?.delete(this); + throw e; + }); + } + #handleReload() { + for (const ws of this.#liveReloadServer.clients) { + ws.close(1012, "Service Restart"); + } + for (const ws of this.#webSocketServer.clients) { + ws.close(1012, "Service Restart"); + } + } + async #handleLoopbackCustomService(request, customService) { + const slashIndex = customService.indexOf("/"); + const workerIndex = parseInt(customService.substring(0, slashIndex)); + const serviceKind = customService[slashIndex + 1]; + const serviceName = customService.substring(slashIndex + 2); + let service; + if (serviceKind === "#" /* UNKNOWN */) { + service = this.#workerOpts[workerIndex]?.core.serviceBindings?.[serviceName]; + } else if (serviceName === CUSTOM_SERVICE_KNOWN_OUTBOUND) { + service = this.#workerOpts[workerIndex]?.core.outboundService; + } + (0, import_assert12.default)(typeof service === "function"); + try { + const response = await service(request, this); + return import_zod19.z.instanceof(Response).parse(response); + } catch (e) { + return new Response(e?.stack ?? e, { status: 500 }); + } + } + get #workerSrcOpts() { + return this.#workerOpts.map(({ core }) => core); + } + #handleLoopback = async (req, res) => { + const headers = new import_undici5.Headers(); + for (const [name, values] of Object.entries(req.headers)) { + if (restrictedUndiciHeaders.includes(name)) + continue; + if (Array.isArray(values)) { + for (const value of values) + headers.append(name, value); + } else if (values !== void 0) { + headers.append(name, values); + } + } + const cfBlob = headers.get(CoreHeaders.CF_BLOB); + headers.delete(CoreHeaders.CF_BLOB); + (0, import_assert12.default)(!Array.isArray(cfBlob)); + const cf = cfBlob ? JSON.parse(cfBlob) : void 0; + const originalUrl = headers.get(CoreHeaders.ORIGINAL_URL); + const url14 = new URL(originalUrl ?? req.url ?? "", "http://localhost"); + headers.delete(CoreHeaders.ORIGINAL_URL); + const noBody = req.method === "GET" || req.method === "HEAD"; + const body = noBody ? void 0 : safeReadableStreamFrom(req); + const request = new Request(url14, { + method: req.method, + headers, + body, + duplex: "half", + cf + }); + let response; + try { + const customService = request.headers.get(CoreHeaders.CUSTOM_SERVICE); + if (customService !== null) { + request.headers.delete(CoreHeaders.CUSTOM_SERVICE); + response = await this.#handleLoopbackCustomService( + request, + customService + ); + } else if (this.#sharedOpts.core.unsafeModuleFallbackService !== void 0 && request.headers.has("X-Resolve-Method") && originalUrl === null) { + response = await this.#sharedOpts.core.unsafeModuleFallbackService( + request, + this + ); + } else if (url14.pathname === "/core/error") { + response = await handlePrettyErrorRequest( + this.#log, + this.#workerSrcOpts, + request + ); + } else if (url14.pathname === "/core/log") { + const level = parseInt(request.headers.get(SharedHeaders.LOG_LEVEL)); + (0, import_assert12.default)( + 0 /* NONE */ <= level && level <= 5 /* VERBOSE */, + `Expected ${SharedHeaders.LOG_LEVEL} header to be log level, got ${level}` + ); + const logLevel = level; + let message = await request.text(); + if (!$.enabled) + message = stripAnsi(message); + this.#log.logWithLevel(logLevel, message); + response = new Response(null, { status: 204 }); + } + } catch (e) { + this.#log.error(e); + res?.writeHead(500); + res?.end(e?.stack ?? String(e)); + return; + } + if (res !== void 0) { + if (response === void 0) { + res.writeHead(404); + res.end(); + } else { + await writeResponse(response, res); + } + } + return response; + }; + #handleLoopbackUpgrade = async (req, socket, head) => { + const { pathname } = new URL(req.url ?? "", "http://localhost"); + if (pathname === "/cdn-cgi/mf/reload") { + this.#liveReloadServer.handleUpgrade(req, socket, head, (ws) => { + this.#liveReloadServer.emit("connection", ws, req); + }); + return; + } + const response = await this.#handleLoopback(req); + const webSocket = response?.webSocket; + if (response?.status === 101 && webSocket) { + this.#webSocketExtraHeaders.set(req, response.headers); + this.#webSocketServer.handleUpgrade(req, socket, head, (ws) => { + void coupleWebSocket(ws, webSocket); + this.#webSocketServer.emit("connection", ws, req); + }); + return; + } + const res = new import_http6.default.ServerResponse(req); + (0, import_assert12.default)(socket instanceof import_net.default.Socket); + res.assignSocket(socket); + if (!response || response.ok) { + res.writeHead(500); + res.end(); + this.#log.error( + new TypeError( + "Web Socket request did not return status 101 Switching Protocols response with Web Socket" + ) + ); + return; + } + await writeResponse(response, res); + }; + async #getLoopbackPort() { + const loopbackHost = this.#sharedOpts.core.host ?? DEFAULT_HOST; + if (this.#loopbackServer !== void 0) { + if (this.#loopbackHost === loopbackHost) { + return getServerPort(this.#loopbackServer); + } + await this.#stopLoopbackServer(); + } + this.#loopbackServer = await this.#startLoopbackServer(loopbackHost); + this.#loopbackHost = loopbackHost; + return getServerPort(this.#loopbackServer); + } + #startLoopbackServer(hostname) { + if (hostname === "*") + hostname = "::"; + return new Promise((resolve) => { + const server = (0, import_stoppable.default)( + import_http6.default.createServer(this.#handleLoopback), + /* grace */ + 0 + ); + server.on("upgrade", this.#handleLoopbackUpgrade); + server.listen(0, hostname, () => resolve(server)); + }); + } + #stopLoopbackServer() { + return new Promise((resolve, reject) => { + (0, import_assert12.default)(this.#loopbackServer !== void 0); + this.#loopbackServer.stop((err) => err ? reject(err) : resolve()); + }); + } + #getSocketAddress(id, previousRequestedPort, host = DEFAULT_HOST, requestedPort) { + if (requestedPort === 0 && previousRequestedPort === 0) { + requestedPort = this.#socketPorts?.get(id); + } + return `${getURLSafeHost(host)}:${requestedPort ?? 0}`; + } + async #assembleConfig(loopbackPort) { + const allPreviousWorkerOpts = this.#previousWorkerOpts; + const allWorkerOpts = this.#workerOpts; + const sharedOpts = this.#sharedOpts; + sharedOpts.core.cf = await setupCf(this.#log, sharedOpts.core.cf); + this.#cfObject = sharedOpts.core.cf; + const durableObjectClassNames = getDurableObjectClassNames(allWorkerOpts); + const wrappedBindingNames = getWrappedBindingNames( + allWorkerOpts, + durableObjectClassNames + ); + const queueProducers = getQueueProducers(allWorkerOpts); + const queueConsumers = getQueueConsumers(allWorkerOpts); + const allWorkerRoutes = getWorkerRoutes(allWorkerOpts, wrappedBindingNames); + const workerNames = [...allWorkerRoutes.keys()]; + const services = /* @__PURE__ */ new Map(); + const extensions = [ + { + modules: [ + { name: "miniflare:shared", esModule: index_worker_default() }, + { name: "miniflare:zod", esModule: zod_worker_default() } + ] + } + ]; + const sockets = [ + { + name: SOCKET_ENTRY, + service: { name: SERVICE_ENTRY }, + ...await getEntrySocketHttpOptions(sharedOpts.core) + } + ]; + const configuredHost = sharedOpts.core.host ?? DEFAULT_HOST; + if (maybeGetLocallyAccessibleHost(configuredHost) === void 0) { + sockets.push({ + name: SOCKET_ENTRY_LOCAL, + service: { name: SERVICE_ENTRY }, + http: ENTRY_SOCKET_HTTP_OPTIONS, + address: "127.0.0.1:0" + }); + } + const proxyBindings = []; + const allWorkerBindings = /* @__PURE__ */ new Map(); + const wrappedBindingsToPopulate = []; + for (let i = 0; i < allWorkerOpts.length; i++) { + const previousWorkerOpts = allPreviousWorkerOpts?.[i]; + const workerOpts = allWorkerOpts[i]; + const workerName = workerOpts.core.name ?? ""; + const isModulesWorker = Boolean(workerOpts.core.modules); + const workerBindings = []; + allWorkerBindings.set(workerName, workerBindings); + const additionalModules = []; + for (const [key, plugin] of PLUGIN_ENTRIES) { + const pluginBindings = await plugin.getBindings(workerOpts[key], i); + if (pluginBindings !== void 0) { + for (const binding of pluginBindings) { + if (key === "kv" && binding.name === SiteBindings.JSON_SITE_MANIFEST && isModulesWorker) { + (0, import_assert12.default)("json" in binding && binding.json !== void 0); + additionalModules.push({ + name: SiteBindings.JSON_SITE_MANIFEST, + text: binding.json + }); + } else { + workerBindings.push(binding); + } + if (isNativeTargetBinding(binding)) { + proxyBindings.push(buildProxyBinding(key, workerName, binding)); + } + if ("wrapped" in binding && binding.wrapped?.moduleName !== void 0 && binding.wrapped.innerBindings !== void 0) { + const workerName2 = maybeWrappedModuleToWorkerName( + binding.wrapped.moduleName + ); + if (workerName2 !== void 0) { + wrappedBindingsToPopulate.push({ + workerName: workerName2, + innerBindings: binding.wrapped.innerBindings + }); + } + } + } + } + } + const unsafeStickyBlobs = sharedOpts.core.unsafeStickyBlobs ?? false; + const unsafeEphemeralDurableObjects = workerOpts.core.unsafeEphemeralDurableObjects ?? false; + const pluginServicesOptionsBase = { + log: this.#log, + workerBindings, + workerIndex: i, + additionalModules, + tmpPath: this.#tmpPath, + workerNames, + loopbackPort, + unsafeStickyBlobs, + wrappedBindingNames, + durableObjectClassNames, + unsafeEphemeralDurableObjects, + queueProducers, + queueConsumers + }; + for (const [key, plugin] of PLUGIN_ENTRIES) { + const pluginServicesExtensions = await plugin.getServices({ + ...pluginServicesOptionsBase, + // @ts-expect-error `CoreOptionsSchema` has required options which are + // missing in other plugins' options. + options: workerOpts[key], + // @ts-expect-error `QueuesPlugin` doesn't define shared options + sharedOptions: sharedOpts[key] + }); + if (pluginServicesExtensions !== void 0) { + let pluginServices; + if (Array.isArray(pluginServicesExtensions)) { + pluginServices = pluginServicesExtensions; + } else { + pluginServices = pluginServicesExtensions.services; + extensions.push(...pluginServicesExtensions.extensions); + } + for (const service of pluginServices) { + if (service.name !== void 0 && !services.has(service.name)) { + services.set(service.name, service); + if (key !== DURABLE_OBJECTS_PLUGIN_NAME) { + const maybeBindings = getInternalDurableObjectProxyBindings( + key, + service + ); + if (maybeBindings !== void 0) { + proxyBindings.push(...maybeBindings); + } + } + } + } + } + } + const previousDirectSockets = previousWorkerOpts?.core.unsafeDirectSockets ?? []; + const directSockets = workerOpts.core.unsafeDirectSockets ?? []; + for (let j = 0; j < directSockets.length; j++) { + const previousDirectSocket = previousDirectSockets[j]; + const directSocket = directSockets[j]; + const entrypoint = directSocket.entrypoint ?? "default"; + const name = getDirectSocketName(i, entrypoint); + const address = this.#getSocketAddress( + name, + previousDirectSocket?.port, + directSocket.host, + directSocket.port + ); + sockets.push({ + name, + address, + service: { + name: getUserServiceName(workerName), + entrypoint: entrypoint === "default" ? void 0 : entrypoint + }, + http: { + style: directSocket.proxy ? import_workerd_capnp.HttpOptions_Style.PROXY : void 0, + cfBlobHeader: CoreHeaders.CF_BLOB, + capnpConnectHost: HOST_CAPNP_CONNECT + } + }); + } + } + const globalServices = getGlobalServices({ + sharedOptions: sharedOpts.core, + allWorkerRoutes, + fallbackWorkerName: this.#workerOpts[0].core.name, + loopbackPort, + log: this.#log, + proxyBindings + }); + for (const service of globalServices) { + (0, import_assert12.default)(service.name !== void 0 && !services.has(service.name)); + services.set(service.name, service); + } + for (const toPopulate of wrappedBindingsToPopulate) { + const bindings = allWorkerBindings.get(toPopulate.workerName); + if (bindings === void 0) + continue; + const existingBindingNames = new Set( + toPopulate.innerBindings.map(({ name }) => name) + ); + toPopulate.innerBindings.push( + ...bindings.filter(({ name }) => !existingBindingNames.has(name)) + ); + } + const servicesArray = Array.from(services.values()); + if (wrappedBindingsToPopulate.length > 0 && _isCyclic(servicesArray)) { + throw new MiniflareCoreError( + "ERR_CYCLIC", + "Generated workerd config contains cycles. Ensure wrapped bindings don't have bindings to themselves." + ); + } + const autogates = [ + // Enables Python support in workerd. + // TODO(later): remove this once this gate is removed from workerd. + "workerd-autogate-builtin-wasm-modules" + ]; + return { services: servicesArray, sockets, extensions, autogates }; + } + async #assembleAndUpdateConfig() { + const initial = !this.#runtimeEntryURL; + (0, import_assert12.default)(this.#runtime !== void 0); + const loopbackPort = await this.#getLoopbackPort(); + const config = await this.#assembleConfig(loopbackPort); + const configBuffer = serializeConfig(config); + (0, import_assert12.default)(config.sockets !== void 0); + const requiredSockets = config.sockets.map( + ({ name }) => { + (0, import_assert12.default)(name !== void 0); + return name; + } + ); + if (this.#sharedOpts.core.inspectorPort !== void 0) { + requiredSockets.push(kInspectorSocket); + } + const configuredHost = this.#sharedOpts.core.host ?? DEFAULT_HOST; + const entryAddress = this.#getSocketAddress( + SOCKET_ENTRY, + this.#previousSharedOpts?.core.port, + configuredHost, + this.#sharedOpts.core.port + ); + let inspectorAddress; + if (this.#sharedOpts.core.inspectorPort !== void 0) { + inspectorAddress = this.#getSocketAddress( + kInspectorSocket, + this.#previousSharedOpts?.core.inspectorPort, + "localhost", + this.#sharedOpts.core.inspectorPort + ); + } + const loopbackAddress = `${maybeGetLocallyAccessibleHost(configuredHost) ?? getURLSafeHost(configuredHost)}:${loopbackPort}`; + const runtimeOpts = { + signal: this.#disposeController.signal, + entryAddress, + loopbackAddress, + requiredSockets, + inspectorAddress, + verbose: this.#sharedOpts.core.verbose, + handleRuntimeStdio: this.#sharedOpts.core.handleRuntimeStdio + }; + const maybeSocketPorts = await this.#runtime.updateConfig( + configBuffer, + runtimeOpts + ); + if (this.#disposeController.signal.aborted) + return; + if (maybeSocketPorts === void 0) { + throw new MiniflareCoreError( + "ERR_RUNTIME_FAILURE", + "The Workers runtime failed to start. There is likely additional logging output above." + ); + } + this.#socketPorts = maybeSocketPorts; + const entrySocket = config.sockets?.[0]; + const secure = entrySocket !== void 0 && "https" in entrySocket; + const previousEntryURL = this.#runtimeEntryURL; + const entryPort = maybeSocketPorts.get(SOCKET_ENTRY); + (0, import_assert12.default)(entryPort !== void 0); + const maybeAccessibleHost = maybeGetLocallyAccessibleHost(configuredHost); + if (maybeAccessibleHost === void 0) { + const localEntryPort = maybeSocketPorts.get(SOCKET_ENTRY_LOCAL); + (0, import_assert12.default)(localEntryPort !== void 0, "Expected local entry socket port"); + this.#runtimeEntryURL = new URL(`http://127.0.0.1:${localEntryPort}`); + } else { + this.#runtimeEntryURL = new URL( + `${secure ? "https" : "http"}://${maybeAccessibleHost}:${entryPort}` + ); + } + if (previousEntryURL?.toString() !== this.#runtimeEntryURL.toString()) { + this.#runtimeDispatcher = new import_undici9.Pool(this.#runtimeEntryURL, { + connect: { rejectUnauthorized: false } + }); + } + if (this.#proxyClient === void 0) { + this.#proxyClient = new ProxyClient( + this.#runtimeEntryURL, + this.dispatchFetch + ); + } else { + this.#proxyClient.setRuntimeEntryURL(this.#runtimeEntryURL); + } + if (!this.#runtimeMutex.hasWaiting) { + const ready = initial ? "Ready" : "Updated and ready"; + const urlSafeHost = getURLSafeHost(configuredHost); + this.#log.info( + `${ready} on ${secure ? "https" : "http"}://${urlSafeHost}:${entryPort}` + ); + if (initial) { + const hosts = []; + if (configuredHost === "::" || configuredHost === "*") { + hosts.push("localhost"); + hosts.push("[::1]"); + } + if (configuredHost === "::" || configuredHost === "*" || configuredHost === "0.0.0.0") { + hosts.push(...getAccessibleHosts(true)); + } + for (const h of hosts) { + this.#log.info(`- ${secure ? "https" : "http"}://${h}:${entryPort}`); + } + } + this.#handleReload(); + } + } + async #waitForReady(disposing = false) { + await this.#initPromise; + await this.#runtimeMutex.drained(); + if (disposing) + return new URL("http://[100::]/"); + this.#checkDisposed(); + (0, import_assert12.default)(this.#runtimeEntryURL !== void 0); + return new URL(this.#runtimeEntryURL.toString()); + } + get ready() { + return this.#waitForReady(); + } + async getCf() { + this.#checkDisposed(); + await this.ready; + return JSON.parse(JSON.stringify(this.#cfObject)); + } + async getInspectorURL() { + this.#checkDisposed(); + await this.ready; + (0, import_assert12.default)(this.#socketPorts !== void 0); + const maybePort = this.#socketPorts.get(kInspectorSocket); + if (maybePort === void 0) { + throw new TypeError( + "Inspector not enabled in Miniflare instance. Set the `inspectorPort` option to enable it." + ); + } + return new URL(`ws://127.0.0.1:${maybePort}`); + } + async unsafeGetDirectURL(workerName, entrypoint = "default") { + this.#checkDisposed(); + await this.ready; + const workerIndex = this.#findAndAssertWorkerIndex(workerName); + const workerOpts = this.#workerOpts[workerIndex]; + const socketName = getDirectSocketName(workerIndex, entrypoint); + (0, import_assert12.default)(this.#socketPorts !== void 0); + const maybePort = this.#socketPorts.get(socketName); + if (maybePort === void 0) { + const friendlyWorkerName = workerName === void 0 ? "entrypoint" : JSON.stringify(workerName); + const friendlyEntrypointName = entrypoint === "default" ? entrypoint : JSON.stringify(entrypoint); + throw new TypeError( + `Direct access disabled in ${friendlyWorkerName} worker for ${friendlyEntrypointName} entrypoint` + ); + } + const directSocket = workerOpts.core.unsafeDirectSockets?.find( + (socket) => (socket.entrypoint ?? "default") === entrypoint + ); + (0, import_assert12.default)(directSocket !== void 0); + const host = directSocket.host ?? DEFAULT_HOST; + const accessibleHost = maybeGetLocallyAccessibleHost(host) ?? getURLSafeHost(host); + return new URL(`http://${accessibleHost}:${maybePort}`); + } + #checkDisposed() { + if (this.#disposeController.signal.aborted) { + throw new MiniflareCoreError( + "ERR_DISPOSED", + "Cannot use disposed instance" + ); + } + } + async #setOptions(opts) { + const [sharedOpts, workerOpts] = validateOptions(opts); + this.#previousSharedOpts = this.#sharedOpts; + this.#previousWorkerOpts = this.#workerOpts; + this.#sharedOpts = sharedOpts; + this.#workerOpts = workerOpts; + this.#log = this.#sharedOpts.core.log ?? this.#log; + await this.#assembleAndUpdateConfig(); + } + setOptions(opts) { + this.#checkDisposed(); + this.#proxyClient?.poisonProxies(); + return this.#runtimeMutex.runWith(() => this.#setOptions(opts)); + } + dispatchFetch = async (input, init2) => { + this.#checkDisposed(); + await this.ready; + (0, import_assert12.default)(this.#runtimeEntryURL !== void 0); + (0, import_assert12.default)(this.#runtimeDispatcher !== void 0); + const forward = new Request(input, init2); + const url14 = new URL(forward.url); + const actualRuntimeOrigin = this.#runtimeEntryURL.origin; + const userRuntimeOrigin = url14.origin; + url14.protocol = this.#runtimeEntryURL.protocol; + url14.host = this.#runtimeEntryURL.host; + if (forward.body !== null && forward.headers.get("Content-Length") === "0") { + forward.headers.delete("Content-Length"); + } + const cfBlob = forward.cf ? { ...fallbackCf, ...forward.cf } : void 0; + const dispatcher = new DispatchFetchDispatcher( + (0, import_undici9.getGlobalDispatcher)(), + this.#runtimeDispatcher, + actualRuntimeOrigin, + userRuntimeOrigin, + cfBlob + ); + const forwardInit = forward; + forwardInit.dispatcher = dispatcher; + const response = await fetch2(url14, forwardInit); + const stack = response.headers.get(CoreHeaders.ERROR_STACK); + if (response.status === 500 && stack !== null) { + const caught = JsonErrorSchema.parse(await response.json()); + throw reviveError(this.#workerSrcOpts, caught); + } + if (process.env.MINIFLARE_ASSERT_BODIES_CONSUMED === "true" && response.body !== null) { + const originalLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Infinity; + const error = new Error( + "`body` returned from `Miniflare#dispatchFetch()` not consumed immediately" + ); + Error.stackTraceLimit = originalLimit; + setImmediate(() => { + if (!response.bodyUsed) + throw error; + }); + } + return response; + }; + /** @internal */ + async _getProxyClient() { + this.#checkDisposed(); + await this.ready; + (0, import_assert12.default)(this.#proxyClient !== void 0); + return this.#proxyClient; + } + #findAndAssertWorkerIndex(workerName) { + if (workerName === void 0) { + return 0; + } else { + const index = this.#workerOpts.findIndex( + ({ core }) => (core.name ?? "") === workerName + ); + if (index === -1) { + throw new TypeError(`${JSON.stringify(workerName)} worker not found`); + } + return index; + } + } + async getBindings(workerName) { + const bindings = {}; + const proxyClient = await this._getProxyClient(); + const workerIndex = this.#findAndAssertWorkerIndex(workerName); + const workerOpts = this.#workerOpts[workerIndex]; + workerName = workerOpts.core.name ?? ""; + for (const [key, plugin] of PLUGIN_ENTRIES) { + const pluginBindings = await plugin.getNodeBindings(workerOpts[key]); + for (const [name, binding] of Object.entries(pluginBindings)) { + if (binding === kProxyNodeBinding) { + const proxyBindingName = getProxyBindingName(key, workerName, name); + const proxy = proxyClient.env[proxyBindingName]; + (0, import_assert12.default)( + proxy !== void 0, + `Expected ${proxyBindingName} to be bound` + ); + bindings[name] = proxy; + } else { + bindings[name] = binding; + } + } + } + return bindings; + } + async getWorker(workerName) { + const proxyClient = await this._getProxyClient(); + const workerIndex = this.#findAndAssertWorkerIndex(workerName); + const workerOpts = this.#workerOpts[workerIndex]; + workerName = workerOpts.core.name ?? ""; + const bindingName = CoreBindings.SERVICE_USER_ROUTE_PREFIX + workerName; + const fetcher = proxyClient.env[bindingName]; + if (fetcher === void 0) { + const stringName = JSON.stringify(workerName); + throw new TypeError( + `${stringName} is being used as a wrapped binding, and cannot be accessed as a worker` + ); + } + return fetcher; + } + async #getProxy(pluginName, bindingName, workerName) { + const proxyClient = await this._getProxyClient(); + const proxyBindingName = getProxyBindingName( + pluginName, + // Default to entrypoint worker if none specified + workerName ?? this.#workerOpts[0].core.name ?? "", + bindingName + ); + const proxy = proxyClient.env[proxyBindingName]; + if (proxy === void 0) { + const friendlyWorkerName = workerName === void 0 ? "entrypoint" : JSON.stringify(workerName); + throw new TypeError( + `${JSON.stringify(bindingName)} unbound in ${friendlyWorkerName} worker` + ); + } + return proxy; + } + // TODO(someday): would be nice to define these in plugins + async getCaches() { + const proxyClient = await this._getProxyClient(); + return proxyClient.global.caches; + } + getD1Database(bindingName, workerName) { + return this.#getProxy(D1_PLUGIN_NAME, bindingName, workerName); + } + getDurableObjectNamespace(bindingName, workerName) { + return this.#getProxy(DURABLE_OBJECTS_PLUGIN_NAME, bindingName, workerName); + } + getKVNamespace(bindingName, workerName) { + return this.#getProxy(KV_PLUGIN_NAME, bindingName, workerName); + } + getQueueProducer(bindingName, workerName) { + return this.#getProxy(QUEUES_PLUGIN_NAME, bindingName, workerName); + } + getR2Bucket(bindingName, workerName) { + return this.#getProxy(R2_PLUGIN_NAME, bindingName, workerName); + } + /** @internal */ + _getInternalDurableObjectNamespace(pluginName, serviceName, className) { + return this.#getProxy(`${pluginName}-internal`, className, serviceName); + } + unsafeGetPersistPaths() { + const result = /* @__PURE__ */ new Map(); + for (const [key, plugin] of PLUGIN_ENTRIES) { + const sharedOpts = this.#sharedOpts[key]; + const maybePath = plugin.getPersistPath?.(sharedOpts, this.#tmpPath); + if (maybePath !== void 0) + result.set(key, maybePath); + } + return result; + } + async dispose() { + this.#disposeController.abort(); + this.#proxyClient?.poisonProxies(); + try { + await this.#waitForReady( + /* disposing */ + true + ); + } finally { + this.#removeExitHook?.(); + await this.#proxyClient?.dispose(); + await this.#runtime?.dispose(); + await this.#stopLoopbackServer(); + await import_fs18.default.promises.rm(this.#tmpPath, { force: true, recursive: true }); + maybeInstanceRegistry?.delete(this); + } + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + CACHE_PLUGIN, + CACHE_PLUGIN_NAME, + CORE_PLUGIN, + CORE_PLUGIN_NAME, + CacheBindings, + CacheHeaders, + CacheOptionsSchema, + CacheSharedOptionsSchema, + CloseEvent, + CoreBindings, + CoreHeaders, + CoreOptionsSchema, + CoreSharedOptionsSchema, + D1OptionsSchema, + D1SharedOptionsSchema, + D1_PLUGIN, + D1_PLUGIN_NAME, + DEFAULT_PERSIST_ROOT, + DURABLE_OBJECTS_PLUGIN, + DURABLE_OBJECTS_PLUGIN_NAME, + DURABLE_OBJECTS_STORAGE_SERVICE_NAME, + DeferredPromise, + DispatchFetchDispatcher, + DurableObjectsOptionsSchema, + DurableObjectsSharedOptionsSchema, + ENTRY_SOCKET_HTTP_OPTIONS, + ErrorEvent, + File, + FormData, + HOST_CAPNP_CONNECT, + HYPERDRIVE_PLUGIN, + HYPERDRIVE_PLUGIN_NAME, + Headers, + HttpOptions_Style, + HyperdriveInputOptionsSchema, + HyperdriveSchema, + JsonSchema, + KVHeaders, + KVLimits, + KVOptionsSchema, + KVParams, + KVSharedOptionsSchema, + KV_PLUGIN, + KV_PLUGIN_NAME, + LiteralSchema, + Log, + LogLevel, + MessageEvent, + Miniflare, + MiniflareCoreError, + MiniflareError, + ModuleDefinitionSchema, + ModuleRuleSchema, + ModuleRuleTypeSchema, + Mutex, + NoOpLog, + PLUGINS, + PLUGIN_ENTRIES, + PathSchema, + PeriodType, + PersistenceSchema, + ProxyAddresses, + ProxyClient, + ProxyOps, + QUEUES_PLUGIN, + QUEUES_PLUGIN_NAME, + QueueBindings, + QueueConsumerOptionsSchema, + QueueConsumerSchema, + QueueConsumersSchema, + QueueContentTypeSchema, + QueueIncomingMessageSchema, + QueueMessageDelaySchema, + QueueProducerOptionsSchema, + QueueProducerSchema, + QueueProducersSchema, + QueuesBatchRequestSchema, + QueuesError, + QueuesOptionsSchema, + R2OptionsSchema, + R2SharedOptionsSchema, + R2_PLUGIN, + R2_PLUGIN_NAME, + RATELIMIT_PLUGIN, + RATELIMIT_PLUGIN_NAME, + RatelimitConfigSchema, + RatelimitOptionsSchema, + Request, + Response, + RouterError, + Runtime, + SERVICE_ENTRY, + SERVICE_LOOPBACK, + SITES_NO_CACHE_PREFIX, + SOCKET_ENTRY, + SOCKET_ENTRY_LOCAL, + SharedBindings, + SharedHeaders, + SiteBindings, + SourceOptionsSchema, + TlsOptions_Version, + TypedEventTarget, + WORKER_BINDING_SERVICE_LOOPBACK, + WaitGroup, + WebSocket, + WebSocketPair, + Worker_Binding_CryptoKey_Usage, + _enableControlEndpoints, + _forceColour, + _initialiseInstanceRegistry, + _isCyclic, + _transformsForContentEncoding, + base64Decode, + base64Encode, + compileModuleRules, + coupleWebSocket, + createFetchMock, + createHTTPReducers, + createHTTPRevivers, + decodeSitesKey, + deserialiseRegExps, + deserialiseSiteRegExps, + encodeSitesKey, + fetch, + formatZodError, + getAccessibleHosts, + getCacheServiceName, + getDirectSocketName, + getEntrySocketHttpOptions, + getFreshSourceMapSupport, + getGlobalServices, + getMiniflareObjectBindings, + getPersistPath, + getRootPath, + globsToRegExps, + isFetcherFetch, + isR2ObjectWriteHttpMetadata, + isSitesRequest, + kCurrentWorker, + kInspectorSocket, + kProxyNodeBinding, + kUnsafeEphemeralUniqueKey, + kVoid, + matchRoutes, + maybeApply, + maybeParseURL, + mergeWorkerOptions, + migrateDatabase, + namespaceEntries, + namespaceKeys, + normaliseDurableObject, + objectEntryWorker, + parseRanges, + parseRoutes, + parseWithReadableStreams, + parseWithRootPath, + prefixError, + prefixStream, + readPrefix, + reduceError, + sanitisePath, + serialiseRegExps, + serialiseSiteRegExps, + serializeConfig, + stringifyWithStreams, + stripAnsi, + structuredSerializableReducers, + structuredSerializableRevivers, + supportedCompatibilityDate, + testRegExps, + testSiteRegExps, + viewToBuffer, + zAwaitable +}); +/*! Path sanitisation regexps adapted from node-sanitize-filename: + * https://github.com/parshap/node-sanitize-filename/blob/209c39b914c8eb48ee27bcbde64b2c7822fdf3de/index.js#L4-L37 + * + * Licensed under the ISC license: + * + * Copyright Parsha Pourkhomami + * + * 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. + */ +/*! + * MIT License + * + * Copyright (c) Sindre Sorhus (https://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. + */ +/*! + * Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.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. + */ +//# sourceMappingURL=index.js.map diff --git a/node_modules/miniflare/dist/src/index.js.map b/node_modules/miniflare/dist/src/index.js.map new file mode 100644 index 0000000..571e573 --- /dev/null +++ b/node_modules/miniflare/dist/src/index.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../src/runtime/config/workerd.capnp.js", "../../src/index.ts", "../../../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/index.worker.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/zod.worker.ts", "../../src/cf.ts", "../../src/http/fetch.ts", "../../src/workers/cache/constants.ts", "../../src/workers/core/constants.ts", "../../src/workers/core/devalue.ts", "../../../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/utils.js", "../../../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/constants.js", "../../../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/parse.js", "../../../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/stringify.js", "../../src/workers/core/routing.ts", "../../src/workers/shared/constants.ts", "../../src/workers/shared/data.ts", "../../src/workers/shared/matcher.ts", "../../src/workers/shared/range.ts", "../../src/workers/shared/sync.ts", "../../src/workers/shared/types.ts", "../../src/workers/kv/constants.ts", "../../src/workers/queues/constants.ts", "../../src/workers/shared/zod.worker.ts", "../../src/workers/queues/schemas.ts", "../../src/http/request.ts", "../../src/http/response.ts", "../../src/http/websocket.ts", "../../src/shared/colour.ts", "../../src/shared/error.ts", "../../src/shared/event.ts", "../../src/shared/log.ts", "../../src/shared/matcher.ts", "../../src/shared/streams.ts", "../../src/shared/types.ts", "../../src/http/server.ts", "../../src/http/cert.ts", "../../src/http/helpers.ts", "../../src/http/index.ts", "../../src/plugins/cache/index.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache.worker.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache-entry.worker.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache-entry-noop.worker.ts", "../../src/plugins/shared/index.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/object-entry.worker.ts", "../../src/plugins/shared/constants.ts", "../../src/plugins/shared/routing.ts", "../../src/plugins/core/index.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/core/entry.worker.ts", "../../src/runtime/index.ts", "../../src/runtime/config/index.ts", "../../src/runtime/config/workerd.ts", "../../src/plugins/do/index.ts", "../../src/plugins/core/constants.ts", "../../src/plugins/core/modules.ts", "../../src/plugins/core/proxy/client.ts", "../../src/plugins/core/proxy/fetch-sync.ts", "../../src/plugins/core/errors/index.ts", "../../src/plugins/core/errors/sourcemap.ts", "../../src/plugins/core/errors/callsite.ts", "../../src/plugins/core/proxy/types.ts", "../../src/plugins/core/services.ts", "../../src/plugins/d1/index.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/d1/database.worker.ts", "../../src/plugins/hyperdrive/index.ts", "../../src/plugins/kv/index.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/kv/namespace.worker.ts", "../../src/plugins/kv/constants.ts", "../../src/plugins/kv/sites.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/kv/sites.worker.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/queues/broker.worker.ts", "../../src/plugins/queues/index.ts", "../../src/plugins/queues/errors.ts", "../../src/plugins/r2/index.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/r2/bucket.worker.ts", "embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/ratelimit/ratelimit.worker.ts", "../../src/plugins/ratelimit/index.ts", "../../src/plugins/index.ts", "../../src/zod-format.ts", "../../src/merge.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,WAAO,eAAe,SAAS,cAAc,EAAE,OAAO,KAAK,CAAC;AAC5D,YAAQ,YAAY,QAAQ,mBAAmB,QAAQ,aAAa,QAAQ,qBAAqB,QAAQ,qBAAqB,QAAQ,cAAc,QAAQ,qBAAqB,QAAQ,oBAAoB,QAAQ,gBAAgB,QAAQ,UAAU,QAAQ,iBAAiB,QAAQ,uBAAuB,QAAQ,qBAAqB,QAAQ,uBAAuB,QAAQ,SAAS,QAAQ,eAAe,QAAQ,8BAA8B,QAAQ,oCAAoC,QAAQ,gCAAgC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Q;AACjC,YAAM,KAAK,UAAU,QAAQ;AAC7B,YAAM,KAAK,oBAAoB;AAE/B,YAAM,YAAAS,QAAG,SAAS,GAAG,KAAK,UAAU,EAAE,OAAO,MAAM,WAAW,KAAK,CAAC;AAIpE,6BAAuB,OAAO,IAAI;AAAA,IACnC;AAAA,EACD;AACD;", + "names": ["Config", "Socket_Which", "Socket", "ServiceDesignator", "Service_Which", "Service", "Worker", "ExternalServer", "Worker_Module_Which", "Worker_Module", "Worker_Binding_Type_Which", "Worker_Binding_DurableObjectNamespaceDesignator", "Worker_Binding_CryptoKey_Usage", "Worker_Binding_CryptoKey_Algorithm_Which", "Worker_Binding_CryptoKey_Which", "Worker_Binding_Which", "Worker_Binding", "Worker_DurableObjectNamespace_Which", "Worker_DurableObjectNamespace", "Worker_DurableObjectStorage_Which", "Worker_Which", "ExternalServer_Which", "HttpOptions_Style", "TlsOptions_Version", "Extension", "CORE_PLUGIN_NAME", "Miniflare", "fetch", "supportedCompatibilityDate", "import_assert", "import_crypto", "import_fs", "import_http", "import_os", "import_path", "import_web", "import_util", "import_undici", "path", "fs", "url", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_ws", "import_zod", "import_path", "path", "assert", "import_undici", "import_ws", "revivers", "reducers", "index", "value", "assert", "url", "reducers", "value", "stringifiedValue", "revivers", "url", "path", "LogLevel", "import_node_buffer", "import_node_assert", "assert", "url", "import_node_buffer", "import_zod", "import_undici", "BaseRequest", "init", "import_undici", "BaseResponse", "url", "init", "import_assert", "import_path", "path", "globToRegexp", "import_assert", "import_path", "import_zod", "assert", "path", "init", "assert", "NodeWebSocket", "fetch", "init", "url", "NodeWebSocket", "headers", "response", "baseFetch", "path", "import_promises", "fs", "net", "import_undici", "import_promises", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "import_fs", "import_promises", "import_path", "import_url", "import_zod", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_url", "url", "url", "path", "crypto", "fs", "fs", "import_assert", "import_fs", "import_promises", "import_path", "import_stream", "import_util", "import_undici", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "import_assert", "import_events", "import_workerd", "import_zod", "import_workerd_capnp", "CapnpConfig", "rl", "process", "workerdPath", "FORCE_COLOR", "childProcess", "assert", "import_promises", "import_zod", "fs", "import_assert", "import_fs", "import_path", "import_url", "import_zod", "module", "path", "rule", "assert", "contents", "import_assert", "import_crypto", "import_web", "import_util", "import_undici", "import_assert", "import_web", "import_fs", "import_path", "import_url", "import_zod", "import_assert", "assert", "contents", "fs", "module", "path", "url", "init", "assert", "import_web", "import_undici", "crypto", "url", "util", "assert", "key", "import_zod", "tls", "encoder", "fetch", "CORE_PLUGIN_NAME", "supportedCompatibilityDate", "path", "fs", "bindings", "moduleName", "bindingEntries", "name", "module", "invalidWrapped", "assert", "import_promises", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "fs", "import_node_assert", "import_zod", "url", "assert", "import_promises", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "import_assert", "import_promises", "import_path", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "rootPath", "fs", "path", "assert", "fs", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "import_promises", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "fs", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "PeriodType", "buildJsonBindings", "CORE_PLUGIN_NAME", "import_assert", "import_util", "path", "assert", "util", "net", "assert", "opts", "path", "util", "zlib", "Miniflare", "os", "crypto", "exitHook", "fs", "url", "http", "stoppable", "workerName", "init", "fetch"] +} diff --git a/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js b/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js new file mode 100644 index 0000000..63b0686 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js @@ -0,0 +1,19 @@ +// src/workers/cache/constants.ts +var CacheHeaders = { + NAMESPACE: "cf-cache-namespace", + STATUS: "cf-cache-status" +}; + +// src/workers/cache/cache-entry-noop.worker.ts +var cache_entry_noop_worker_default = { + async fetch(request) { + return request.method === "GET" ? new Response(null, { + status: 504, + headers: { [CacheHeaders.STATUS]: "MISS" } + }) : request.method === "PUT" ? (await request.body?.pipeTo(new WritableStream()), new Response(null, { status: 204 })) : request.method === "PURGE" ? new Response(null, { status: 404 }) : new Response(null, { status: 405 }); + } +}; +export { + cache_entry_noop_worker_default as default +}; +//# sourceMappingURL=cache-entry-noop.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js.map b/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js.map new file mode 100644 index 0000000..27d36f9 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/cache/constants.ts", "../../../../src/workers/cache/cache-entry-noop.worker.ts"], + "mappings": ";AAAO,IAAM,eAAe;AAAA,EAC3B,WAAW;AAAA,EACX,QAAQ;AACT;;;ACDA,IAAO,kCAAyB;AAAA,EAC/B,MAAM,MAAM,SAAS;AACpB,WAAI,QAAQ,WAAW,QACf,IAAI,SAAS,MAAM;AAAA,MACzB,QAAQ;AAAA,MACR,SAAS,EAAE,CAAC,aAAa,MAAM,GAAG,OAAO;AAAA,IAC1C,CAAC,IACS,QAAQ,WAAW,SAE7B,MAAM,QAAQ,MAAM,OAAO,IAAI,eAAe,CAAC,GACxC,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,KAC/B,QAAQ,WAAW,UACtB,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,IAElC,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AAAA,EAE3C;AACD;", + "names": [] +} diff --git a/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js b/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js new file mode 100644 index 0000000..de45782 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js @@ -0,0 +1,28 @@ +// src/workers/cache/cache-entry.worker.ts +import { SharedBindings } from "miniflare:shared"; + +// src/workers/cache/constants.ts +var CacheHeaders = { + NAMESPACE: "cf-cache-namespace", + STATUS: "cf-cache-status" +}, CacheBindings = { + MAYBE_JSON_CACHE_WARN_USAGE: "MINIFLARE_CACHE_WARN_USAGE" +}; + +// src/workers/cache/cache-entry.worker.ts +var cache_entry_worker_default = { + async fetch(request, env) { + let namespace = request.headers.get(CacheHeaders.NAMESPACE), name = namespace === null ? "default" : `named:${namespace}`, objectNamespace = env[SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT], id = objectNamespace.idFromName(name), stub = objectNamespace.get(id), cf = { + ...request.cf, + miniflare: { + name, + cacheWarnUsage: env[CacheBindings.MAYBE_JSON_CACHE_WARN_USAGE] + } + }; + return await stub.fetch(request, { cf }); + } +}; +export { + cache_entry_worker_default as default +}; +//# sourceMappingURL=cache-entry.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js.map b/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js.map new file mode 100644 index 0000000..da27240 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/cache/cache-entry.worker.ts", "../../../../src/workers/cache/constants.ts"], + "mappings": ";AAAA,SAAmC,sBAAsB;;;ACAlD,IAAM,eAAe;AAAA,EAC3B,WAAW;AAAA,EACX,QAAQ;AACT,GAEa,gBAAgB;AAAA,EAC5B,6BAA6B;AAC9B;;;ADCA,IAAO,6BAA8B;AAAA,EACpC,MAAM,MAAM,SAAS,KAAK;AACzB,QAAM,YAAY,QAAQ,QAAQ,IAAI,aAAa,SAAS,GACtD,OAAO,cAAc,OAAO,YAAY,SAAS,aAEjD,kBAAkB,IAAI,eAAe,+BAA+B,GACpE,KAAK,gBAAgB,WAAW,IAAI,GACpC,OAAO,gBAAgB,IAAI,EAAE,GAC7B,KAA+C;AAAA,MACpD,GAAG,QAAQ;AAAA,MACX,WAAW;AAAA,QACV;AAAA,QACA,gBAAgB,IAAI,cAAc,2BAA2B;AAAA,MAC9D;AAAA,IACD;AACA,WAAO,MAAM,KAAK,MAAM,SAAS,EAAE,GAAkC,CAAC;AAAA,EACvE;AACD;", + "names": [] +} diff --git a/node_modules/miniflare/dist/src/workers/cache/cache.worker.js b/node_modules/miniflare/dist/src/workers/cache/cache.worker.js new file mode 100644 index 0000000..2e26111 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache.worker.js @@ -0,0 +1,655 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from == "object" || typeof from == "function") + for (let key of __getOwnPropNames(from)) + !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target, + mod +)); +var __decorateClass = (decorators, target, key, kind) => { + for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--) + (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result); + return kind && result && __defProp(target, key, result), result; +}; + +// ../../node_modules/.pnpm/http-cache-semantics@4.1.0/node_modules/http-cache-semantics/index.js +var require_http_cache_semantics = __commonJS({ + "../../node_modules/.pnpm/http-cache-semantics@4.1.0/node_modules/http-cache-semantics/index.js"(exports, module) { + "use strict"; + var statusCodeCacheableByDefault = /* @__PURE__ */ new Set([ + 200, + 203, + 204, + 206, + 300, + 301, + 404, + 405, + 410, + 414, + 501 + ]), understoodStatuses = /* @__PURE__ */ new Set([ + 200, + 203, + 204, + 300, + 301, + 302, + 303, + 307, + 308, + 404, + 405, + 410, + 414, + 501 + ]), errorStatusCodes = /* @__PURE__ */ new Set([ + 500, + 502, + 503, + 504 + ]), hopByHopHeaders = { + date: !0, + // included, because we add Age update Date + connection: !0, + "keep-alive": !0, + "proxy-authenticate": !0, + "proxy-authorization": !0, + te: !0, + trailer: !0, + "transfer-encoding": !0, + upgrade: !0 + }, excludedFromRevalidationUpdate = { + // Since the old body is reused, it doesn't make sense to change properties of the body + "content-length": !0, + "content-encoding": !0, + "transfer-encoding": !0, + "content-range": !0 + }; + function toNumberOrZero(s) { + let n = parseInt(s, 10); + return isFinite(n) ? n : 0; + } + function isErrorResponse(response) { + return response ? errorStatusCodes.has(response.status) : !0; + } + function parseCacheControl(header) { + let cc = {}; + if (!header) + return cc; + let parts = header.trim().split(/\s*,\s*/); + for (let part of parts) { + let [k, v] = part.split(/\s*=\s*/, 2); + cc[k] = v === void 0 ? !0 : v.replace(/^"|"$/g, ""); + } + return cc; + } + function formatCacheControl(cc) { + let parts = []; + for (let k in cc) { + let v = cc[k]; + parts.push(v === !0 ? k : k + "=" + v); + } + if (parts.length) + return parts.join(", "); + } + module.exports = class { + constructor(req, res, { + shared, + cacheHeuristic, + immutableMinTimeToLive, + ignoreCargoCult, + _fromObject + } = {}) { + if (_fromObject) { + this._fromObject(_fromObject); + return; + } + if (!res || !res.headers) + throw Error("Response headers missing"); + this._assertRequestHasHeaders(req), this._responseTime = this.now(), this._isShared = shared !== !1, this._cacheHeuristic = cacheHeuristic !== void 0 ? cacheHeuristic : 0.1, this._immutableMinTtl = immutableMinTimeToLive !== void 0 ? immutableMinTimeToLive : 24 * 3600 * 1e3, this._status = "status" in res ? res.status : 200, this._resHeaders = res.headers, this._rescc = parseCacheControl(res.headers["cache-control"]), this._method = "method" in req ? req.method : "GET", this._url = req.url, this._host = req.headers.host, this._noAuthorization = !req.headers.authorization, this._reqHeaders = res.headers.vary ? req.headers : null, this._reqcc = parseCacheControl(req.headers["cache-control"]), ignoreCargoCult && "pre-check" in this._rescc && "post-check" in this._rescc && (delete this._rescc["pre-check"], delete this._rescc["post-check"], delete this._rescc["no-cache"], delete this._rescc["no-store"], delete this._rescc["must-revalidate"], this._resHeaders = Object.assign({}, this._resHeaders, { + "cache-control": formatCacheControl(this._rescc) + }), delete this._resHeaders.expires, delete this._resHeaders.pragma), res.headers["cache-control"] == null && /no-cache/.test(res.headers.pragma) && (this._rescc["no-cache"] = !0); + } + now() { + return Date.now(); + } + storable() { + return !!(!this._reqcc["no-store"] && // A cache MUST NOT store a response to any request, unless: + // The request method is understood by the cache and defined as being cacheable, and + (this._method === "GET" || this._method === "HEAD" || this._method === "POST" && this._hasExplicitExpiration()) && // the response status code is understood by the cache, and + understoodStatuses.has(this._status) && // the "no-store" cache directive does not appear in request or response header fields, and + !this._rescc["no-store"] && // the "private" response directive does not appear in the response, if the cache is shared, and + (!this._isShared || !this._rescc.private) && // the Authorization header field does not appear in the request, if the cache is shared, + (!this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) && // the response either: + // contains an Expires header field, or + (this._resHeaders.expires || // contains a max-age response directive, or + // contains a s-maxage response directive and the cache is shared, or + // contains a public response directive. + this._rescc["max-age"] || this._isShared && this._rescc["s-maxage"] || this._rescc.public || // has a status code that is defined as cacheable by default + statusCodeCacheableByDefault.has(this._status))); + } + _hasExplicitExpiration() { + return this._isShared && this._rescc["s-maxage"] || this._rescc["max-age"] || this._resHeaders.expires; + } + _assertRequestHasHeaders(req) { + if (!req || !req.headers) + throw Error("Request headers missing"); + } + satisfiesWithoutRevalidation(req) { + this._assertRequestHasHeaders(req); + let requestCC = parseCacheControl(req.headers["cache-control"]); + return requestCC["no-cache"] || /no-cache/.test(req.headers.pragma) || requestCC["max-age"] && this.age() > requestCC["max-age"] || requestCC["min-fresh"] && this.timeToLive() < 1e3 * requestCC["min-fresh"] || this.stale() && !(requestCC["max-stale"] && !this._rescc["must-revalidate"] && (requestCC["max-stale"] === !0 || requestCC["max-stale"] > this.age() - this.maxAge())) ? !1 : this._requestMatches(req, !1); + } + _requestMatches(req, allowHeadMethod) { + return (!this._url || this._url === req.url) && this._host === req.headers.host && // the request method associated with the stored response allows it to be used for the presented request, and + (!req.method || this._method === req.method || allowHeadMethod && req.method === "HEAD") && // selecting header fields nominated by the stored response (if any) match those presented, and + this._varyMatches(req); + } + _allowsStoringAuthenticated() { + return this._rescc["must-revalidate"] || this._rescc.public || this._rescc["s-maxage"]; + } + _varyMatches(req) { + if (!this._resHeaders.vary) + return !0; + if (this._resHeaders.vary === "*") + return !1; + let fields = this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/); + for (let name of fields) + if (req.headers[name] !== this._reqHeaders[name]) + return !1; + return !0; + } + _copyWithoutHopByHopHeaders(inHeaders) { + let headers = {}; + for (let name in inHeaders) + hopByHopHeaders[name] || (headers[name] = inHeaders[name]); + if (inHeaders.connection) { + let tokens = inHeaders.connection.trim().split(/\s*,\s*/); + for (let name of tokens) + delete headers[name]; + } + if (headers.warning) { + let warnings = headers.warning.split(/,/).filter((warning) => !/^\s*1[0-9][0-9]/.test(warning)); + warnings.length ? headers.warning = warnings.join(",").trim() : delete headers.warning; + } + return headers; + } + responseHeaders() { + let headers = this._copyWithoutHopByHopHeaders(this._resHeaders), age = this.age(); + return age > 3600 * 24 && !this._hasExplicitExpiration() && this.maxAge() > 3600 * 24 && (headers.warning = (headers.warning ? `${headers.warning}, ` : "") + '113 - "rfc7234 5.5.4"'), headers.age = `${Math.round(age)}`, headers.date = new Date(this.now()).toUTCString(), headers; + } + /** + * Value of the Date response header or current time if Date was invalid + * @return timestamp + */ + date() { + let serverDate = Date.parse(this._resHeaders.date); + return isFinite(serverDate) ? serverDate : this._responseTime; + } + /** + * Value of the Age header, in seconds, updated for the current time. + * May be fractional. + * + * @return Number + */ + age() { + let age = this._ageValue(), residentTime = (this.now() - this._responseTime) / 1e3; + return age + residentTime; + } + _ageValue() { + return toNumberOrZero(this._resHeaders.age); + } + /** + * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. + * + * For an up-to-date value, see `timeToLive()`. + * + * @return Number + */ + maxAge() { + if (!this.storable() || this._rescc["no-cache"] || this._isShared && this._resHeaders["set-cookie"] && !this._rescc.public && !this._rescc.immutable || this._resHeaders.vary === "*") + return 0; + if (this._isShared) { + if (this._rescc["proxy-revalidate"]) + return 0; + if (this._rescc["s-maxage"]) + return toNumberOrZero(this._rescc["s-maxage"]); + } + if (this._rescc["max-age"]) + return toNumberOrZero(this._rescc["max-age"]); + let defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0, serverDate = this.date(); + if (this._resHeaders.expires) { + let expires = Date.parse(this._resHeaders.expires); + return Number.isNaN(expires) || expires < serverDate ? 0 : Math.max(defaultMinTtl, (expires - serverDate) / 1e3); + } + if (this._resHeaders["last-modified"]) { + let lastModified = Date.parse(this._resHeaders["last-modified"]); + if (isFinite(lastModified) && serverDate > lastModified) + return Math.max( + defaultMinTtl, + (serverDate - lastModified) / 1e3 * this._cacheHeuristic + ); + } + return defaultMinTtl; + } + timeToLive() { + let age = this.maxAge() - this.age(), staleIfErrorAge = age + toNumberOrZero(this._rescc["stale-if-error"]), staleWhileRevalidateAge = age + toNumberOrZero(this._rescc["stale-while-revalidate"]); + return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1e3; + } + stale() { + return this.maxAge() <= this.age(); + } + _useStaleIfError() { + return this.maxAge() + toNumberOrZero(this._rescc["stale-if-error"]) > this.age(); + } + useStaleWhileRevalidate() { + return this.maxAge() + toNumberOrZero(this._rescc["stale-while-revalidate"]) > this.age(); + } + static fromObject(obj) { + return new this(void 0, void 0, { _fromObject: obj }); + } + _fromObject(obj) { + if (this._responseTime) + throw Error("Reinitialized"); + if (!obj || obj.v !== 1) + throw Error("Invalid serialization"); + this._responseTime = obj.t, this._isShared = obj.sh, this._cacheHeuristic = obj.ch, this._immutableMinTtl = obj.imm !== void 0 ? obj.imm : 24 * 3600 * 1e3, this._status = obj.st, this._resHeaders = obj.resh, this._rescc = obj.rescc, this._method = obj.m, this._url = obj.u, this._host = obj.h, this._noAuthorization = obj.a, this._reqHeaders = obj.reqh, this._reqcc = obj.reqcc; + } + toObject() { + return { + v: 1, + t: this._responseTime, + sh: this._isShared, + ch: this._cacheHeuristic, + imm: this._immutableMinTtl, + st: this._status, + resh: this._resHeaders, + rescc: this._rescc, + m: this._method, + u: this._url, + h: this._host, + a: this._noAuthorization, + reqh: this._reqHeaders, + reqcc: this._reqcc + }; + } + /** + * Headers for sending to the origin server to revalidate stale response. + * Allows server to return 304 to allow reuse of the previous response. + * + * Hop by hop headers are always stripped. + * Revalidation headers may be added or removed, depending on request. + */ + revalidationHeaders(incomingReq) { + this._assertRequestHasHeaders(incomingReq); + let headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); + if (delete headers["if-range"], !this._requestMatches(incomingReq, !0) || !this.storable()) + return delete headers["if-none-match"], delete headers["if-modified-since"], headers; + if (this._resHeaders.etag && (headers["if-none-match"] = headers["if-none-match"] ? `${headers["if-none-match"]}, ${this._resHeaders.etag}` : this._resHeaders.etag), headers["accept-ranges"] || headers["if-match"] || headers["if-unmodified-since"] || this._method && this._method != "GET") { + if (delete headers["if-modified-since"], headers["if-none-match"]) { + let etags = headers["if-none-match"].split(/,/).filter((etag) => !/^\s*W\//.test(etag)); + etags.length ? headers["if-none-match"] = etags.join(",").trim() : delete headers["if-none-match"]; + } + } else + this._resHeaders["last-modified"] && !headers["if-modified-since"] && (headers["if-modified-since"] = this._resHeaders["last-modified"]); + return headers; + } + /** + * Creates new CachePolicy with information combined from the previews response, + * and the new revalidation response. + * + * Returns {policy, modified} where modified is a boolean indicating + * whether the response body has been modified, and old cached body can't be used. + * + * @return {Object} {policy: CachePolicy, modified: Boolean} + */ + revalidatedPolicy(request, response) { + if (this._assertRequestHasHeaders(request), this._useStaleIfError() && isErrorResponse(response)) + return { + modified: !1, + matches: !1, + policy: this + }; + if (!response || !response.headers) + throw Error("Response headers missing"); + let matches = !1; + if (response.status !== void 0 && response.status != 304 ? matches = !1 : response.headers.etag && !/^\s*W\//.test(response.headers.etag) ? matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//, "") === response.headers.etag : this._resHeaders.etag && response.headers.etag ? matches = this._resHeaders.etag.replace(/^\s*W\//, "") === response.headers.etag.replace(/^\s*W\//, "") : this._resHeaders["last-modified"] ? matches = this._resHeaders["last-modified"] === response.headers["last-modified"] : !this._resHeaders.etag && !this._resHeaders["last-modified"] && !response.headers.etag && !response.headers["last-modified"] && (matches = !0), !matches) + return { + policy: new this.constructor(request, response), + // Client receiving 304 without body, even if it's invalid/mismatched has no option + // but to reuse a cached body. We don't have a good way to tell clients to do + // error recovery in such case. + modified: response.status != 304, + matches: !1 + }; + let headers = {}; + for (let k in this._resHeaders) + headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k]; + let newResponse = Object.assign({}, response, { + status: this._status, + method: this._method, + headers + }); + return { + policy: new this.constructor(request, newResponse, { + shared: this._isShared, + cacheHeuristic: this._cacheHeuristic, + immutableMinTimeToLive: this._immutableMinTtl + }), + modified: !1, + matches: !0 + }; + } + }; + } +}); + +// src/workers/cache/cache.worker.ts +var import_http_cache_semantics = __toESM(require_http_cache_semantics()); +import assert from "node:assert"; +import { Buffer as Buffer2 } from "node:buffer"; +import { + DeferredPromise, + GET, + KeyValueStorage, + LogLevel, + MiniflareDurableObject, + PURGE, + PUT, + parseRanges +} from "miniflare:shared"; + +// src/workers/kv/constants.ts +import { testRegExps } from "miniflare:shared"; +var KVLimits = { + MIN_CACHE_TTL: 60, + MAX_LIST_KEYS: 1e3, + MAX_KEY_SIZE: 512, + MAX_VALUE_SIZE: 25 * 1024 * 1024, + MAX_VALUE_SIZE_TEST: 1024, + MAX_METADATA_SIZE: 1024 +}; +var SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/"; +function isSitesRequest(request) { + return new URL(request.url).pathname.startsWith(`/${SITES_NO_CACHE_PREFIX}`); +} + +// src/workers/cache/errors.worker.ts +import { HttpError } from "miniflare:shared"; + +// src/workers/cache/constants.ts +var CacheHeaders = { + NAMESPACE: "cf-cache-namespace", + STATUS: "cf-cache-status" +}; + +// src/workers/cache/errors.worker.ts +var CacheError = class extends HttpError { + constructor(code, message, headers = []) { + super(code, message); + this.headers = headers; + } + toResponse() { + return new Response(null, { + status: this.code, + headers: this.headers + }); + } + context(info) { + return this.message += ` (${info})`, this; + } +}, StorageFailure = class extends CacheError { + constructor() { + super(413, "Cache storage failed"); + } +}, PurgeFailure = class extends CacheError { + constructor() { + super(404, "Couldn't find asset to purge"); + } +}, CacheMiss = class extends CacheError { + constructor() { + super( + // workerd ignores this, but it's the correct status code + 504, + "Asset not found in cache", + [[CacheHeaders.STATUS, "MISS"]] + ); + } +}, RangeNotSatisfiable = class extends CacheError { + constructor(size) { + super(416, "Range not satisfiable", [ + ["Content-Range", `bytes */${size}`], + [CacheHeaders.STATUS, "HIT"] + ]); + } +}; + +// src/workers/cache/cache.worker.ts +function getCacheKey(req) { + return req.cf?.cacheKey ? String(req.cf?.cacheKey) : req.url; +} +function getExpiration(timers, req, res) { + let reqHeaders = normaliseHeaders(req.headers); + delete reqHeaders["cache-control"]; + let resHeaders = normaliseHeaders(res.headers); + resHeaders["cache-control"]?.toLowerCase().includes("private=set-cookie") && (resHeaders["cache-control"] = resHeaders["cache-control"]?.toLowerCase().replace(/private=set-cookie;?/i, ""), delete resHeaders["set-cookie"]); + let cacheReq = { + url: req.url, + // If a request gets to the Cache service, it's method will be GET. See README.md for details + method: "GET", + headers: reqHeaders + }, cacheRes = { + status: res.status, + headers: resHeaders + }, originalNow = import_http_cache_semantics.default.prototype.now; + import_http_cache_semantics.default.prototype.now = timers.now; + try { + let policy = new import_http_cache_semantics.default(cacheReq, cacheRes, { shared: !0 }); + return { + // Check if the request & response is cacheable + storable: policy.storable() && !("set-cookie" in resHeaders), + expiration: policy.timeToLive(), + // Cache Policy Headers is typed as [header: string]: string | string[] | undefined + // It's safe to ignore the undefined here, which is what casting to HeadersInit does + headers: policy.responseHeaders() + }; + } finally { + import_http_cache_semantics.default.prototype.now = originalNow; + } +} +function normaliseHeaders(headers) { + let result = {}; + for (let [key, value] of headers) + result[key.toLowerCase()] = value; + return result; +} +var etagRegexp = /^(W\/)?"(.+)"$/; +function parseETag(value) { + return etagRegexp.exec(value.trim())?.[2] ?? void 0; +} +var utcDateRegexp = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d\d (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d\d\d\d \d\d:\d\d:\d\d GMT$/; +function parseUTCDate(value) { + return utcDateRegexp.test(value) ? Date.parse(value) : NaN; +} +function getMatchResponse(reqHeaders, res) { + let reqIfNoneMatchHeader = reqHeaders.get("If-None-Match"), resETagHeader = res.headers.get("ETag"); + if (reqIfNoneMatchHeader !== null && resETagHeader !== null) { + let resETag = parseETag(resETagHeader); + if (resETag !== void 0) { + if (reqIfNoneMatchHeader.trim() === "*") + return new Response(null, { status: 304, headers: res.headers }); + for (let reqIfNoneMatch of reqIfNoneMatchHeader.split(",")) + if (resETag === parseETag(reqIfNoneMatch)) + return new Response(null, { status: 304, headers: res.headers }); + } + } + let reqIfModifiedSinceHeader = reqHeaders.get("If-Modified-Since"), resLastModifiedHeader = res.headers.get("Last-Modified"); + if (reqIfModifiedSinceHeader !== null && resLastModifiedHeader !== null) { + let reqIfModifiedSince = parseUTCDate(reqIfModifiedSinceHeader); + if (parseUTCDate(resLastModifiedHeader) <= reqIfModifiedSince) + return new Response(null, { status: 304, headers: res.headers }); + } + if (res.ranges.length > 0) + if (res.status = 206, res.ranges.length > 1) + assert(!(res.body instanceof ReadableStream)), res.headers.set("Content-Type", res.body.multipartContentType); + else { + let { start, end } = res.ranges[0]; + res.headers.set( + "Content-Range", + `bytes ${start}-${end}/${res.totalSize}` + ), res.headers.set("Content-Length", `${end - start + 1}`); + } + return res.body instanceof ReadableStream || (res.body = res.body.body), new Response(res.body, { status: res.status, headers: res.headers }); +} +var CR = "\r".charCodeAt(0), LF = ` +`.charCodeAt(0), STATUS_REGEXP = /^HTTP\/\d(?:\.\d)? (?\d+) (?.*)$/; +async function parseHttpResponse(stream) { + let buffer = Buffer2.alloc(0), blankLineIndex = -1; + for await (let chunk of stream.values({ preventCancel: !0 })) + if (buffer = Buffer2.concat([buffer, chunk]), blankLineIndex = buffer.findIndex( + (_value, index) => buffer[index] === CR && buffer[index + 1] === LF && buffer[index + 2] === CR && buffer[index + 3] === LF + ), blankLineIndex !== -1) + break; + assert(blankLineIndex !== -1, "Expected to find blank line in HTTP message"); + let rawStatusHeaders = buffer.subarray(0, blankLineIndex).toString(), [rawStatus, ...rawHeaders] = rawStatusHeaders.split(`\r +`), statusMatch = rawStatus.match(STATUS_REGEXP); + assert( + statusMatch?.groups != null, + `Expected first line ${JSON.stringify(rawStatus)} to be HTTP status line` + ); + let { rawStatusCode, statusText } = statusMatch.groups, statusCode = parseInt(rawStatusCode), headers = rawHeaders.map((rawHeader) => { + let index = rawHeader.indexOf(":"); + return [ + rawHeader.substring(0, index), + rawHeader.substring(index + 1).trim() + ]; + }), prefix = buffer.subarray( + blankLineIndex + 4 + /* "\r\n\r\n" */ + ), { readable, writable } = new IdentityTransformStream(), writer = writable.getWriter(); + return writer.write(prefix).then(() => (writer.releaseLock(), stream.pipeTo(writable))).catch((e) => console.error("Error writing HTTP body:", e)), new Response(readable, { status: statusCode, statusText, headers }); +} +var SizingStream = class extends TransformStream { + size; + constructor() { + let sizePromise = new DeferredPromise(), size = 0; + super({ + transform(chunk, controller) { + size += chunk.byteLength, controller.enqueue(chunk); + }, + flush() { + sizePromise.resolve(size); + } + }), this.size = sizePromise; + } +}, CacheObject = class extends MiniflareDurableObject { + #warnedUsage = !1; + async #maybeWarnUsage(request) { + !this.#warnedUsage && request.cf?.miniflare?.cacheWarnUsage === !0 && (this.#warnedUsage = !0, await this.logWithLevel( + LogLevel.WARN, + "Cache operations will have no impact if you deploy to a workers.dev subdomain!" + )); + } + #storage; + get storage() { + return this.#storage ??= new KeyValueStorage(this); + } + match = async (req) => { + await this.#maybeWarnUsage(req); + let cacheKey = getCacheKey(req); + if (isSitesRequest(req)) + throw new CacheMiss(); + let resHeaders, resRanges, cached = await this.storage.get(cacheKey, ({ size, headers }) => { + resHeaders = new Headers(headers); + let contentType = resHeaders.get("Content-Type"), rangeHeader = req.headers.get("Range"); + if (rangeHeader !== null && (resRanges = parseRanges(rangeHeader, size), resRanges === void 0)) + throw new RangeNotSatisfiable(size); + return { + ranges: resRanges, + contentLength: size, + contentType: contentType ?? void 0 + }; + }); + if (cached?.metadata === void 0) + throw new CacheMiss(); + return assert(resHeaders !== void 0), resHeaders.set("CF-Cache-Status", "HIT"), resRanges ??= [], getMatchResponse(req.headers, { + status: cached.metadata.status, + headers: resHeaders, + ranges: resRanges, + body: cached.value, + totalSize: cached.metadata.size + }); + }; + put = async (req) => { + await this.#maybeWarnUsage(req); + let cacheKey = getCacheKey(req); + if (isSitesRequest(req)) + throw new CacheMiss(); + assert(req.body !== null); + let res = await parseHttpResponse(req.body), body = res.body; + assert(body !== null); + let { storable, expiration, headers } = getExpiration( + this.timers, + req, + res + ); + if (!storable) { + try { + await body.pipeTo(new WritableStream()); + } catch { + } + throw new StorageFailure(); + } + let contentLength = parseInt(res.headers.get("Content-Length")), sizePromise; + if (Number.isNaN(contentLength)) { + let stream = new SizingStream(); + body = body.pipeThrough(stream), sizePromise = stream.size; + } else + sizePromise = Promise.resolve(contentLength); + let metadata = sizePromise.then((size) => ({ + headers: Object.entries(headers), + status: res.status, + size + })); + return await this.storage.put({ + key: cacheKey, + value: body, + expiration: this.timers.now() + expiration, + metadata + }), new Response(null, { status: 204 }); + }; + delete = async (req) => { + await this.#maybeWarnUsage(req); + let cacheKey = getCacheKey(req); + if (!await this.storage.delete(cacheKey)) + throw new PurgeFailure(); + return new Response(null); + }; +}; +__decorateClass([ + GET() +], CacheObject.prototype, "match", 2), __decorateClass([ + PUT() +], CacheObject.prototype, "put", 2), __decorateClass([ + PURGE() +], CacheObject.prototype, "delete", 2); +export { + CacheObject, + parseHttpResponse +}; +//# sourceMappingURL=cache.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/cache/cache.worker.js.map b/node_modules/miniflare/dist/src/workers/cache/cache.worker.js.map new file mode 100644 index 0000000..ee4c681 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../../../node_modules/.pnpm/http-cache-semantics@4.1.0/node_modules/http-cache-semantics/index.js", "../../../../src/workers/cache/cache.worker.ts", "../../../../src/workers/kv/constants.ts", "../../../../src/workers/cache/errors.worker.ts", "../../../../src/workers/cache/constants.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,+BAA+B,oBAAI,IAAI;AAAA,MACzC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACJ,CAAC,GAGK,qBAAqB,oBAAI,IAAI;AAAA,MAC/B;AAAA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P,YAAY,KAAK,OAAO,IAAI,IAAI;AAAA,MAChC;AAAA,IACD,CAAC,GACM,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC1C;AAAA,EAGA,SAA4B,OAAO,QAAQ;AAC1C,UAAM,KAAK,gBAAgB,GAAG;AAC9B,QAAM,WAAW,YAAY,GAAG;AAIhC,QAAI,CAFY,MAAM,KAAK,QAAQ,OAAO,QAAQ;AAEpC,YAAM,IAAI,aAAa;AACrC,WAAO,IAAI,SAAS,IAAI;AAAA,EACzB;AACD;AA/GC;AAAA,EADC,IAAI;AAAA,GAlBO,YAmBZ,wBA8CA;AAAA,EADC,IAAI;AAAA,GAhEO,YAiEZ,sBAwDA;AAAA,EADC,MAAM;AAAA,GAxHK,YAyHZ;", + "names": ["Buffer", "CachePolicy", "Buffer"] +} diff --git a/node_modules/miniflare/dist/src/workers/core/entry.worker.js b/node_modules/miniflare/dist/src/workers/core/entry.worker.js new file mode 100644 index 0000000..8cca530 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/core/entry.worker.js @@ -0,0 +1,977 @@ +// ../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs +var FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY = !0; +typeof process < "u" && ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}, isTTY = process.stdout && process.stdout.isTTY); +var $ = { + enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY) +}; +function init(x, y) { + let rgx = new RegExp(`\\x1b\\[${y}m`, "g"), open = `\x1B[${x}m`, close = `\x1B[${y}m`; + return function(txt) { + return !$.enabled || txt == null ? txt : open + (~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close; + }; +} +var reset = init(0, 0), bold = init(1, 22), dim = init(2, 22), italic = init(3, 23), underline = init(4, 24), inverse = init(7, 27), hidden = init(8, 28), strikethrough = init(9, 29), black = init(30, 39), red = init(31, 39), green = init(32, 39), yellow = init(33, 39), blue = init(34, 39), magenta = init(35, 39), cyan = init(36, 39), white = init(37, 39), gray = init(90, 39), grey = init(90, 39), bgBlack = init(40, 49), bgRed = init(41, 49), bgGreen = init(42, 49), bgYellow = init(43, 49), bgBlue = init(44, 49), bgMagenta = init(45, 49), bgCyan = init(46, 49), bgWhite = init(47, 49); + +// src/workers/core/entry.worker.ts +import { HttpError, LogLevel, SharedHeaders } from "miniflare:shared"; + +// src/workers/core/constants.ts +var CoreHeaders = { + CUSTOM_SERVICE: "MF-Custom-Service", + ORIGINAL_URL: "MF-Original-URL", + PROXY_SHARED_SECRET: "MF-Proxy-Shared-Secret", + DISABLE_PRETTY_ERROR: "MF-Disable-Pretty-Error", + ERROR_STACK: "MF-Experimental-Error-Stack", + ROUTE_OVERRIDE: "MF-Route-Override", + CF_BLOB: "MF-CF-Blob", + // API Proxy + OP_SECRET: "MF-Op-Secret", + OP: "MF-Op", + OP_TARGET: "MF-Op-Target", + OP_KEY: "MF-Op-Key", + OP_SYNC: "MF-Op-Sync", + OP_STRINGIFIED_SIZE: "MF-Op-Stringified-Size", + OP_RESULT_TYPE: "MF-Op-Result-Type" +}, CoreBindings = { + SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK", + SERVICE_USER_ROUTE_PREFIX: "MINIFLARE_USER_ROUTE_", + SERVICE_USER_FALLBACK: "MINIFLARE_USER_FALLBACK", + TEXT_CUSTOM_SERVICE: "MINIFLARE_CUSTOM_SERVICE", + TEXT_UPSTREAM_URL: "MINIFLARE_UPSTREAM_URL", + JSON_CF_BLOB: "CF_BLOB", + JSON_ROUTES: "MINIFLARE_ROUTES", + JSON_LOG_LEVEL: "MINIFLARE_LOG_LEVEL", + DATA_LIVE_RELOAD_SCRIPT: "MINIFLARE_LIVE_RELOAD_SCRIPT", + DURABLE_OBJECT_NAMESPACE_PROXY: "MINIFLARE_PROXY", + DATA_PROXY_SECRET: "MINIFLARE_PROXY_SECRET", + DATA_PROXY_SHARED_SECRET: "MINIFLARE_PROXY_SHARED_SECRET" +}, ProxyOps = { + // Get the target or a property of the target + GET: "GET", + // Get the descriptor for a property of the target + GET_OWN_DESCRIPTOR: "GET_OWN_DESCRIPTOR", + // Get the target's own property names + GET_OWN_KEYS: "GET_OWN_KEYS", + // Call a method on the target + CALL: "CALL", + // Remove the strong reference to the target on the "heap", allowing it to be + // garbage collected + FREE: "FREE" +}, ProxyAddresses = { + GLOBAL: 0, + // globalThis + ENV: 1, + // env + USER_START: 2 +}; +function isFetcherFetch(targetName, key) { + return (targetName === "Fetcher" || targetName === "DurableObject" || targetName === "WorkerRpc") && key === "fetch"; +} +function isR2ObjectWriteHttpMetadata(targetName, key) { + return (targetName === "HeadResult" || targetName === "GetResult") && key === "writeHttpMetadata"; +} + +// src/workers/core/http.ts +var STATUS_CODES = { + 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" +}; + +// src/workers/core/routing.ts +function matchRoutes(routes, url) { + for (let route of routes) { + if (route.protocol && route.protocol !== url.protocol) + continue; + if (route.allowHostnamePrefix) { + if (!url.hostname.endsWith(route.hostname)) + continue; + } else if (url.hostname !== route.hostname) + continue; + let path = url.pathname + url.search; + if (route.allowPathSuffix) { + if (!path.startsWith(route.path)) + continue; + } else if (path !== route.path) + continue; + return route.target; + } + return null; +} + +// src/workers/core/proxy.worker.ts +import assert2 from "node:assert"; +import { Buffer as Buffer2 } from "node:buffer"; + +// ../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/utils.js +var DevalueError = class extends Error { + /** + * @param {string} message + * @param {string[]} keys + */ + constructor(message, keys) { + super(message), this.name = "DevalueError", this.path = keys.join(""); + } +}; +function is_primitive(thing) { + return Object(thing) !== thing; +} +var object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames( + Object.prototype +).sort().join("\0"); +function is_plain_object(thing) { + let proto = Object.getPrototypeOf(thing); + return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names; +} +function get_type(thing) { + return Object.prototype.toString.call(thing).slice(8, -1); +} +function get_escaped_char(char) { + switch (char) { + case '"': + return '\\"'; + case "<": + return "\\u003C"; + case "\\": + return "\\\\"; + case ` +`: + return "\\n"; + case "\r": + return "\\r"; + case " ": + return "\\t"; + case "\b": + return "\\b"; + case "\f": + return "\\f"; + case "\u2028": + return "\\u2028"; + case "\u2029": + return "\\u2029"; + default: + return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : ""; + } +} +function stringify_string(str) { + let result = "", last_pos = 0, len = str.length; + for (let i = 0; i < len; i += 1) { + let char = str[i], replacement = get_escaped_char(char); + replacement && (result += str.slice(last_pos, i) + replacement, last_pos = i + 1); + } + return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`; +} + +// ../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/parse.js +function parse(serialized, revivers) { + return unflatten(JSON.parse(serialized), revivers); +} +function unflatten(parsed, revivers) { + if (typeof parsed == "number") + return hydrate(parsed, !0); + if (!Array.isArray(parsed) || parsed.length === 0) + throw new Error("Invalid input"); + let values = ( + /** @type {any[]} */ + parsed + ), hydrated = Array(values.length); + function hydrate(index, standalone = !1) { + if (index === -1) + return; + if (index === -3) + return NaN; + if (index === -4) + return 1 / 0; + if (index === -5) + return -1 / 0; + if (index === -6) + return -0; + if (standalone) + throw new Error("Invalid input"); + if (index in hydrated) + return hydrated[index]; + let value = values[index]; + if (!value || typeof value != "object") + hydrated[index] = value; + else if (Array.isArray(value)) + if (typeof value[0] == "string") { + let type = value[0], reviver = revivers?.[type]; + if (reviver) + return hydrated[index] = reviver(hydrate(value[1])); + switch (type) { + case "Date": + hydrated[index] = new Date(value[1]); + break; + case "Set": + let set = /* @__PURE__ */ new Set(); + hydrated[index] = set; + for (let i = 1; i < value.length; i += 1) + set.add(hydrate(value[i])); + break; + case "Map": + let map = /* @__PURE__ */ new Map(); + hydrated[index] = map; + for (let i = 1; i < value.length; i += 2) + map.set(hydrate(value[i]), hydrate(value[i + 1])); + break; + case "RegExp": + hydrated[index] = new RegExp(value[1], value[2]); + break; + case "Object": + hydrated[index] = Object(value[1]); + break; + case "BigInt": + hydrated[index] = BigInt(value[1]); + break; + case "null": + let obj = /* @__PURE__ */ Object.create(null); + hydrated[index] = obj; + for (let i = 1; i < value.length; i += 2) + obj[value[i]] = hydrate(value[i + 1]); + break; + default: + throw new Error(`Unknown type ${type}`); + } + } else { + let array = new Array(value.length); + hydrated[index] = array; + for (let i = 0; i < value.length; i += 1) { + let n = value[i]; + n !== -2 && (array[i] = hydrate(n)); + } + } + else { + let object = {}; + hydrated[index] = object; + for (let key in value) { + let n = value[key]; + object[key] = hydrate(n); + } + } + return hydrated[index]; + } + return hydrate(0); +} + +// ../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/stringify.js +function stringify(value, reducers) { + let stringified = [], indexes = /* @__PURE__ */ new Map(), custom = []; + for (let key in reducers) + custom.push({ key, fn: reducers[key] }); + let keys = [], p = 0; + function flatten(thing) { + if (typeof thing == "function") + throw new DevalueError("Cannot stringify a function", keys); + if (indexes.has(thing)) + return indexes.get(thing); + if (thing === void 0) + return -1; + if (Number.isNaN(thing)) + return -3; + if (thing === 1 / 0) + return -4; + if (thing === -1 / 0) + return -5; + if (thing === 0 && 1 / thing < 0) + return -6; + let index2 = p++; + indexes.set(thing, index2); + for (let { key, fn } of custom) { + let value2 = fn(thing); + if (value2) + return stringified[index2] = `["${key}",${flatten(value2)}]`, index2; + } + let str = ""; + if (is_primitive(thing)) + str = stringify_primitive(thing); + else + switch (get_type(thing)) { + case "Number": + case "String": + case "Boolean": + str = `["Object",${stringify_primitive(thing)}]`; + break; + case "BigInt": + str = `["BigInt",${thing}]`; + break; + case "Date": + str = `["Date","${thing.toISOString()}"]`; + break; + case "RegExp": + let { source, flags } = thing; + str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`; + break; + case "Array": + str = "["; + for (let i = 0; i < thing.length; i += 1) + i > 0 && (str += ","), i in thing ? (keys.push(`[${i}]`), str += flatten(thing[i]), keys.pop()) : str += -2; + str += "]"; + break; + case "Set": + str = '["Set"'; + for (let value2 of thing) + str += `,${flatten(value2)}`; + str += "]"; + break; + case "Map": + str = '["Map"'; + for (let [key, value2] of thing) + keys.push( + `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})` + ), str += `,${flatten(key)},${flatten(value2)}`; + str += "]"; + break; + default: + if (!is_plain_object(thing)) + throw new DevalueError( + "Cannot stringify arbitrary non-POJOs", + keys + ); + if (Object.getOwnPropertySymbols(thing).length > 0) + throw new DevalueError( + "Cannot stringify POJOs with symbolic keys", + keys + ); + if (Object.getPrototypeOf(thing) === null) { + str = '["null"'; + for (let key in thing) + keys.push(`.${key}`), str += `,${stringify_string(key)},${flatten(thing[key])}`, keys.pop(); + str += "]"; + } else { + str = "{"; + let started = !1; + for (let key in thing) + started && (str += ","), started = !0, keys.push(`.${key}`), str += `${stringify_string(key)}:${flatten(thing[key])}`, keys.pop(); + str += "}"; + } + } + return stringified[index2] = str, index2; + } + let index = flatten(value); + return index < 0 ? `${index}` : `[${stringified.join(",")}]`; +} +function stringify_primitive(thing) { + let type = typeof thing; + return type === "string" ? stringify_string(thing) : thing instanceof String ? stringify_string(thing.toString()) : thing === void 0 ? (-1).toString() : thing === 0 && 1 / thing < 0 ? (-6).toString() : type === "bigint" ? `["BigInt","${thing}"]` : String(thing); +} + +// src/workers/core/proxy.worker.ts +import { readPrefix, reduceError } from "miniflare:shared"; + +// src/workers/core/devalue.ts +import assert from "node:assert"; +import { Buffer } from "node:buffer"; +var ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS = [ + DataView, + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + BigInt64Array, + BigUint64Array +], ALLOWED_ERROR_CONSTRUCTORS = [ + EvalError, + RangeError, + ReferenceError, + SyntaxError, + TypeError, + URIError, + Error + // `Error` last so more specific error subclasses preferred +], structuredSerializableReducers = { + ArrayBuffer(value) { + if (value instanceof ArrayBuffer) + return [Buffer.from(value).toString("base64")]; + }, + ArrayBufferView(value) { + if (ArrayBuffer.isView(value)) + return [ + value.constructor.name, + value.buffer, + value.byteOffset, + value.byteLength + ]; + }, + Error(value) { + for (let ctor of ALLOWED_ERROR_CONSTRUCTORS) + if (value instanceof ctor && value.name === ctor.name) + return [value.name, value.message, value.stack, value.cause]; + if (value instanceof Error) + return ["Error", value.message, value.stack, value.cause]; + } +}, structuredSerializableRevivers = { + ArrayBuffer(value) { + assert(Array.isArray(value)); + let [encoded] = value; + assert(typeof encoded == "string"); + let view = Buffer.from(encoded, "base64"); + return view.buffer.slice( + view.byteOffset, + view.byteOffset + view.byteLength + ); + }, + ArrayBufferView(value) { + assert(Array.isArray(value)); + let [name, buffer, byteOffset, byteLength] = value; + assert(typeof name == "string"), assert(buffer instanceof ArrayBuffer), assert(typeof byteOffset == "number"), assert(typeof byteLength == "number"); + let ctor = globalThis[name]; + assert(ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS.includes(ctor)); + let length = byteLength; + return "BYTES_PER_ELEMENT" in ctor && (length /= ctor.BYTES_PER_ELEMENT), new ctor(buffer, byteOffset, length); + }, + Error(value) { + assert(Array.isArray(value)); + let [name, message, stack, cause] = value; + assert(typeof name == "string"), assert(typeof message == "string"), assert(stack === void 0 || typeof stack == "string"); + let ctor = globalThis[name]; + assert(ALLOWED_ERROR_CONSTRUCTORS.includes(ctor)); + let error = new ctor(message, { cause }); + return error.stack = stack, error; + } +}; +function createHTTPReducers(impl) { + return { + Headers(val) { + if (val instanceof impl.Headers) + return Object.fromEntries(val); + }, + Request(val) { + if (val instanceof impl.Request) + return [val.method, val.url, val.headers, val.cf, val.body]; + }, + Response(val) { + if (val instanceof impl.Response) + return [val.status, val.statusText, val.headers, val.cf, val.body]; + } + }; +} +function createHTTPRevivers(impl) { + return { + Headers(value) { + return assert(typeof value == "object" && value !== null), new impl.Headers(value); + }, + Request(value) { + assert(Array.isArray(value)); + let [method, url, headers, cf, body] = value; + return assert(typeof method == "string"), assert(typeof url == "string"), assert(headers instanceof impl.Headers), assert(body === null || impl.isReadableStream(body)), new impl.Request(url, { + method, + headers, + cf, + // @ts-expect-error `duplex` is not required by `workerd` yet + duplex: body === null ? void 0 : "half", + body + }); + }, + Response(value) { + assert(Array.isArray(value)); + let [status, statusText, headers, cf, body] = value; + return assert(typeof status == "number"), assert(typeof statusText == "string"), assert(headers instanceof impl.Headers), assert(body === null || impl.isReadableStream(body)), new impl.Response(body, { + status, + statusText, + headers, + cf + }); + } + }; +} +function stringifyWithStreams(impl, value, reducers, allowUnbufferedStream) { + let unbufferedStream, bufferPromises = [], streamReducers = { + ReadableStream(value2) { + if (impl.isReadableStream(value2)) + return allowUnbufferedStream && unbufferedStream === void 0 ? unbufferedStream = value2 : bufferPromises.push(impl.bufferReadableStream(value2)), !0; + }, + Blob(value2) { + if (value2 instanceof impl.Blob) + return bufferPromises.push(value2.arrayBuffer()), !0; + }, + ...reducers + }, stringifiedValue = stringify(value, streamReducers); + return bufferPromises.length === 0 ? { value: stringifiedValue, unbufferedStream } : Promise.all(bufferPromises).then((streamBuffers) => (streamReducers.ReadableStream = function(value2) { + if (impl.isReadableStream(value2)) + return value2 === unbufferedStream ? !0 : streamBuffers.shift(); + }, streamReducers.Blob = function(value2) { + if (value2 instanceof impl.Blob) { + let array = [streamBuffers.shift(), value2.type]; + return value2 instanceof impl.File && array.push(value2.name, value2.lastModified), array; + } + }, { value: stringify(value, streamReducers), unbufferedStream })); +} +function parseWithReadableStreams(impl, stringified, revivers) { + let streamRevivers = { + ReadableStream(value) { + return value === !0 ? (assert(stringified.unbufferedStream !== void 0), stringified.unbufferedStream) : (assert(value instanceof ArrayBuffer), impl.unbufferReadableStream(value)); + }, + Blob(value) { + if (assert(Array.isArray(value)), value.length === 2) { + let [buffer, type] = value; + assert(buffer instanceof ArrayBuffer), assert(typeof type == "string"); + let opts = {}; + return type !== "" && (opts.type = type), new impl.Blob([buffer], opts); + } else { + assert(value.length === 4); + let [buffer, type, name, lastModified] = value; + assert(buffer instanceof ArrayBuffer), assert(typeof type == "string"), assert(typeof name == "string"), assert(typeof lastModified == "number"); + let opts = { lastModified }; + return type !== "" && (opts.type = type), new impl.File([buffer], name, opts); + } + }, + ...revivers + }; + return parse(stringified.value, streamRevivers); +} + +// src/workers/core/proxy.worker.ts +var ENCODER = new TextEncoder(), DECODER = new TextDecoder(), ALLOWED_HOSTNAMES = ["127.0.0.1", "[::1]", "localhost"], WORKERS_PLATFORM_IMPL = { + Blob, + File, + Headers, + Request, + Response, + isReadableStream(value) { + return value instanceof ReadableStream; + }, + bufferReadableStream(stream) { + return new Response(stream).arrayBuffer(); + }, + unbufferReadableStream(buffer) { + let body = new Response(buffer).body; + return assert2(body !== null), body; + } +}, objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0"); +function isPlainObject(value) { + let proto = Object.getPrototypeOf(value); + return value?.constructor?.name === "RpcStub" || isObject(value) && objectContainsFunctions(value) ? !1 : proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames; +} +function objectContainsFunctions(obj) { + for (let [, entry] of Object.entries(obj)) { + if (typeof entry == "function") + return !0; + if (isObject(entry) && objectContainsFunctions(entry)) + return !1; + } + return !1; +} +function isObject(value) { + return value && typeof value == "object"; +} +function getType(value) { + return Object.prototype.toString.call(value).slice(8, -1); +} +var ProxyServer = class { + constructor(_state, env) { + this.env = env; + this.heap.set(ProxyAddresses.GLOBAL, globalThis), this.heap.set(ProxyAddresses.ENV, env); + } + nextHeapAddress = ProxyAddresses.USER_START; + heap = /* @__PURE__ */ new Map(); + reducers = { + ...structuredSerializableReducers, + ...createHTTPReducers(WORKERS_PLATFORM_IMPL), + // Corresponding revivers in `ProxyClient` + // `Native` reducer *MUST* be applied last + Native: (value) => { + let type = getType(value); + if (type === "Object" && !isPlainObject(value) || type === "Promise") { + let address = this.nextHeapAddress++; + return this.heap.set(address, value), assert2(value !== null), [address, value?.constructor.name]; + } + } + }; + revivers = { + ...structuredSerializableRevivers, + ...createHTTPRevivers(WORKERS_PLATFORM_IMPL), + // Corresponding reducers in `ProxyClient` + Native: (value) => { + assert2(Array.isArray(value)); + let [address] = value; + assert2(typeof address == "number"); + let heapValue = this.heap.get(address); + return assert2(heapValue !== void 0), heapValue instanceof Promise && this.heap.delete(address), heapValue; + } + }; + nativeReviver = { Native: this.revivers.Native }; + async fetch(request) { + try { + return await this.#fetch(request); + } catch (e) { + let error = reduceError(e); + return Response.json(error, { + status: 500, + headers: { [CoreHeaders.ERROR_STACK]: "true" } + }); + } + } + async #fetch(request) { + let hostHeader = request.headers.get("Host"); + if (hostHeader == null) + return new Response(null, { status: 400 }); + try { + let host = new URL(`http://${hostHeader}`); + if (!ALLOWED_HOSTNAMES.includes(host.hostname)) + return new Response(null, { status: 401 }); + } catch { + return new Response(null, { status: 400 }); + } + let secretHex = request.headers.get(CoreHeaders.OP_SECRET); + if (secretHex == null) + return new Response(null, { status: 401 }); + let expectedSecret = this.env[CoreBindings.DATA_PROXY_SECRET], secretBuffer = Buffer2.from(secretHex, "hex"); + if (secretBuffer.byteLength !== expectedSecret.byteLength || !crypto.subtle.timingSafeEqual(secretBuffer, expectedSecret)) + return new Response(null, { status: 401 }); + let opHeader = request.headers.get(CoreHeaders.OP), targetHeader = request.headers.get(CoreHeaders.OP_TARGET), keyHeader = request.headers.get(CoreHeaders.OP_KEY), allowAsync = request.headers.get(CoreHeaders.OP_SYNC) === null, argsSizeHeader = request.headers.get(CoreHeaders.OP_STRINGIFIED_SIZE), contentLengthHeader = request.headers.get("Content-Length"); + if (targetHeader === null) + return new Response(null, { status: 400 }); + if (opHeader === ProxyOps.FREE) { + for (let targetValue of targetHeader.split(",")) { + let targetAddress = parseInt(targetValue); + assert2(!Number.isNaN(targetAddress)), this.heap.delete(targetAddress); + } + return new Response(null, { status: 204 }); + } + let target = parse( + targetHeader, + this.nativeReviver + ), targetName = target.constructor.name, status = 200, result, unbufferedRest; + if (opHeader === ProxyOps.GET) { + if (result = keyHeader === null ? target : target[keyHeader], result?.constructor.name === "RpcProperty" && (result = await result), typeof result == "function") + return new Response(null, { + status: 204, + headers: { [CoreHeaders.OP_RESULT_TYPE]: "Function" } + }); + } else if (opHeader === ProxyOps.GET_OWN_DESCRIPTOR) { + if (keyHeader === null) + return new Response(null, { status: 400 }); + let descriptor = Object.getOwnPropertyDescriptor(target, keyHeader); + descriptor !== void 0 && (result = { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + writable: descriptor.writable + }); + } else if (opHeader === ProxyOps.GET_OWN_KEYS) + result = Object.getOwnPropertyNames(target); + else if (opHeader === ProxyOps.CALL) { + if (keyHeader === null) + return new Response(null, { status: 400 }); + let func = target[keyHeader]; + if (assert2(typeof func == "function"), isFetcherFetch(targetName, keyHeader)) { + let originalUrl = request.headers.get(CoreHeaders.ORIGINAL_URL), url = new URL(originalUrl ?? request.url); + return request = new Request(url, request), request.headers.delete(CoreHeaders.OP_SECRET), request.headers.delete(CoreHeaders.OP), request.headers.delete(CoreHeaders.OP_TARGET), request.headers.delete(CoreHeaders.OP_KEY), request.headers.delete(CoreHeaders.ORIGINAL_URL), request.headers.delete(CoreHeaders.DISABLE_PRETTY_ERROR), func.call(target, request); + } + let args; + if (argsSizeHeader === null || argsSizeHeader === contentLengthHeader) + args = parseWithReadableStreams( + WORKERS_PLATFORM_IMPL, + { value: await request.text() }, + this.revivers + ); + else { + let argsSize = parseInt(argsSizeHeader); + assert2(!Number.isNaN(argsSize)), assert2(request.body !== null); + let [encodedArgs, rest] = await readPrefix(request.body, argsSize); + unbufferedRest = rest; + let stringifiedArgs = DECODER.decode(encodedArgs); + args = parseWithReadableStreams( + WORKERS_PLATFORM_IMPL, + { value: stringifiedArgs, unbufferedStream: rest }, + this.revivers + ); + } + assert2(Array.isArray(args)); + try { + func.constructor.name === "RpcProperty" ? (result = func(...args), result = new Promise( + (resolve, reject) => result.then((v) => { + if (v.hasOwnProperty(Symbol.dispose) && delete v[Symbol.dispose], v.hasOwnProperty(Symbol.asyncDispose) && delete v[Symbol.asyncDispose], v.constructor.name === "RpcStub") + return resolve(new Proxy({ v }, { + get(target2, p) { + return target2.v[p]; + } + })); + resolve(v); + }).catch(reject) + )) : result = func.apply(target, args), isR2ObjectWriteHttpMetadata(targetName, keyHeader) && (result = args[0]); + } catch (e) { + status = 500, result = e; + } + } else + return new Response(null, { status: 404 }); + let headers = new Headers(); + if (allowAsync && result instanceof Promise) { + try { + result = await result; + } catch (e) { + status = 500, result = e; + } + headers.append(CoreHeaders.OP_RESULT_TYPE, "Promise"); + } + if (unbufferedRest !== void 0 && !unbufferedRest.locked) + try { + await unbufferedRest.pipeTo(new WritableStream()); + } catch { + } + if (result instanceof ReadableStream) + return headers.append(CoreHeaders.OP_RESULT_TYPE, "ReadableStream"), new Response(result, { status, headers }); + { + let stringified = await stringifyWithStreams( + WORKERS_PLATFORM_IMPL, + result, + this.reducers, + /* allowUnbufferedStream */ + allowAsync + ); + if (stringified.unbufferedStream === void 0) + return new Response(stringified.value, { status, headers }); + { + let body = new IdentityTransformStream(), encodedValue = ENCODER.encode(stringified.value), encodedSize = encodedValue.byteLength.toString(); + return headers.set(CoreHeaders.OP_STRINGIFIED_SIZE, encodedSize), this.#writeWithUnbufferedStream( + body.writable, + encodedValue, + stringified.unbufferedStream + ), new Response(body.readable, { status, headers }); + } + } + } + async #writeWithUnbufferedStream(writable, encodedValue, unbufferedStream) { + let writer = writable.getWriter(); + await writer.write(encodedValue), writer.releaseLock(), await unbufferedStream.pipeTo(writable); + } +}; + +// src/workers/core/entry.worker.ts +var encoder = new TextEncoder(); +function getUserRequest(request, env) { + let originalUrl = request.headers.get(CoreHeaders.ORIGINAL_URL), url = new URL(originalUrl ?? request.url), rewriteHeadersFromOriginalUrl = !1, proxySharedSecret = request.headers.get( + CoreHeaders.PROXY_SHARED_SECRET + ); + if (proxySharedSecret) { + let secretFromHeader = encoder.encode(proxySharedSecret), configuredSecret = env[CoreBindings.DATA_PROXY_SHARED_SECRET]; + if (secretFromHeader.byteLength === configuredSecret?.byteLength && crypto.subtle.timingSafeEqual(secretFromHeader, configuredSecret)) + rewriteHeadersFromOriginalUrl = !0; + else + throw new HttpError( + 400, + `Disallowed header in request: ${CoreHeaders.PROXY_SHARED_SECRET}=${proxySharedSecret}` + ); + } + let upstreamUrl = env[CoreBindings.TEXT_UPSTREAM_URL]; + if (upstreamUrl !== void 0) { + let path = url.pathname + url.search; + path.startsWith("/") && (path = `./${path.substring(1)}`), url = new URL(path, upstreamUrl), rewriteHeadersFromOriginalUrl = !0; + } + if (request = new Request(url, request), request.cf === void 0) { + let cf = { + ...env[CoreBindings.JSON_CF_BLOB], + // Defaulting to empty string to preserve undefined `Accept-Encoding` + // through Wrangler's proxy worker. + clientAcceptEncoding: request.headers.get("Accept-Encoding") ?? "" + }; + request = new Request(request, { cf }); + } + return request.headers.set("Accept-Encoding", "br, gzip"), rewriteHeadersFromOriginalUrl && request.headers.set("Host", url.host), request.headers.delete(CoreHeaders.PROXY_SHARED_SECRET), request.headers.delete(CoreHeaders.ORIGINAL_URL), request.headers.delete(CoreHeaders.DISABLE_PRETTY_ERROR), request; +} +function getTargetService(request, url, env) { + let service = env[CoreBindings.SERVICE_USER_FALLBACK], override = request.headers.get(CoreHeaders.ROUTE_OVERRIDE); + request.headers.delete(CoreHeaders.ROUTE_OVERRIDE); + let route = override ?? matchRoutes(env[CoreBindings.JSON_ROUTES], url); + return route !== null && (service = env[`${CoreBindings.SERVICE_USER_ROUTE_PREFIX}${route}`]), service; +} +function maybePrettifyError(request, response, env) { + return response.status !== 500 || response.headers.get(CoreHeaders.ERROR_STACK) === null ? response : env[CoreBindings.SERVICE_LOOPBACK].fetch( + "http://localhost/core/error", + { + method: "POST", + headers: request.headers, + body: response.body, + cf: { prettyErrorOriginalUrl: request.url } + } + ); +} +function maybeInjectLiveReload(response, env, ctx) { + let liveReloadScript = env[CoreBindings.DATA_LIVE_RELOAD_SCRIPT]; + if (liveReloadScript === void 0 || !response.headers.get("Content-Type")?.toLowerCase().includes("text/html")) + return response; + let headers = new Headers(response.headers), contentLength = parseInt(headers.get("content-length")); + isNaN(contentLength) || headers.set( + "content-length", + String(contentLength + liveReloadScript.byteLength) + ); + let { readable, writable } = new IdentityTransformStream(); + return ctx.waitUntil( + (async () => { + await response.body?.pipeTo(writable, { preventClose: !0 }); + let writer = writable.getWriter(); + await writer.write(liveReloadScript), await writer.close(); + })() + ), new Response(readable, { + status: response.status, + statusText: response.statusText, + headers + }); +} +var acceptEncodingElement = /^(?[a-z]+|\*)(?:\s*;\s*q=(?\d+(?:.\d+)?))?$/; +function maybeParseAcceptEncodingElement(element) { + let match = acceptEncodingElement.exec(element); + if (match?.groups != null) + return { + coding: match.groups.coding, + weight: match.groups.weight === void 0 ? 1 : parseFloat(match.groups.weight) + }; +} +function parseAcceptEncoding(header) { + let encodings = []; + for (let element of header.split(",")) { + let maybeEncoding = maybeParseAcceptEncodingElement(element.trim()); + maybeEncoding !== void 0 && encodings.push(maybeEncoding); + } + return encodings.sort((a, b) => b.weight - a.weight); +} +function ensureAcceptableEncoding(clientAcceptEncoding, response) { + if (clientAcceptEncoding === null) + return response; + let encodings = parseAcceptEncoding(clientAcceptEncoding); + if (encodings.length === 0) + return response; + let contentEncoding = response.headers.get("Content-Encoding"); + if (contentEncoding !== null && contentEncoding !== "gzip" && contentEncoding !== "br") + return response; + let desiredEncoding, identityDisallowed = !1; + for (let encoding of encodings) + if (encoding.weight === 0) + (encoding.coding === "identity" || encoding.coding === "*") && (identityDisallowed = !0); + else if (encoding.coding === "gzip" || encoding.coding === "br") { + desiredEncoding = encoding.coding; + break; + } else if (encoding.coding === "identity") + break; + return desiredEncoding === void 0 ? identityDisallowed ? new Response("Unsupported Media Type", { + status: 415, + headers: { "Accept-Encoding": "br, gzip" } + }) : (contentEncoding === null || (response = new Response(response.body, response), response.headers.delete("Content-Encoding")), response) : (contentEncoding === desiredEncoding || (response = new Response(response.body, response), response.headers.set("Content-Encoding", desiredEncoding)), response); +} +function colourFromHTTPStatus(status) { + return 200 <= status && status < 300 ? green : 400 <= status && status < 500 ? yellow : 500 <= status ? red : blue; +} +function maybeLogRequest(req, res, env, ctx, startTime) { + if (env[CoreBindings.JSON_LOG_LEVEL] < LogLevel.INFO) + return; + let url = new URL(req.url), statusText = (res.statusText.trim() || STATUS_CODES[res.status]) ?? "", lines = [ + `${bold(req.method)} ${url.pathname} `, + colourFromHTTPStatus(res.status)(`${bold(res.status)} ${statusText} `), + grey(`(${Date.now() - startTime}ms)`) + ], message = reset(lines.join("")); + ctx.waitUntil( + env[CoreBindings.SERVICE_LOOPBACK].fetch("http://localhost/core/log", { + method: "POST", + headers: { [SharedHeaders.LOG_LEVEL]: LogLevel.INFO.toString() }, + body: message + }) + ); +} +function handleProxy(request, env) { + let ns = env[CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY], id = ns.idFromName(""); + return ns.get(id).fetch(request); +} +async function handleScheduled(params, service) { + let time = params.get("time"), scheduledTime = time ? new Date(parseInt(time)) : void 0, cron = params.get("cron") ?? void 0, result = await service.scheduled({ + scheduledTime, + cron + }); + return new Response(result.outcome, { + status: result.outcome === "ok" ? 200 : 500 + }); +} +var entry_worker_default = { + async fetch(request, env, ctx) { + let startTime = Date.now(); + if (request.headers.get(CoreHeaders.OP) !== null) + return handleProxy(request, env); + let disablePrettyErrorPage = request.headers.get(CoreHeaders.DISABLE_PRETTY_ERROR) !== null, clientAcceptEncoding = request.headers.get("Accept-Encoding"); + try { + request = getUserRequest(request, env); + } catch (e) { + if (e instanceof HttpError) + return e.toResponse(); + throw e; + } + let url = new URL(request.url), service = getTargetService(request, url, env); + if (service === void 0) + return new Response("No entrypoint worker found", { status: 404 }); + try { + if (url.pathname === "/cdn-cgi/mf/scheduled") + return await handleScheduled(url.searchParams, service); + let response = await service.fetch(request); + return disablePrettyErrorPage || (response = await maybePrettifyError(request, response, env)), response = maybeInjectLiveReload(response, env, ctx), response = ensureAcceptableEncoding(clientAcceptEncoding, response), maybeLogRequest(request, response, env, ctx, startTime), response; + } catch (e) { + return new Response(e?.stack ?? String(e), { status: 500 }); + } + } +}; +export { + ProxyServer, + entry_worker_default as default +}; +//# sourceMappingURL=entry.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/core/entry.worker.js.map b/node_modules/miniflare/dist/src/workers/core/entry.worker.js.map new file mode 100644 index 0000000..555be10 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/core/entry.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs", "../../../../src/workers/core/entry.worker.ts", "../../../../src/workers/core/constants.ts", "../../../../src/workers/core/http.ts", "../../../../src/workers/core/routing.ts", "../../../../src/workers/core/proxy.worker.ts", "../../../../../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/utils.js", "../../../../../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/parse.js", "../../../../../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/stringify.js", "../../../../src/workers/core/devalue.ts"], + "mappings": ";AAAA,IAAI,aAAa,qBAAqB,UAAU,MAAM,QAAM;AACxD,OAAO,UAAY,QACrB,EAAE,aAAa,qBAAqB,UAAU,KAAK,IAAI,QAAQ,OAAO,CAAC,GACxE,QAAQ,QAAQ,UAAU,QAAQ,OAAO;AAGnC,IAAM,IAAI;AAAA,EAChB,SAAS,CAAC,uBAAuB,YAAY,QAAQ,SAAS,WAC7D,eAAe,QAAQ,gBAAgB,OAAO;AAEhD;AAEA,SAAS,KAAK,GAAG,GAAG;AACnB,MAAI,MAAM,IAAI,OAAO,WAAW,MAAM,GAAG,GACrC,OAAO,QAAQ,MAAM,QAAQ,QAAQ;AAEzC,SAAO,SAAU,KAAK;AACrB,WAAI,CAAC,EAAE,WAAW,OAAO,OAAa,MAC/B,QAAU,EAAE,KAAG,KAAK,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,QAAQ,IAAI,IAAI,OAAO;AAAA,EACrF;AACD;AAGO,IAAM,QAAQ,KAAK,GAAG,CAAC,GACjB,OAAO,KAAK,GAAG,EAAE,GACjB,MAAM,KAAK,GAAG,EAAE,GAChB,SAAS,KAAK,GAAG,EAAE,GACnB,YAAY,KAAK,GAAG,EAAE,GACtB,UAAU,KAAK,GAAG,EAAE,GACpB,SAA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AS,UAAU,GAAG,IAE3D,WAAW,sBAAsB,UAAU,KAAK,GAAG,GACnD,WAAW,yBAAyB,sBAAsB,QAAQ,GAClE,gBAAgB,SAAS,UAAU,KAAK,KAAK,SAAS,GAC/C;AAAA,IACR,SAAS,GAAP;AACD,aAAO,IAAI,SAAS,GAAG,SAAS,OAAO,CAAC,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC3D;AAAA,EACD;AACD;", + "names": ["assert", "Buffer", "index", "value", "value", "assert", "Buffer", "target"] +} diff --git a/node_modules/miniflare/dist/src/workers/d1/database.worker.js b/node_modules/miniflare/dist/src/workers/d1/database.worker.js new file mode 100644 index 0000000..f6b2587 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/d1/database.worker.js @@ -0,0 +1,115 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __decorateClass = (decorators, target, key, kind) => { + for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--) + (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result); + return kind && result && __defProp(target, key, result), result; +}; + +// src/workers/d1/database.worker.ts +import assert from "node:assert"; +import { + HttpError, + MiniflareDurableObject, + POST, + all, + get, + viewToBuffer +} from "miniflare:shared"; +import { z } from "miniflare:zod"; +var D1ValueSchema = z.union([ + z.number(), + z.string(), + z.null(), + z.number().array() +]), D1QuerySchema = z.object({ + sql: z.string(), + params: z.array(D1ValueSchema).nullable().optional() +}), D1QueriesSchema = z.union([D1QuerySchema, z.array(D1QuerySchema)]), served_by = "miniflare.db", D1Error = class extends HttpError { + constructor(cause) { + super(500); + this.cause = cause; + } + toResponse() { + let response = { success: !1, error: typeof this.cause == "object" && this.cause !== null && "message" in this.cause && typeof this.cause.message == "string" ? this.cause.message : String(this.cause) }; + return Response.json(response); + } +}; +function convertParams(params) { + return (params ?? []).map( + (param) => ( + // If `param` is an array, assume it's a byte array + Array.isArray(param) ? viewToBuffer(new Uint8Array(param)) : param + ) + ); +} +function convertResults(rows) { + return rows.map( + (row) => Object.fromEntries( + Object.entries(row).map(([key, value]) => { + let normalised; + return value instanceof ArrayBuffer ? normalised = Array.from(new Uint8Array(value)) : normalised = value, [key, normalised]; + }) + ) + ); +} +function sqlStmts(db) { + return { + getChanges: db.prepare( + "SELECT total_changes() AS totalChanges, last_insert_rowid() AS lastRowId" + ) + }; +} +var D1DatabaseObject = class extends MiniflareDurableObject { + #stmts; + constructor(state, env) { + super(state, env), this.#stmts = sqlStmts(this.db); + } + #changes() { + let changes = get(this.#stmts.getChanges()); + return assert(changes !== void 0), changes; + } + #query = (query) => { + let beforeTime = performance.now(), beforeSize = this.state.storage.sql.databaseSize, beforeChanges = this.#changes(), params = convertParams(query.params ?? []), cursor = this.db.prepare(query.sql)(...params), results = convertResults(all(cursor)), afterTime = performance.now(), afterSize = this.state.storage.sql.databaseSize, afterChanges = this.#changes(), duration = afterTime - beforeTime, changes = afterChanges.totalChanges - beforeChanges.totalChanges, hasChanges = changes !== 0, lastRowChanged = afterChanges.lastRowId !== beforeChanges.lastRowId, changed = hasChanges || lastRowChanged || afterSize !== beforeSize; + return { + success: !0, + results, + meta: { + served_by, + duration, + changes, + last_row_id: afterChanges.lastRowId, + changed_db: changed, + size_after: afterSize, + rows_read: cursor.rowsRead, + rows_written: cursor.rowsWritten + } + }; + }; + #txn(queries) { + if (queries = queries.filter( + (query) => query.sql.replace(/^\s+--.*/gm, "").trim().length > 0 + ), queries.length === 0) { + let error = new Error("No SQL statements detected."); + throw new D1Error(error); + } + try { + return this.state.storage.transactionSync(() => queries.map(this.#query)); + } catch (e) { + throw new D1Error(e); + } + } + queryExecute = async (req) => { + let queries = D1QueriesSchema.parse(await req.json()); + return Array.isArray(queries) || (queries = [queries]), Response.json(this.#txn(queries)); + }; +}; +__decorateClass([ + POST("/query"), + POST("/execute") +], D1DatabaseObject.prototype, "queryExecute", 2); +export { + D1DatabaseObject, + D1Error +}; +//# sourceMappingURL=database.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/d1/database.worker.js.map b/node_modules/miniflare/dist/src/workers/d1/database.worker.js.map new file mode 100644 index 0000000..e974ab2 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/d1/database.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/d1/database.worker.ts"], + "mappings": ";;;;;;;;;AAAA,OAAO,YAAY;AACnB;AAAA,EACC;AAAA,EACA;AAAA,EAEA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,SAAS;AAElB,IAAM,gBAAgB,EAAE,MAAM;AAAA,EAC7B,EAAE,OAAO;AAAA,EACT,EAAE,OAAO;AAAA,EACT,EAAE,KAAK;AAAA,EACP,EAAE,OAAO,EAAE,MAAM;AAClB,CAAC,GAGK,gBAAgB,EAAE,OAAO;AAAA,EAC9B,KAAK,EAAE,OAAO;AAAA,EACd,QAAQ,EAAE,MAAM,aAAa,EAAE,SAAS,EAAE,SAAS;AACpD,CAAC,GAEK,kBAAkB,EAAE,MAAM,CAAC,eAAe,EAAE,MAAM,aAAa,CAAC,CAAC,GAEjE,YAAY,gBAoBL,UAAN,cAAsB,UAAU;AAAA,EACtC,YAAqB,OAAgB;AACpC,UAAM,GAAG;AADW;AAAA,EAErB;AAAA,EAEA,aAAuB;AAQtB,QAAM,WAA8B,EAAE,SAAS,IAAO,OANrD,OAAO,KAAK,SAAU,YACtB,KAAK,UAAU,QACf,aAAa,KAAK,SAClB,OAAO,KAAK,MAAM,WAAY,WAC3B,KAAK,MAAM,UACX,OAAO,KAAK,KAAK,EACuC;AAC5D,WAAO,SAAS,KAAK,QAAQ;AAAA,EAC9B;AACD;AAEA,SAAS,cAAc,QAAyC;AAC/D,UAAQ,UAAU,CAAC,GAAG;AAAA,IAAI,CAAC;AAAA;AAAA,MAE1B,MAAM,QAAQ,KAAK,IAAI,aAAa,IAAI,WAAW,KAAK,CAA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A,MACA,MAAM;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA,aAAa,aAAa;AAAA,QAC1B,YAAY;AAAA,QACZ,YAAY;AAAA,QACZ,WAAW,OAAO;AAAA,QAClB,cAAc,OAAO;AAAA,MACtB;AAAA,IACD;AAAA,EACD;AAAA,EAEA,KAAK,SAAyC;AAK7C,QAHA,UAAU,QAAQ;AAAA,MACjB,CAAC,UAAU,MAAM,IAAI,QAAQ,cAAc,EAAE,EAAE,KAAK,EAAE,SAAS;AAAA,IAChE,GACI,QAAQ,WAAW,GAAG;AACzB,UAAM,QAAQ,IAAI,MAAM,6BAA6B;AACrD,YAAM,IAAI,QAAQ,KAAK;AAAA,IACxB;AAEA,QAAI;AACH,aAAO,KAAK,MAAM,QAAQ,gBAAgB,MAAM,QAAQ,IAAI,KAAK,MAAM,CAAC;AAAA,IACzE,SAAS,GAAP;AACD,YAAM,IAAI,QAAQ,CAAC;AAAA,IACpB;AAAA,EACD;AAAA,EAIA,eAA6B,OAAO,QAAQ;AAC3C,QAAI,UAAU,gBAAgB,MAAM,MAAM,IAAI,KAAK,CAAC;AACpD,WAAK,MAAM,QAAQ,OAAO,MAAG,UAAU,CAAC,OAAO,IACxC,SAAS,KAAK,KAAK,KAAK,OAAO,CAAC;AAAA,EACxC;AACD;AALC;AAAA,EAFC,KAAK,QAAQ;AAAA,EACb,KAAK,UAAU;AAAA,GAtEJ,iBAuEZ;", + "names": [] +} diff --git a/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js b/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js new file mode 100644 index 0000000..2bc3a75 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js @@ -0,0 +1,258 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __decorateClass = (decorators, target, key, kind) => { + for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--) + (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result); + return kind && result && __defProp(target, key, result), result; +}; + +// src/workers/kv/namespace.worker.ts +import assert from "node:assert"; +import { + DELETE, + DeferredPromise, + GET, + HttpError as HttpError2, + KeyValueStorage, + MiniflareDurableObject, + PUT, + maybeApply +} from "miniflare:shared"; + +// src/workers/kv/constants.ts +import { testRegExps } from "miniflare:shared"; +var KVLimits = { + MIN_CACHE_TTL: 60, + MAX_LIST_KEYS: 1e3, + MAX_KEY_SIZE: 512, + MAX_VALUE_SIZE: 25 * 1024 * 1024, + MAX_VALUE_SIZE_TEST: 1024, + MAX_METADATA_SIZE: 1024 +}, KVParams = { + URL_ENCODED: "urlencoded", + CACHE_TTL: "cache_ttl", + EXPIRATION: "expiration", + EXPIRATION_TTL: "expiration_ttl", + LIST_LIMIT: "key_count_limit", + LIST_PREFIX: "prefix", + LIST_CURSOR: "cursor" +}, KVHeaders = { + EXPIRATION: "CF-Expiration", + METADATA: "CF-KV-Metadata" +}; + +// src/workers/kv/validator.worker.ts +import { Buffer as Buffer2 } from "node:buffer"; +import { HttpError } from "miniflare:shared"; +function decodeKey({ key }, query) { + if (query.get(KVParams.URL_ENCODED)?.toLowerCase() !== "true") + return key; + try { + return decodeURIComponent(key); + } catch (e) { + throw e instanceof URIError ? new HttpError(400, "Could not URL-decode key name") : e; + } +} +function validateKey(key) { + if (key === "") + throw new HttpError(400, "Key names must not be empty"); + if (key === "." || key === "..") + throw new HttpError( + 400, + `Illegal key name "${key}". Please use a different name.` + ); + validateKeyLength(key); +} +function validateKeyLength(key) { + let keyLength = Buffer2.byteLength(key); + if (keyLength > KVLimits.MAX_KEY_SIZE) + throw new HttpError( + 414, + `UTF-8 encoded length of ${keyLength} exceeds key length limit of ${KVLimits.MAX_KEY_SIZE}.` + ); +} +function validateGetOptions(key, options) { + validateKey(key); + let cacheTtl = options?.cacheTtl; + if (cacheTtl !== void 0 && (isNaN(cacheTtl) || cacheTtl < KVLimits.MIN_CACHE_TTL)) + throw new HttpError( + 400, + `Invalid ${KVParams.CACHE_TTL} of ${cacheTtl}. Cache TTL must be at least ${KVLimits.MIN_CACHE_TTL}.` + ); +} +function validatePutOptions(key, options) { + let { now, rawExpiration, rawExpirationTtl, rawMetadata } = options; + validateKey(key); + let expiration; + if (rawExpirationTtl !== null) { + let expirationTtl = parseInt(rawExpirationTtl); + if (Number.isNaN(expirationTtl) || expirationTtl <= 0) + throw new HttpError( + 400, + `Invalid ${KVParams.EXPIRATION_TTL} of ${rawExpirationTtl}. Please specify integer greater than 0.` + ); + if (expirationTtl < KVLimits.MIN_CACHE_TTL) + throw new HttpError( + 400, + `Invalid ${KVParams.EXPIRATION_TTL} of ${rawExpirationTtl}. Expiration TTL must be at least ${KVLimits.MIN_CACHE_TTL}.` + ); + expiration = now + expirationTtl; + } else if (rawExpiration !== null) { + if (expiration = parseInt(rawExpiration), Number.isNaN(expiration) || expiration <= now) + throw new HttpError( + 400, + `Invalid ${KVParams.EXPIRATION} of ${rawExpiration}. Please specify integer greater than the current number of seconds since the UNIX epoch.` + ); + if (expiration < now + KVLimits.MIN_CACHE_TTL) + throw new HttpError( + 400, + `Invalid ${KVParams.EXPIRATION} of ${rawExpiration}. Expiration times must be at least ${KVLimits.MIN_CACHE_TTL} seconds in the future.` + ); + } + let metadata; + if (rawMetadata !== null) { + let metadataLength = Buffer2.byteLength(rawMetadata); + if (metadataLength > KVLimits.MAX_METADATA_SIZE) + throw new HttpError( + 413, + `Metadata length of ${metadataLength} exceeds limit of ${KVLimits.MAX_METADATA_SIZE}.` + ); + metadata = JSON.parse(rawMetadata); + } + return { expiration, metadata }; +} +function decodeListOptions(url) { + let limitParam = url.searchParams.get(KVParams.LIST_LIMIT), limit = limitParam === null ? KVLimits.MAX_LIST_KEYS : parseInt(limitParam), prefix = url.searchParams.get(KVParams.LIST_PREFIX) ?? void 0, cursor = url.searchParams.get(KVParams.LIST_CURSOR) ?? void 0; + return { limit, prefix, cursor }; +} +function validateListOptions(options) { + let limit = options.limit; + if (limit !== void 0) { + if (isNaN(limit) || limit < 1) + throw new HttpError( + 400, + `Invalid ${KVParams.LIST_LIMIT} of ${limit}. Please specify an integer greater than 0.` + ); + if (limit > KVLimits.MAX_LIST_KEYS) + throw new HttpError( + 400, + `Invalid ${KVParams.LIST_LIMIT} of ${limit}. Please specify an integer less than ${KVLimits.MAX_LIST_KEYS}.` + ); + } + let prefix = options.prefix; + prefix != null && validateKeyLength(prefix); +} + +// src/workers/kv/namespace.worker.ts +function createMaxValueSizeError(length, maxValueSize) { + return new HttpError2( + 413, + `Value length of ${length} exceeds limit of ${maxValueSize}.` + ); +} +var MaxLengthStream = class extends TransformStream { + signal; + length; + constructor(maxLength) { + let abortController = new AbortController(), lengthPromise = new DeferredPromise(), length = 0; + super({ + transform(chunk, controller) { + length += chunk.byteLength, length <= maxLength ? controller.enqueue(chunk) : abortController.signal.aborted || abortController.abort(); + }, + flush() { + lengthPromise.resolve(length); + } + }), this.signal = abortController.signal, this.length = lengthPromise; + } +}; +function millisToSeconds(millis) { + return Math.floor(millis / 1e3); +} +function secondsToMillis(seconds) { + return seconds * 1e3; +} +var KVNamespaceObject = class extends MiniflareDurableObject { + #storage; + get storage() { + return this.#storage ??= new KeyValueStorage(this); + } + get = async (req, params, url) => { + let key = decodeKey(params, url.searchParams), cacheTtlParam = url.searchParams.get(KVParams.CACHE_TTL), cacheTtl = cacheTtlParam === null ? void 0 : parseInt(cacheTtlParam); + validateGetOptions(key, { cacheTtl }); + let entry = await this.storage.get(key); + if (entry === null) + throw new HttpError2(404, "Not Found"); + let headers = new Headers(); + return entry.expiration !== void 0 && headers.set( + KVHeaders.EXPIRATION, + millisToSeconds(entry.expiration).toString() + ), entry.metadata !== void 0 && headers.set(KVHeaders.METADATA, JSON.stringify(entry.metadata)), new Response(entry.value, { headers }); + }; + put = async (req, params, url) => { + let key = decodeKey(params, url.searchParams), rawExpiration = url.searchParams.get(KVParams.EXPIRATION), rawExpirationTtl = url.searchParams.get(KVParams.EXPIRATION_TTL), rawMetadata = req.headers.get(KVHeaders.METADATA), now = millisToSeconds(this.timers.now()), { expiration, metadata } = validatePutOptions(key, { + now, + rawExpiration, + rawExpirationTtl, + rawMetadata + }), value = req.body, contentLength = parseInt(req.headers.get("Content-Length")), valueLengthHint; + Number.isNaN(contentLength) ? value === null && (valueLengthHint = 0) : valueLengthHint = contentLength, value ??= new ReadableStream({ + start(controller) { + controller.close(); + } + }); + let maxValueSize = this.beingTested ? KVLimits.MAX_VALUE_SIZE_TEST : KVLimits.MAX_VALUE_SIZE, maxLengthStream; + if (valueLengthHint !== void 0 && valueLengthHint > maxValueSize) + throw createMaxValueSizeError(valueLengthHint, maxValueSize); + maxLengthStream = new MaxLengthStream(maxValueSize), value = value.pipeThrough(maxLengthStream); + try { + await this.storage.put({ + key, + value, + expiration: maybeApply(secondsToMillis, expiration), + metadata, + signal: maxLengthStream?.signal + }); + } catch (e) { + if (typeof e == "object" && e !== null && "name" in e && e.name === "AbortError") { + assert(maxLengthStream !== void 0); + let length = await maxLengthStream.length; + throw createMaxValueSizeError(length, maxValueSize); + } else + throw e; + } + return new Response(); + }; + delete = async (req, params, url) => { + let key = decodeKey(params, url.searchParams); + return validateKey(key), await this.storage.delete(key), new Response(); + }; + list = async (req, params, url) => { + let options = decodeListOptions(url); + validateListOptions(options); + let res = await this.storage.list(options), keys = res.keys.map((key) => ({ + name: key.key, + expiration: maybeApply(millisToSeconds, key.expiration), + // workerd expects metadata to be a JSON-serialised string + metadata: maybeApply(JSON.stringify, key.metadata) + })), result; + return res.cursor === void 0 ? result = { keys, list_complete: !0, cacheStatus: null } : result = { + keys, + list_complete: !1, + cursor: res.cursor, + cacheStatus: null + }, Response.json(result); + }; +}; +__decorateClass([ + GET("/:key") +], KVNamespaceObject.prototype, "get", 2), __decorateClass([ + PUT("/:key") +], KVNamespaceObject.prototype, "put", 2), __decorateClass([ + DELETE("/:key") +], KVNamespaceObject.prototype, "delete", 2), __decorateClass([ + GET("/") +], KVNamespaceObject.prototype, "list", 2); +export { + KVNamespaceObject +}; +//# sourceMappingURL=namespace.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js.map b/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js.map new file mode 100644 index 0000000..06a4d21 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/kv/namespace.worker.ts", "../../../../src/workers/kv/constants.ts", "../../../../src/workers/kv/validator.worker.ts"], + "mappings": ";;;;;;;;;AAAA,OAAO,YAAY;AACnB;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OACM;;;ACXP,SAAyB,mBAAmB;AAErC,IAAM,WAAW;AAAA,EACvB,eAAe;AAAA,EACf,eAAe;AAAA,EACf,cAAc;AAAA,EACd,gBAAgB,KAAK,OAAO;AAAA,EAC5B,qBAAqB;AAAA,EACrB,mBAAmB;AACpB,GAEa,WAAW;AAAA,EACvB,aAAa;AAAA,EACb,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,aAAa;AACd,GAEa,YAAY;AAAA,EACxB,YAAY;AAAA,EACZ,UAAU;AACX;;;ACxBA,SAAS,UAAAC,eAAc;AACvB,SAAS,iBAAiB;AAGnB,SAAS,UAAU,EAAE,IAAI,GAAoB,OAAwB;AAC3E,MAAI,MAAM,IAAI,SAAS,WAAW,GAAG,YAAY,MAAM;AAAQ,WAAO;AACtE,MAAI;AACH,WAAO,mBAAmB,GAAG;AAAA,EAC9B,SAAS,GAAP;AACD,UAAI,aAAa,WACV,IAAI,UAAU,KAAK,+BAA+B,IAElD;AAAA,EAER;AACD;AAEO,SAAS,YAAY,KAAmB;AAC9C,MAAI,QAAQ;AACX,UAAM,IAAI,UAAU,K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KAAK,QAAQ,OAAO,GAAG,GACtB,IAAI,SAAS;AAAA,EACrB;AAAA,EAGA,OAAqB,OAAO,KAAK,QAAQ,QAAQ;AAEhD,QAAM,UAAU,kBAAkB,GAAG;AACrC,wBAAoB,OAAO;AAG3B,QAAM,MAAM,MAAM,KAAK,QAAQ,KAAK,OAAO,GACrC,OAAO,IAAI,KAAK,IAAiC,CAAC,SAAS;AAAA,MAChE,MAAM,IAAI;AAAA,MACV,YAAY,WAAW,iBAAiB,IAAI,UAAU;AAAA;AAAA,MAEtD,UAAU,WAAW,KAAK,WAAW,IAAI,QAAQ;AAAA,IAClD,EAAE,GACE;AACJ,WAAI,IAAI,WAAW,SAClB,SAAS,EAAE,MAAM,eAAe,IAAM,aAAa,KAAK,IAExD,SAAS;AAAA,MACR;AAAA,MACA,eAAe;AAAA,MACf,QAAQ,IAAI;AAAA,MACZ,aAAa;AAAA,IACd,GAEM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACD;AAjJC;AAAA,EADC,IAAI,OAAO;AAAA,GAPA,kBAQZ,sBA2BA;AAAA,EADC,IAAI,OAAO;AAAA,GAlCA,kBAmCZ,sBAiFA;AAAA,EADC,OAAO,OAAO;AAAA,GAnHH,kBAoHZ,yBAWA;AAAA,EADC,IAAI,GAAG;AAAA,GA9HI,kBA+HZ;", + "names": ["HttpError", "Buffer", "Buffer", "HttpError"] +} diff --git a/node_modules/miniflare/dist/src/workers/kv/sites.worker.js b/node_modules/miniflare/dist/src/workers/kv/sites.worker.js new file mode 100644 index 0000000..a4ee8e3 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/kv/sites.worker.js @@ -0,0 +1,147 @@ +// src/workers/kv/sites.worker.ts +import { SharedBindings, base64Decode, base64Encode } from "miniflare:shared"; + +// src/workers/kv/constants.ts +import { testRegExps } from "miniflare:shared"; +var KVLimits = { + MIN_CACHE_TTL: 60, + MAX_LIST_KEYS: 1e3, + MAX_KEY_SIZE: 512, + MAX_VALUE_SIZE: 25 * 1024 * 1024, + MAX_VALUE_SIZE_TEST: 1024, + MAX_METADATA_SIZE: 1024 +}, KVParams = { + URL_ENCODED: "urlencoded", + CACHE_TTL: "cache_ttl", + EXPIRATION: "expiration", + EXPIRATION_TTL: "expiration_ttl", + LIST_LIMIT: "key_count_limit", + LIST_PREFIX: "prefix", + LIST_CURSOR: "cursor" +}; +var SiteBindings = { + KV_NAMESPACE_SITE: "__STATIC_CONTENT", + JSON_SITE_MANIFEST: "__STATIC_CONTENT_MANIFEST", + JSON_SITE_FILTER: "MINIFLARE_SITE_FILTER" +}, SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/"; +function encodeSitesKey(key) { + return SITES_NO_CACHE_PREFIX + encodeURIComponent(key); +} +function decodeSitesKey(key) { + return key.startsWith(SITES_NO_CACHE_PREFIX) ? decodeURIComponent(key.substring(SITES_NO_CACHE_PREFIX.length)) : key; +} +function deserialiseRegExps(matcher) { + return { + include: matcher.include.map((regExp) => new RegExp(regExp)), + exclude: matcher.exclude.map((regExp) => new RegExp(regExp)) + }; +} +function deserialiseSiteRegExps(siteRegExps) { + return { + include: siteRegExps.include && deserialiseRegExps(siteRegExps.include), + exclude: siteRegExps.exclude && deserialiseRegExps(siteRegExps.exclude) + }; +} +function testSiteRegExps(regExps, key) { + return regExps.include !== void 0 ? testRegExps(regExps.include, key) : regExps.exclude !== void 0 ? !testRegExps(regExps.exclude, key) : !0; +} + +// src/workers/kv/validator.worker.ts +import { Buffer } from "node:buffer"; +import { HttpError } from "miniflare:shared"; +function validateKeyLength(key) { + let keyLength = Buffer.byteLength(key); + if (keyLength > KVLimits.MAX_KEY_SIZE) + throw new HttpError( + 414, + `UTF-8 encoded length of ${keyLength} exceeds key length limit of ${KVLimits.MAX_KEY_SIZE}.` + ); +} +function decodeListOptions(url) { + let limitParam = url.searchParams.get(KVParams.LIST_LIMIT), limit = limitParam === null ? KVLimits.MAX_LIST_KEYS : parseInt(limitParam), prefix = url.searchParams.get(KVParams.LIST_PREFIX) ?? void 0, cursor = url.searchParams.get(KVParams.LIST_CURSOR) ?? void 0; + return { limit, prefix, cursor }; +} +function validateListOptions(options) { + let limit = options.limit; + if (limit !== void 0) { + if (isNaN(limit) || limit < 1) + throw new HttpError( + 400, + `Invalid ${KVParams.LIST_LIMIT} of ${limit}. Please specify an integer greater than 0.` + ); + if (limit > KVLimits.MAX_LIST_KEYS) + throw new HttpError( + 400, + `Invalid ${KVParams.LIST_LIMIT} of ${limit}. Please specify an integer less than ${KVLimits.MAX_LIST_KEYS}.` + ); + } + let prefix = options.prefix; + prefix != null && validateKeyLength(prefix); +} + +// src/workers/kv/sites.worker.ts +var siteRegExpsCache = /* @__PURE__ */ new WeakMap(); +function getSiteRegExps(env) { + let regExps = siteRegExpsCache.get(env); + return regExps !== void 0 || (regExps = deserialiseSiteRegExps(env[SiteBindings.JSON_SITE_FILTER]), siteRegExpsCache.set(env, regExps)), regExps; +} +async function* walkDirectory(blobsService, path = "") { + let res = await blobsService.fetch(`http://placeholder/${path}`); + if (!(res.headers.get("Content-Type") ?? "").toLowerCase().startsWith("application/json")) { + await res.body?.pipeTo(new WritableStream()), yield path; + return; + } + let entries = await res.json(); + for (let { name, type } of entries) { + let entryPath = `${path}${path === "" ? "" : "/"}${name}`; + type === "directory" ? yield* walkDirectory(blobsService, entryPath) : yield entryPath; + } +} +var encoder = new TextEncoder(); +function arrayCompare(a, b) { + let minLength = Math.min(a.length, b.length); + for (let i = 0; i < minLength; i++) { + let aElement = a[i], bElement = b[i]; + if (aElement < bElement) + return -1; + if (aElement > bElement) + return 1; + } + return a.length - b.length; +} +async function handleListRequest(url, blobsService, siteRegExps) { + let options = decodeListOptions(url); + validateListOptions(options); + let { limit = KVLimits.MAX_LIST_KEYS, prefix, cursor } = options, keys = []; + for await (let name of walkDirectory(blobsService)) + testSiteRegExps(siteRegExps, name) && (name = encodeSitesKey(name), !(prefix !== void 0 && !name.startsWith(prefix)) && keys.push({ name, encodedName: encoder.encode(name) })); + keys.sort((a, b) => arrayCompare(a.encodedName, b.encodedName)); + for (let key of keys) + delete key.encodedName; + let startAfter = cursor === void 0 ? "" : base64Decode(cursor), startIndex = 0; + startAfter !== "" && (startIndex = keys.findIndex(({ name }) => name === startAfter), startIndex === -1 && (startIndex = keys.length), startIndex++); + let endIndex = startIndex + limit, nextCursor = endIndex < keys.length ? base64Encode(keys[endIndex - 1].name) : void 0; + return keys = keys.slice(startIndex, endIndex), nextCursor === void 0 ? Response.json({ keys, list_complete: !0 }) : Response.json({ keys, list_complete: !1, cursor: nextCursor }); +} +var sites_worker_default = { + async fetch(request, env) { + if (request.method !== "GET") { + let message = `Cannot ${request.method.toLowerCase()}() with Workers Sites namespace`; + return new Response(message, { status: 405, statusText: message }); + } + let url = new URL(request.url), key = url.pathname.substring(1); + url.searchParams.get(KVParams.URL_ENCODED)?.toLowerCase() === "true" && (key = decodeURIComponent(key)), key = decodeSitesKey(key); + let siteRegExps = getSiteRegExps(env); + if (key !== "" && !testSiteRegExps(siteRegExps, key)) + return new Response("Not Found", { + status: 404, + statusText: "Not Found" + }); + let blobsService = env[SharedBindings.MAYBE_SERVICE_BLOBS]; + return key === "" ? handleListRequest(url, blobsService, siteRegExps) : blobsService.fetch(new URL(key, "http://placeholder")); + } +}; +export { + sites_worker_default as default +}; +//# sourceMappingURL=sites.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/kv/sites.worker.js.map b/node_modules/miniflare/dist/src/workers/kv/sites.worker.js.map new file mode 100644 index 0000000..8573b4a --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/kv/sites.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/kv/sites.worker.ts", "../../../../src/workers/kv/constants.ts", "../../../../src/workers/kv/validator.worker.ts"], + "mappings": ";AAAA,SAAS,gBAAgB,cAAc,oBAAoB;;;ACA3D,SAAyB,mBAAmB;AAErC,IAAM,WAAW;AAAA,EACvB,eAAe;AAAA,EACf,eAAe;AAAA,EACf,cAAc;AAAA,EAC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AAK,EAAE,MAAM,eAAe,GAAK,CAAC,IAE3C,SAAS,KAAK,EAAE,MAAM,eAAe,IAAO,QAAQ,WAAW,CAAC;AAEzE;AAEA,IAAO,uBAA8B;AAAA,EACpC,MAAM,MAAM,SAAS,KAAK;AAEzB,QAAI,QAAQ,WAAW,OAAO;AAC7B,UAAM,UAAU,UAAU,QAAQ,OAAO,YAAY;AACrD,aAAO,IAAI,SAAS,SAAS,EAAE,QAAQ,KAAK,YAAY,QAAQ,CAAC;AAAA,IAClE;AAGA,QAAM,MAAM,IAAI,IAAI,QAAQ,GAAG,GAC3B,MAAM,IAAI,SAAS,UAAU,CAAC;AAClC,IAAI,IAAI,aAAa,IAAI,SAAS,WAAW,GAAG,YAAY,MAAM,WACjE,MAAM,mBAAmB,GAAG,IAI7B,MAAM,eAAe,GAAG;AAGxB,QAAM,cAAc,eAAe,GAAG;AACtC,QAAI,QAAQ,MAAM,CAAC,gBAAgB,aAAa,GAAG;AAClD,aAAO,IAAI,SAAS,aAAa;AAAA,QAChC,QAAQ;AAAA,QACR,YAAY;AAAA,MACb,CAAC;AAGF,QAAM,eAAe,IAAI,eAAe,mBAAmB;AAC3D,WAAI,QAAQ,KACJ,kBAAkB,KAAK,cAAc,WAAW,IAEhD,aAAa,MAAM,IAAI,IAAI,KAAK,oBAAoB,CAAC;AAAA,EAE9D;AACD;", + "names": [] +} diff --git a/node_modules/miniflare/dist/src/workers/queues/broker.worker.js b/node_modules/miniflare/dist/src/workers/queues/broker.worker.js new file mode 100644 index 0000000..3d06df8 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/queues/broker.worker.js @@ -0,0 +1,284 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __decorateClass = (decorators, target, key, kind) => { + for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--) + (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result); + return kind && result && __defProp(target, key, result), result; +}; + +// src/workers/queues/broker.worker.ts +import assert from "node:assert"; +import { Buffer as Buffer2 } from "node:buffer"; + +// ../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs +var FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY = !0; +typeof process < "u" && ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}, isTTY = process.stdout && process.stdout.isTTY); +var $ = { + enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY) +}; +function init(x, y) { + let rgx = new RegExp(`\\x1b\\[${y}m`, "g"), open = `\x1B[${x}m`, close = `\x1B[${y}m`; + return function(txt) { + return !$.enabled || txt == null ? txt : open + (~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close; + }; +} +var reset = init(0, 0), bold = init(1, 22), dim = init(2, 22), italic = init(3, 23), underline = init(4, 24), inverse = init(7, 27), hidden = init(8, 28), strikethrough = init(9, 29), black = init(30, 39), red = init(31, 39), green = init(32, 39), yellow = init(33, 39), blue = init(34, 39), magenta = init(35, 39), cyan = init(36, 39), white = init(37, 39), gray = init(90, 39), grey = init(90, 39), bgBlack = init(40, 49), bgRed = init(41, 49), bgGreen = init(42, 49), bgYellow = init(43, 49), bgBlue = init(44, 49), bgMagenta = init(45, 49), bgCyan = init(46, 49), bgWhite = init(47, 49); + +// src/workers/queues/broker.worker.ts +import { + HttpError, + LogLevel, + MiniflareDurableObject, + POST, + SharedBindings, + viewToBuffer +} from "miniflare:shared"; + +// src/workers/queues/constants.ts +var QueueBindings = { + SERVICE_WORKER_PREFIX: "MINIFLARE_WORKER_", + MAYBE_JSON_QUEUE_PRODUCERS: "MINIFLARE_QUEUE_PRODUCERS", + MAYBE_JSON_QUEUE_CONSUMERS: "MINIFLARE_QUEUE_CONSUMERS" +}; + +// src/workers/queues/schemas.ts +import { Base64DataSchema, z } from "miniflare:zod"; +var QueueMessageDelaySchema = z.number().int().min(0).max(43200).optional(), QueueProducerOptionsSchema = /* @__PURE__ */ z.object({ + // https://developers.cloudflare.com/queues/platform/configuration/#producer + queueName: z.string(), + deliveryDelay: QueueMessageDelaySchema +}), QueueProducerSchema = /* @__PURE__ */ z.intersection( + QueueProducerOptionsSchema, + z.object({ workerName: z.string() }) +), QueueProducersSchema = /* @__PURE__ */ z.record(QueueProducerSchema), QueueConsumerOptionsSchema = /* @__PURE__ */ z.object({ + // https://developers.cloudflare.com/queues/platform/configuration/#consumer + // https://developers.cloudflare.com/queues/platform/limits/ + maxBatchSize: z.number().min(0).max(100).optional(), + maxBatchTimeout: z.number().min(0).max(30).optional(), + // seconds + maxRetires: z.number().min(0).max(100).optional(), + deadLetterQueue: z.ostring(), + retryDelay: QueueMessageDelaySchema +}), QueueConsumerSchema = /* @__PURE__ */ z.intersection( + QueueConsumerOptionsSchema, + z.object({ workerName: z.string() }) +), QueueConsumersSchema = /* @__PURE__ */ z.record(QueueConsumerSchema), QueueContentTypeSchema = /* @__PURE__ */ z.enum(["text", "json", "bytes", "v8"]).default("v8"), QueueIncomingMessageSchema = /* @__PURE__ */ z.object({ + contentType: QueueContentTypeSchema, + delaySecs: QueueMessageDelaySchema, + body: Base64DataSchema, + // When enqueuing messages on dead-letter queues, we want to reuse the same ID + // and timestamp + id: z.ostring(), + timestamp: z.onumber() +}), QueuesBatchRequestSchema = /* @__PURE__ */ z.object({ + messages: z.array(QueueIncomingMessageSchema) +}); + +// src/workers/queues/broker.worker.ts +var MAX_MESSAGE_SIZE_BYTES = 128 * 1e3, MAX_MESSAGE_BATCH_COUNT = 100, MAX_MESSAGE_BATCH_SIZE = (256 + 32) * 1e3, DEFAULT_BATCH_SIZE = 5, DEFAULT_BATCH_TIMEOUT = 1, DEFAULT_RETRIES = 2, exceptionQueueResponse = { + outcome: "exception", + retryBatch: { retry: !1 }, + ackAll: !1, + retryMessages: [], + explicitAcks: [] +}, PayloadTooLargeError = class extends HttpError { + constructor(message) { + super(413, message); + } +}; +function validateMessageSize(headers) { + let size = headers.get("Content-Length"); + if (size !== null && parseInt(size) > MAX_MESSAGE_SIZE_BYTES) + throw new PayloadTooLargeError( + `message length of ${size} bytes exceeds limit of ${MAX_MESSAGE_SIZE_BYTES}` + ); +} +function validateContentType(headers) { + let format = headers.get("X-Msg-Fmt") ?? void 0, result = QueueContentTypeSchema.safeParse(format); + if (!result.success) + throw new HttpError( + 400, + `message content type ${format} is invalid; if specified, must be one of 'text', 'json', 'bytes', or 'v8'` + ); + return result.data; +} +function validateMessageDelay(headers) { + let format = headers.get("X-Msg-Delay-Secs"); + if (!format) + return; + let result = QueueMessageDelaySchema.safeParse(Number(format)); + if (!result.success) + throw new HttpError( + 400, + `message delay ${format} is invalid: ${result.error}` + ); + return result.data; +} +function validateBatchSize(headers) { + let count = headers.get("CF-Queue-Batch-Count"); + if (count !== null && parseInt(count) > MAX_MESSAGE_BATCH_COUNT) + throw new PayloadTooLargeError( + `batch message count of ${count} exceeds limit of ${MAX_MESSAGE_BATCH_COUNT}` + ); + let largestSize = headers.get("CF-Queue-Largest-Msg"); + if (largestSize !== null && parseInt(largestSize) > MAX_MESSAGE_SIZE_BYTES) + throw new PayloadTooLargeError( + `message in batch has length ${largestSize} bytes which exceeds single message size limit of ${MAX_MESSAGE_SIZE_BYTES}` + ); + let batchSize = headers.get("CF-Queue-Batch-Bytes"); + if (batchSize !== null && parseInt(batchSize) > MAX_MESSAGE_BATCH_SIZE) + throw new PayloadTooLargeError( + `batch size of ${batchSize} bytes exceeds limit of 256000` + ); +} +function deserialise({ contentType, body }) { + return contentType === "text" ? { contentType, body: body.toString() } : contentType === "json" ? { contentType, body: JSON.parse(body.toString()) } : contentType === "bytes" ? { contentType, body: viewToBuffer(body) } : { contentType, body }; +} +function serialise(msg) { + let body; + return msg.body.contentType === "text" ? body = Buffer2.from(msg.body.body) : msg.body.contentType === "json" ? body = Buffer2.from(JSON.stringify(msg.body.body)) : msg.body.contentType === "bytes" ? body = Buffer2.from(msg.body.body) : body = msg.body.body, { + id: msg.id, + timestamp: msg.timestamp.getTime(), + contentType: msg.body.contentType, + body: body.toString("base64") + }; +} +var QueueMessage = class { + constructor(id, timestamp, body) { + this.id = id; + this.timestamp = timestamp; + this.body = body; + } + #failedAttempts = 0; + incrementFailedAttempts() { + return ++this.#failedAttempts; + } + get failedAttempts() { + return this.#failedAttempts; + } +}; +function formatQueueResponse(queueName, acked, total, time) { + let colour; + acked === total ? colour = green : acked > 0 ? colour = yellow : colour = red; + let message = `${bold("QUEUE")} ${queueName} ${colour(`${acked}/${total}`)}`; + return time !== void 0 && (message += grey(` (${time}ms)`)), reset(message); +} +var QueueBrokerObject = class extends MiniflareDurableObject { + #producers; + #consumers; + #messages = []; + #pendingFlush; + constructor(state, env) { + super(state, env); + let maybeProducers = env[QueueBindings.MAYBE_JSON_QUEUE_PRODUCERS]; + maybeProducers === void 0 ? this.#producers = {} : this.#producers = QueueProducersSchema.parse(maybeProducers); + let maybeConsumers = env[QueueBindings.MAYBE_JSON_QUEUE_CONSUMERS]; + maybeConsumers === void 0 ? this.#consumers = {} : this.#consumers = QueueConsumersSchema.parse(maybeConsumers); + } + get #maybeProducer() { + return this.#producers[this.name]; + } + get #maybeConsumer() { + return this.#consumers[this.name]; + } + #dispatchBatch(workerName, batch) { + let bindingName = `${QueueBindings.SERVICE_WORKER_PREFIX}${workerName}`, maybeService = this.env[bindingName]; + assert( + maybeService !== void 0, + `Expected ${bindingName} service binding` + ); + let messages = batch.map(({ id, timestamp, body, failedAttempts }) => { + let attempts = failedAttempts + 1; + return body.contentType === "v8" ? { id, timestamp, serializedBody: body.body, attempts } : { id, timestamp, body: body.body, attempts }; + }); + return maybeService.queue(this.name, messages); + } + #flush = async () => { + let consumer = this.#maybeConsumer; + assert(consumer !== void 0); + let batchSize = consumer.maxBatchSize ?? DEFAULT_BATCH_SIZE, maxAttempts = (consumer.maxRetires ?? DEFAULT_RETRIES) + 1, maxAttemptsS = maxAttempts === 1 ? "" : "s", batch = this.#messages.splice(0, batchSize), startTime = Date.now(), endTime, response; + try { + response = await this.#dispatchBatch(consumer.workerName, batch), endTime = Date.now(); + } catch (e) { + endTime = Date.now(), await this.logWithLevel(LogLevel.ERROR, String(e)), response = exceptionQueueResponse; + } + let retryAll = response.retryBatch.retry || response.outcome !== "ok", retryMessages = new Map(response.retryMessages?.map((r) => [r.msgId, r.delaySeconds])), globalDelay = response.retryBatch.delaySeconds ?? consumer.retryDelay ?? 0, failedMessages = 0, toDeadLetterQueue = []; + for (let message of batch) + if (retryAll || retryMessages.has(message.id)) + if (failedMessages++, message.incrementFailedAttempts() < maxAttempts) { + await this.logWithLevel( + LogLevel.DEBUG, + `Retrying message "${message.id}" on queue "${this.name}"...` + ); + let fn = () => { + this.#messages.push(message), this.#ensurePendingFlush(); + }, delay = retryMessages.get(message.id) ?? globalDelay; + this.timers.setTimeout(fn, delay * 1e3); + } else + consumer.deadLetterQueue !== void 0 ? (await this.logWithLevel( + LogLevel.WARN, + `Moving message "${message.id}" on queue "${this.name}" to dead letter queue "${consumer.deadLetterQueue}" after ${maxAttempts} failed attempt${maxAttemptsS}...` + ), toDeadLetterQueue.push(message)) : await this.logWithLevel( + LogLevel.WARN, + `Dropped message "${message.id}" on queue "${this.name}" after ${maxAttempts} failed attempt${maxAttemptsS}!` + ); + let acked = batch.length - failedMessages; + if (await this.logWithLevel( + LogLevel.INFO, + formatQueueResponse(this.name, acked, batch.length, endTime - startTime) + ), this.#pendingFlush = void 0, this.#messages.length > 0 && this.#ensurePendingFlush(), toDeadLetterQueue.length > 0) { + let name = consumer.deadLetterQueue; + assert(name !== void 0); + let ns = this.env[SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT], id = ns.idFromName(name), stub = ns.get(id), cf = { miniflare: { name } }, batchRequest = { + messages: toDeadLetterQueue.map(serialise) + }, res = await stub.fetch("http://placeholder/batch", { + method: "POST", + body: JSON.stringify(batchRequest), + cf + }); + assert(res.ok); + } + }; + #ensurePendingFlush() { + let consumer = this.#maybeConsumer; + assert(consumer !== void 0); + let batchSize = consumer.maxBatchSize ?? DEFAULT_BATCH_SIZE, batchTimeout = consumer.maxBatchTimeout ?? DEFAULT_BATCH_TIMEOUT, batchHasSpace = this.#messages.length < batchSize; + if (this.#pendingFlush !== void 0) { + if (this.#pendingFlush.immediate || batchHasSpace) + return; + this.timers.clearTimeout(this.#pendingFlush.timeout), this.#pendingFlush = void 0; + } + let delay = batchHasSpace ? batchTimeout * 1e3 : 0, timeout = this.timers.setTimeout(this.#flush, delay); + this.#pendingFlush = { immediate: delay === 0, timeout }; + } + #enqueue(messages, globalDelay = 0) { + for (let message of messages) { + let randomness = crypto.getRandomValues(new Uint8Array(16)), id = message.id ?? Buffer2.from(randomness).toString("hex"), timestamp = new Date(message.timestamp ?? this.timers.now()), body = deserialise(message), msg = new QueueMessage(id, timestamp, body), fn = () => { + this.#messages.push(msg), this.#ensurePendingFlush(); + }, delay = message.delaySecs ?? globalDelay; + this.timers.setTimeout(fn, delay * 1e3); + } + } + message = async (req) => { + validateMessageSize(req.headers); + let contentType = validateContentType(req.headers), delay = validateMessageDelay(req.headers), body = Buffer2.from(await req.arrayBuffer()); + return this.#maybeConsumer === void 0 ? new Response() : (this.#enqueue( + [{ contentType, delaySecs: delay, body }], + this.#maybeProducer?.deliveryDelay + ), new Response()); + }; + batch = async (req) => { + validateBatchSize(req.headers); + let delay = validateMessageDelay(req.headers) ?? this.#maybeProducer?.deliveryDelay, body = QueuesBatchRequestSchema.parse(await req.json()); + return this.#maybeConsumer === void 0 ? new Response() : (this.#enqueue(body.messages, delay), new Response()); + }; +}; +__decorateClass([ + POST("/message") +], QueueBrokerObject.prototype, "message", 2), __decorateClass([ + POST("/batch") +], QueueBrokerObject.prototype, "batch", 2); +export { + QueueBrokerObject +}; +//# sourceMappingURL=broker.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/queues/broker.worker.js.map b/node_modules/miniflare/dist/src/workers/queues/broker.worker.js.map new file mode 100644 index 0000000..24f9037 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/queues/broker.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/queues/broker.worker.ts", "../../../../../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs", "../../../../src/workers/queues/constants.ts", "../../../../src/workers/queues/schemas.ts"], + "mappings": ";;;;;;;;;AAAA,OAAO,YAAY;AACnB,SAAS,UAAAA,eAAc;;;ACDvB,IAAI,aAAa,qBAAqB,UAAU,MAAM,QAAM;AACxD,OAAO,UAAY,QACrB,EAAE,aAAa,qBAAqB,UAAU,KAAK,IAAI,QAAQ,OAAO,CAAC,GACxE,QAAQ,QAAQ,UAAU,QAAQ,OAAO;AAGnC,IAAM,IAAI;AAAA,EAChB,SAAS,CAAC,uBAAuB,YAAY,QAAQ,SAAS,WAC7D,eAAe,QAAQ,gBAAgB,OAAO;AAEhD;AAEA,SAAS,KAAK,GAAG,GAAG;AACnB,MAAI,MAAM,IAAI,OAAO,WAAW,MAAM,GAAG,GACrC,OAAO,QAAQ,MAAM,QAAQ,QAAQ;AAEzC,SAAO,SAAU,KAAK;AACrB,WAAI,CAAC,EAAE,WAAW,OAAO,OAAa,MAC/B,QAAU,EAAE,KAAG,KAAK,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,QAAQ,IAAI,IAAI,OAAO;AAAA,EACrF;AACD;AAGO,IAAM,QAAQ,KAAK,GAAG,CAAC,GACjB,OAAO,KAAK,GAAG,EAAE,GACjB,MAAM,KAAK,GAAG,EAAE,GAChB,SAAS,KAAK,GAAG,EAAE,GACnB,YAAY,KAAK,GAAG,EAAE,GACtB,UAAU,KAAK,GAAG,EAAE,GACpB,SAAS,KAAK,GAAG,EAAE,GACnB,gBAAgB,KAAK,GAAG,EAAE,GAG1B,QAAQ,KAAK,IAAI,EAAE,GACnB,MAAM,KAAK,IAAI,EAAE,GACjB,QAAQ,KAAK,IAA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IAAI,YAAY,CAAC;AAIhD,WADiB,KAAK,mBACL,SAAkB,IAAI,SAAS,KAEhD,KAAK;AAAA,MACJ,CAAC,EAAE,aAAa,WAAW,OAAO,KAAK,CAAC;AAAA,MACxC,KAAK,gBAAgB;AAAA,IACtB,GACO,IAAI,SAAS;AAAA,EACrB;AAAA,EAGA,QAAsB,OAAO,QAAQ;AAKpC,sBAAkB,IAAI,OAAO;AAC7B,QAAM,QAAQ,qBAAqB,IAAI,OAAO,KAAK,KAAK,gBAAgB,eAClE,OAAO,yBAAyB,MAAM,MAAM,IAAI,KAAK,CAAC;AAI5D,WADiB,KAAK,mBACL,SAAkB,IAAI,SAAS,KAEhD,KAAK,SAAS,KAAK,UAAU,KAAK,GAC3B,IAAI,SAAS;AAAA,EACrB;AACD;AAlCC;AAAA,EADC,KAAK,UAAU;AAAA,GAjLJ,kBAkLZ,0BAkBA;AAAA,EADC,KAAK,QAAQ;AAAA,GAnMF,kBAoMZ;", + "names": ["Buffer", "Buffer"] +} diff --git a/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js b/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js new file mode 100644 index 0000000..7f1a7e4 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js @@ -0,0 +1,1157 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __decorateClass = (decorators, target, key, kind) => { + for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--) + (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result); + return kind && result && __defProp(target, key, result), result; +}; + +// src/workers/r2/bucket.worker.ts +import assert2 from "node:assert"; +import { Buffer as Buffer3 } from "node:buffer"; +import { createHash } from "node:crypto"; +import { + DeferredPromise, + GET, + MiniflareDurableObject, + PUT, + WaitGroup, + all, + base64Decode, + base64Encode, + get, + maybeApply, + readPrefix +} from "miniflare:shared"; + +// src/workers/r2/constants.ts +var R2Limits = { + MAX_LIST_KEYS: 1e3, + MAX_KEY_SIZE: 1024, + // https://developers.cloudflare.com/r2/platform/limits/ + MAX_VALUE_SIZE: 5363466240, + // 5 GiB - 5 MiB + MAX_METADATA_SIZE: 2048, + // 2048 B + MIN_MULTIPART_PART_SIZE: 5242880, + MIN_MULTIPART_PART_SIZE_TEST: 50 +}, R2Headers = { + ERROR: "cf-r2-error", + REQUEST: "cf-r2-request", + METADATA_SIZE: "cf-r2-metadata-size" +}; + +// src/workers/r2/errors.worker.ts +import { HttpError } from "miniflare:shared"; +var R2ErrorCode = { + INTERNAL_ERROR: 10001, + NO_SUCH_OBJECT_KEY: 10007, + ENTITY_TOO_LARGE: 100100, + ENTITY_TOO_SMALL: 10011, + METADATA_TOO_LARGE: 10012, + INVALID_OBJECT_NAME: 10020, + INVALID_MAX_KEYS: 10022, + NO_SUCH_UPLOAD: 10024, + INVALID_PART: 10025, + INVALID_ARGUMENT: 10029, + PRECONDITION_FAILED: 10031, + BAD_DIGEST: 10037, + INVALID_RANGE: 10039, + BAD_UPLOAD: 10048 +}, R2Error = class extends HttpError { + constructor(code, message, v4Code) { + super(code, message); + this.v4Code = v4Code; + } + object; + toResponse() { + if (this.object !== void 0) { + let { metadataSize, value } = this.object.encode(); + return new Response(value, { + status: this.code, + headers: { + [R2Headers.METADATA_SIZE]: `${metadataSize}`, + "Content-Type": "application/json", + [R2Headers.ERROR]: JSON.stringify({ + message: this.message, + version: 1, + // Note the lowercase 'c', which the runtime expects + v4code: this.v4Code + }) + } + }); + } + return new Response(null, { + status: this.code, + headers: { + [R2Headers.ERROR]: JSON.stringify({ + message: this.message, + version: 1, + // Note the lowercase 'c', which the runtime expects + v4code: this.v4Code + }) + } + }); + } + context(info) { + return this.message += ` (${info})`, this; + } + attach(object) { + return this.object = object, this; + } +}, InvalidMetadata = class extends R2Error { + constructor() { + super(400, "Metadata missing or invalid", R2ErrorCode.INVALID_ARGUMENT); + } +}, InternalError = class extends R2Error { + constructor() { + super( + 500, + "We encountered an internal error. Please try again.", + R2ErrorCode.INTERNAL_ERROR + ); + } +}, NoSuchKey = class extends R2Error { + constructor() { + super( + 404, + "The specified key does not exist.", + R2ErrorCode.NO_SUCH_OBJECT_KEY + ); + } +}, EntityTooLarge = class extends R2Error { + constructor() { + super( + 400, + "Your proposed upload exceeds the maximum allowed object size.", + R2ErrorCode.ENTITY_TOO_LARGE + ); + } +}, EntityTooSmall = class extends R2Error { + constructor() { + super( + 400, + "Your proposed upload is smaller than the minimum allowed object size.", + R2ErrorCode.ENTITY_TOO_SMALL + ); + } +}, MetadataTooLarge = class extends R2Error { + constructor() { + super( + 400, + "Your metadata headers exceed the maximum allowed metadata size.", + R2ErrorCode.METADATA_TOO_LARGE + ); + } +}, BadDigest = class extends R2Error { + constructor(algorithm, provided, calculated) { + super( + 400, + [ + `The ${algorithm} checksum you specified did not match what we received.`, + `You provided a ${algorithm} checksum with value: ${provided.toString( + "hex" + )}`, + `Actual ${algorithm} was: ${calculated.toString("hex")}` + ].join(` +`), + R2ErrorCode.BAD_DIGEST + ); + } +}, InvalidObjectName = class extends R2Error { + constructor() { + super( + 400, + "The specified object name is not valid.", + R2ErrorCode.INVALID_OBJECT_NAME + ); + } +}, InvalidMaxKeys = class extends R2Error { + constructor() { + super( + 400, + "MaxKeys params must be positive integer <= 1000.", + R2ErrorCode.INVALID_MAX_KEYS + ); + } +}, NoSuchUpload = class extends R2Error { + constructor() { + super( + 400, + "The specified multipart upload does not exist.", + R2ErrorCode.NO_SUCH_UPLOAD + ); + } +}, InvalidPart = class extends R2Error { + constructor() { + super( + 400, + "One or more of the specified parts could not be found.", + R2ErrorCode.INVALID_PART + ); + } +}, PreconditionFailed = class extends R2Error { + constructor() { + super( + 412, + "At least one of the pre-conditions you specified did not hold.", + R2ErrorCode.PRECONDITION_FAILED + ); + } +}, InvalidRange = class extends R2Error { + constructor() { + super( + 416, + "The requested range is not satisfiable", + R2ErrorCode.INVALID_RANGE + ); + } +}, BadUpload = class extends R2Error { + constructor() { + super( + 500, + "There was a problem with the multipart upload.", + R2ErrorCode.BAD_UPLOAD + ); + } +}; + +// src/workers/r2/r2Object.worker.ts +import { HEX_REGEXP } from "miniflare:zod"; +var InternalR2Object = class { + key; + version; + size; + etag; + uploaded; + httpMetadata; + customMetadata; + range; + checksums; + constructor(row, range) { + this.key = row.key, this.version = row.version, this.size = row.size, this.etag = row.etag, this.uploaded = row.uploaded, this.httpMetadata = JSON.parse(row.http_metadata), this.customMetadata = JSON.parse(row.custom_metadata), this.range = range; + let checksums = JSON.parse(row.checksums); + this.etag.length === 32 && HEX_REGEXP.test(this.etag) && (checksums.md5 = row.etag), this.checksums = checksums; + } + // Format for return to the Workers Runtime + #rawProperties() { + return { + name: this.key, + version: this.version, + size: this.size, + etag: this.etag, + uploaded: this.uploaded, + httpFields: this.httpMetadata, + customFields: Object.entries(this.customMetadata).map(([k, v]) => ({ + k, + v + })), + range: this.range, + checksums: { + 0: this.checksums.md5, + 1: this.checksums.sha1, + 2: this.checksums.sha256, + 3: this.checksums.sha384, + 4: this.checksums.sha512 + } + }; + } + encode() { + let json = JSON.stringify(this.#rawProperties()), blob = new Blob([json]); + return { metadataSize: blob.size, value: blob.stream(), size: blob.size }; + } + static encodeMultiple(objects) { + let json = JSON.stringify({ + ...objects, + objects: objects.objects.map((o) => o.#rawProperties()) + }), blob = new Blob([json]); + return { metadataSize: blob.size, value: blob.stream(), size: blob.size }; + } +}, InternalR2ObjectBody = class extends InternalR2Object { + constructor(metadata, body, range) { + super(metadata, range); + this.body = body; + } + encode() { + let { metadataSize, value: metadata } = super.encode(), size = this.range?.length ?? this.size, identity2 = new FixedLengthStream(size + metadataSize); + return metadata.pipeTo(identity2.writable, { preventClose: !0 }).then(() => this.body.pipeTo(identity2.writable)), { + metadataSize, + value: identity2.readable, + size + }; + } +}; + +// src/workers/r2/schemas.worker.ts +import { Base64DataSchema, HexDataSchema, z } from "miniflare:zod"; +var MultipartUploadState = { + IN_PROGRESS: 0, + COMPLETED: 1, + ABORTED: 2 +}, SQL_SCHEMA = ` +CREATE TABLE IF NOT EXISTS _mf_objects ( + key TEXT PRIMARY KEY, + blob_id TEXT, + version TEXT NOT NULL, + size INTEGER NOT NULL, + etag TEXT NOT NULL, + uploaded INTEGER NOT NULL, + checksums TEXT NOT NULL, + http_metadata TEXT NOT NULL, + custom_metadata TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS _mf_multipart_uploads ( + upload_id TEXT PRIMARY KEY, + key TEXT NOT NULL, + http_metadata TEXT NOT NULL, + custom_metadata TEXT NOT NULL, + state TINYINT DEFAULT 0 NOT NULL +); +CREATE TABLE IF NOT EXISTS _mf_multipart_parts ( + upload_id TEXT NOT NULL REFERENCES _mf_multipart_uploads(upload_id), + part_number INTEGER NOT NULL, + blob_id TEXT NOT NULL, + size INTEGER NOT NULL, + etag TEXT NOT NULL, + checksum_md5 TEXT NOT NULL, + object_key TEXT REFERENCES _mf_objects(key) DEFERRABLE INITIALLY DEFERRED, + PRIMARY KEY (upload_id, part_number) +); +`, DateSchema = z.coerce.number().transform((value) => new Date(value)), RecordSchema = z.object({ + k: z.string(), + v: z.string() +}).array().transform( + (entries) => Object.fromEntries(entries.map(({ k, v }) => [k, v])) +), R2RangeSchema = z.object({ + offset: z.coerce.number().optional(), + length: z.coerce.number().optional(), + suffix: z.coerce.number().optional() +}), R2EtagSchema = z.discriminatedUnion("type", [ + z.object({ type: z.literal("strong"), value: z.string() }), + z.object({ type: z.literal("weak"), value: z.string() }), + z.object({ type: z.literal("wildcard") }) +]), R2EtagMatchSchema = R2EtagSchema.array().min(1).optional(), R2ConditionalSchema = z.object({ + // Performs the operation if the object's ETag matches the given string + etagMatches: R2EtagMatchSchema, + // "If-Match" + // Performs the operation if the object's ETag does NOT match the given string + etagDoesNotMatch: R2EtagMatchSchema, + // "If-None-Match" + // Performs the operation if the object was uploaded BEFORE the given date + uploadedBefore: DateSchema.optional(), + // "If-Unmodified-Since" + // Performs the operation if the object was uploaded AFTER the given date + uploadedAfter: DateSchema.optional(), + // "If-Modified-Since" + // Truncates dates to seconds before performing comparisons + secondsGranularity: z.oboolean() +}), R2ChecksumsSchema = z.object({ + 0: HexDataSchema.optional(), + 1: HexDataSchema.optional(), + 2: HexDataSchema.optional(), + 3: HexDataSchema.optional(), + 4: HexDataSchema.optional() +}).transform((checksums) => ({ + md5: checksums[0], + sha1: checksums[1], + sha256: checksums[2], + sha384: checksums[3], + sha512: checksums[4] +})), R2PublishedPartSchema = z.object({ + etag: z.string(), + part: z.number() +}), R2HttpFieldsSchema = z.object({ + contentType: z.ostring(), + contentLanguage: z.ostring(), + contentDisposition: z.ostring(), + contentEncoding: z.ostring(), + cacheControl: z.ostring(), + cacheExpiry: z.coerce.number().optional() +}), R2HeadRequestSchema = z.object({ + method: z.literal("head"), + object: z.string() +}), R2GetRequestSchema = z.object({ + method: z.literal("get"), + object: z.string(), + // Specifies that only a specific length (from an optional offset) or suffix + // of bytes from the object should be returned. Refer to + // https://developers.cloudflare.com/r2/runtime-apis/#ranged-reads. + range: R2RangeSchema.optional(), + rangeHeader: z.ostring(), + // Specifies that the object should only be returned given satisfaction of + // certain conditions in the R2Conditional. Refer to R2Conditional above. + onlyIf: R2ConditionalSchema.optional() +}), R2PutRequestSchema = z.object({ + method: z.literal("put"), + object: z.string(), + customFields: RecordSchema.optional(), + // (renamed in transform) + httpFields: R2HttpFieldsSchema.optional(), + // (renamed in transform) + onlyIf: R2ConditionalSchema.optional(), + md5: Base64DataSchema.optional(), + // (intentionally base64, not hex) + sha1: HexDataSchema.optional(), + sha256: HexDataSchema.optional(), + sha384: HexDataSchema.optional(), + sha512: HexDataSchema.optional() +}).transform((value) => ({ + method: value.method, + object: value.object, + customMetadata: value.customFields, + httpMetadata: value.httpFields, + onlyIf: value.onlyIf, + md5: value.md5, + sha1: value.sha1, + sha256: value.sha256, + sha384: value.sha384, + sha512: value.sha512 +})), R2CreateMultipartUploadRequestSchema = z.object({ + method: z.literal("createMultipartUpload"), + object: z.string(), + customFields: RecordSchema.optional(), + // (renamed in transform) + httpFields: R2HttpFieldsSchema.optional() + // (renamed in transform) +}).transform((value) => ({ + method: value.method, + object: value.object, + customMetadata: value.customFields, + httpMetadata: value.httpFields +})), R2UploadPartRequestSchema = z.object({ + method: z.literal("uploadPart"), + object: z.string(), + uploadId: z.string(), + partNumber: z.number() +}), R2CompleteMultipartUploadRequestSchema = z.object({ + method: z.literal("completeMultipartUpload"), + object: z.string(), + uploadId: z.string(), + parts: R2PublishedPartSchema.array() +}), R2AbortMultipartUploadRequestSchema = z.object({ + method: z.literal("abortMultipartUpload"), + object: z.string(), + uploadId: z.string() +}), R2ListRequestSchema = z.object({ + method: z.literal("list"), + limit: z.onumber(), + prefix: z.ostring(), + cursor: z.ostring(), + delimiter: z.ostring(), + startAfter: z.ostring(), + include: z.union([z.literal(0), z.literal(1)]).transform((value) => value === 0 ? "httpMetadata" : "customMetadata").array().optional() +}), R2DeleteRequestSchema = z.intersection( + z.object({ method: z.literal("delete") }), + z.union([ + z.object({ object: z.string() }), + z.object({ objects: z.string().array() }) + ]) +), R2BindingRequestSchema = z.union([ + R2HeadRequestSchema, + R2GetRequestSchema, + R2PutRequestSchema, + R2CreateMultipartUploadRequestSchema, + R2UploadPartRequestSchema, + R2CompleteMultipartUploadRequestSchema, + R2AbortMultipartUploadRequestSchema, + R2ListRequestSchema, + R2DeleteRequestSchema +]); + +// src/workers/r2/validator.worker.ts +import assert from "node:assert"; +import { Buffer as Buffer2 } from "node:buffer"; +import { parseRanges } from "miniflare:shared"; +function identity(ms) { + return ms; +} +function truncateToSeconds(ms) { + return Math.floor(ms / 1e3) * 1e3; +} +function includesEtag(conditions, etag, comparison) { + for (let condition of conditions) + if (condition.type === "wildcard" || condition.value === etag && (condition.type === "strong" || comparison === "weak")) + return !0; + return !1; +} +function _testR2Conditional(cond, metadata) { + if (metadata === void 0) { + let ifMatch2 = cond.etagMatches === void 0, ifModifiedSince2 = cond.uploadedAfter === void 0; + return ifMatch2 && ifModifiedSince2; + } + let { etag, uploaded: lastModifiedRaw } = metadata, ifMatch = cond.etagMatches === void 0 || includesEtag(cond.etagMatches, etag, "strong"), ifNoneMatch = cond.etagDoesNotMatch === void 0 || !includesEtag(cond.etagDoesNotMatch, etag, "weak"), maybeTruncate = cond.secondsGranularity ? truncateToSeconds : identity, lastModified = maybeTruncate(lastModifiedRaw), ifModifiedSince = cond.uploadedAfter === void 0 || maybeTruncate(cond.uploadedAfter.getTime()) < lastModified || cond.etagDoesNotMatch !== void 0 && ifNoneMatch, ifUnmodifiedSince = cond.uploadedBefore === void 0 || lastModified < maybeTruncate(cond.uploadedBefore.getTime()) || cond.etagMatches !== void 0 && ifMatch; + return ifMatch && ifNoneMatch && ifModifiedSince && ifUnmodifiedSince; +} +var R2_HASH_ALGORITHMS = [ + { name: "MD5", field: "md5" }, + { name: "SHA-1", field: "sha1" }, + { name: "SHA-256", field: "sha256" }, + { name: "SHA-384", field: "sha384" }, + { name: "SHA-512", field: "sha512" } +]; +function serialisedLength(x) { + for (let i = 0; i < x.length; i++) + if (x.charCodeAt(i) >= 256) + return x.length * 2; + return x.length; +} +var Validator = class { + hash(digests, hashes) { + let checksums = {}; + for (let { name, field } of R2_HASH_ALGORITHMS) { + let providedHash = hashes[field]; + if (providedHash !== void 0) { + let computedHash = digests.get(name); + if (assert(computedHash !== void 0), !providedHash.equals(computedHash)) + throw new BadDigest(name, providedHash, computedHash); + checksums[field] = computedHash.toString("hex"); + } + } + return checksums; + } + condition(meta, onlyIf) { + if (onlyIf !== void 0 && !_testR2Conditional(onlyIf, meta)) + throw new PreconditionFailed(); + return this; + } + range(options, size) { + if (options.rangeHeader !== void 0) { + let ranges = parseRanges(options.rangeHeader, size); + if (ranges?.length === 1) + return ranges[0]; + } else if (options.range !== void 0) { + let { offset, length, suffix } = options.range; + if (suffix !== void 0) { + if (suffix <= 0) + throw new InvalidRange(); + suffix > size && (suffix = size), offset = size - suffix, length = suffix; + } + if (offset === void 0 && (offset = 0), length === void 0 && (length = size - offset), offset < 0 || offset > size || length <= 0) + throw new InvalidRange(); + return offset + length > size && (length = size - offset), { start: offset, end: offset + length - 1 }; + } + } + size(size) { + if (size > R2Limits.MAX_VALUE_SIZE) + throw new EntityTooLarge(); + return this; + } + metadataSize(customMetadata) { + if (customMetadata === void 0) + return this; + let metadataLength = 0; + for (let [key, value] of Object.entries(customMetadata)) + metadataLength += serialisedLength(key) + serialisedLength(value); + if (metadataLength > R2Limits.MAX_METADATA_SIZE) + throw new MetadataTooLarge(); + return this; + } + key(key) { + if (Buffer2.byteLength(key) > R2Limits.MAX_KEY_SIZE) + throw new InvalidObjectName(); + return this; + } + limit(limit) { + if (limit !== void 0 && (limit < 1 || limit > R2Limits.MAX_LIST_KEYS)) + throw new InvalidMaxKeys(); + return this; + } +}; + +// src/workers/r2/bucket.worker.ts +var DigestingStream = class extends TransformStream { + digests; + constructor(algorithms) { + let digests = new DeferredPromise(), hashes = algorithms.map((alg) => { + let stream = new crypto.DigestStream(alg), writer = stream.getWriter(); + return { stream, writer }; + }); + super({ + async transform(chunk, controller) { + for (let hash of hashes) + await hash.writer.write(chunk); + controller.enqueue(chunk); + }, + async flush() { + let result = /* @__PURE__ */ new Map(); + for (let i = 0; i < hashes.length; i++) + await hashes[i].writer.close(), result.set(algorithms[i], Buffer3.from(await hashes[i].stream.digest)); + digests.resolve(result); + } + }), this.digests = digests; + } +}, validate = new Validator(), decoder = new TextDecoder(); +function generateVersion() { + return Buffer3.from(crypto.getRandomValues(new Uint8Array(16))).toString( + "hex" + ); +} +function generateId() { + return Buffer3.from(crypto.getRandomValues(new Uint8Array(128))).toString( + "base64url" + ); +} +function generateMultipartEtag(md5Hexes) { + let hash = createHash("md5"); + for (let md5Hex of md5Hexes) + hash.update(md5Hex, "hex"); + return `${hash.digest("hex")}-${md5Hexes.length}`; +} +function rangeOverlaps(a, b) { + return a.start <= b.end && b.start <= a.end; +} +async function decodeMetadata(req) { + let metadataSize = parseInt(req.headers.get(R2Headers.METADATA_SIZE)); + if (Number.isNaN(metadataSize)) + throw new InvalidMetadata(); + assert2(req.body !== null); + let body = req.body, [metadataBuffer, value] = await readPrefix(body, metadataSize), metadataJson = decoder.decode(metadataBuffer); + return { metadata: R2BindingRequestSchema.parse(JSON.parse(metadataJson)), metadataSize, value }; +} +function decodeHeaderMetadata(req) { + let header = req.headers.get(R2Headers.REQUEST); + if (header === null) + throw new InvalidMetadata(); + return R2BindingRequestSchema.parse(JSON.parse(header)); +} +function encodeResult(result) { + let encoded; + return result instanceof InternalR2Object ? encoded = result.encode() : encoded = InternalR2Object.encodeMultiple(result), new Response(encoded.value, { + headers: { + [R2Headers.METADATA_SIZE]: `${encoded.metadataSize}`, + "Content-Type": "application/json", + "Content-Length": `${encoded.size}` + } + }); +} +function encodeJSONResult(result) { + let encoded = JSON.stringify(result); + return new Response(encoded, { + headers: { + [R2Headers.METADATA_SIZE]: `${Buffer3.byteLength(encoded)}`, + "Content-Type": "application/json" + } + }); +} +function sqlStmts(db) { + let stmtGetPreviousByKey = db.stmt("SELECT blob_id, etag, uploaded FROM _mf_objects WHERE key = :key"), stmtGetByKey = db.stmt(` + SELECT key, blob_id, version, size, etag, uploaded, checksums, http_metadata, custom_metadata + FROM _mf_objects WHERE key = :key + `), stmtPut = db.stmt(` + INSERT OR REPLACE INTO _mf_objects (key, blob_id, version, size, etag, uploaded, checksums, http_metadata, custom_metadata) + VALUES (:key, :blob_id, :version, :size, :etag, :uploaded, :checksums, :http_metadata, :custom_metadata) + `), stmtDelete = db.stmt("DELETE FROM _mf_objects WHERE key = :key RETURNING blob_id"); + function stmtListWithoutDelimiter(...extraColumns) { + let columns = [ + "key", + "version", + "size", + "etag", + "uploaded", + "checksums", + ...extraColumns + ]; + return db.stmt(` + SELECT ${columns.join(", ")} + FROM _mf_objects + WHERE substr(key, 1, length(:prefix)) = :prefix + AND (:start_after IS NULL OR key > :start_after) + ORDER BY key LIMIT :limit + `); + } + let stmtGetUploadState = db.stmt( + // For checking current upload state + "SELECT state FROM _mf_multipart_uploads WHERE upload_id = :upload_id AND key = :key" + ), stmtGetUploadMetadata = db.stmt( + // For checking current upload state, and getting metadata for completion + "SELECT http_metadata, custom_metadata, state FROM _mf_multipart_uploads WHERE upload_id = :upload_id AND key = :key" + ), stmtUpdateUploadState = db.stmt( + // For completing/aborting uploads + "UPDATE _mf_multipart_uploads SET state = :state WHERE upload_id = :upload_id" + ), stmtGetPreviousPartByNumber = db.stmt( + // For getting part number's previous blob ID to garbage collect + "SELECT blob_id FROM _mf_multipart_parts WHERE upload_id = :upload_id AND part_number = :part_number" + ), stmtPutPart = db.stmt( + // For recording metadata when uploading parts + `INSERT OR REPLACE INTO _mf_multipart_parts (upload_id, part_number, blob_id, size, etag, checksum_md5) + VALUES (:upload_id, :part_number, :blob_id, :size, :etag, :checksum_md5)` + ), stmtLinkPart = db.stmt( + // For linking parts with an object when completing uploads + `UPDATE _mf_multipart_parts SET object_key = :object_key + WHERE upload_id = :upload_id AND part_number = :part_number` + ), stmtDeletePartsByUploadId = db.stmt( + // For deleting parts when aborting uploads + "DELETE FROM _mf_multipart_parts WHERE upload_id = :upload_id RETURNING blob_id" + ), stmtDeleteUnlinkedPartsByUploadId = db.stmt( + // For deleting unused parts when completing uploads + "DELETE FROM _mf_multipart_parts WHERE upload_id = :upload_id AND object_key IS NULL RETURNING blob_id" + ), stmtDeletePartsByKey = db.stmt( + // For deleting dangling parts when overwriting an existing key + "DELETE FROM _mf_multipart_parts WHERE object_key = :object_key RETURNING blob_id" + ), stmtListPartsByUploadId = db.stmt( + // For getting part metadata when completing uploads + `SELECT upload_id, part_number, blob_id, size, etag, checksum_md5, object_key + FROM _mf_multipart_parts WHERE upload_id = :upload_id` + ), stmtListPartsByKey = db.stmt( + // For getting part metadata when getting values, size included for range + // requests, so we only need to read blobs containing the required data + "SELECT blob_id, size FROM _mf_multipart_parts WHERE object_key = :object_key ORDER BY part_number" + ); + return { + getByKey: stmtGetByKey, + getPartsByKey: db.txn((key) => { + let row = get(stmtGetByKey({ key })); + if (row !== void 0) + if (row.blob_id === null) { + let partsRows = all(stmtListPartsByKey({ object_key: key })); + return { row, parts: partsRows }; + } else + return { row }; + }), + put: db.txn((newRow, onlyIf) => { + let key = newRow.key, row = get(stmtGetPreviousByKey({ key })); + onlyIf !== void 0 && validate.condition(row, onlyIf), stmtPut(newRow); + let maybeOldBlobId = row?.blob_id; + return maybeOldBlobId === void 0 ? [] : maybeOldBlobId === null ? all(stmtDeletePartsByKey({ object_key: key })).map(({ blob_id }) => blob_id) : [maybeOldBlobId]; + }), + deleteByKeys: db.txn((keys) => { + let oldBlobIds = []; + for (let key of keys) { + let maybeOldBlobId = get(stmtDelete({ key }))?.blob_id; + if (maybeOldBlobId === null) { + let partRows = stmtDeletePartsByKey({ object_key: key }); + for (let partRow of partRows) + oldBlobIds.push(partRow.blob_id); + } else + maybeOldBlobId !== void 0 && oldBlobIds.push(maybeOldBlobId); + } + return oldBlobIds; + }), + listWithoutDelimiter: stmtListWithoutDelimiter(), + listHttpMetadataWithoutDelimiter: stmtListWithoutDelimiter("http_metadata"), + listCustomMetadataWithoutDelimiter: stmtListWithoutDelimiter("custom_metadata"), + listHttpCustomMetadataWithoutDelimiter: stmtListWithoutDelimiter( + "http_metadata", + "custom_metadata" + ), + listMetadata: db.stmt(` + SELECT + -- When grouping by a delimited prefix, this will give us the last key with that prefix. + -- NOTE: we'll use this for the next cursor. If we didn't return the last key, the next page may return the + -- same delimited prefix. Essentially, we're skipping over all keys with this group's delimited prefix. + -- When grouping by a key, this will just give us the key. + max(key) AS last_key, + iif( + -- Try get 1-indexed position \`i\` of :delimiter in rest of key after :prefix... + instr(substr(key, length(:prefix) + 1), :delimiter), + -- ...if found, we have a delimited prefix of the :prefix followed by the rest of key up to and including the :delimiter + 'dlp:' || substr(key, 1, length(:prefix) + instr(substr(key, length(:prefix) + 1), :delimiter) + length(:delimiter) - 1), + -- ...otherwise, we just have a regular key + 'key:' || key + ) AS delimited_prefix_or_key, + -- NOTE: we'll ignore metadata for delimited prefix rows, so it doesn't matter which keys' we return + version, size, etag, uploaded, checksums, http_metadata, custom_metadata + FROM _mf_objects + WHERE substr(key, 1, length(:prefix)) = :prefix + AND (:start_after IS NULL OR key > :start_after) + GROUP BY delimited_prefix_or_key -- Group keys with same delimited prefix into a row, leaving others in their own rows + ORDER BY last_key LIMIT :limit; + `), + createMultipartUpload: db.stmt(` + INSERT INTO _mf_multipart_uploads (upload_id, key, http_metadata, custom_metadata) + VALUES (:upload_id, :key, :http_metadata, :custom_metadata) + `), + putPart: db.txn( + (key, newRow) => { + if (get( + stmtGetUploadState({ + key, + upload_id: newRow.upload_id + }) + )?.state !== MultipartUploadState.IN_PROGRESS) + throw new NoSuchUpload(); + let partRow = get( + stmtGetPreviousPartByNumber({ + upload_id: newRow.upload_id, + part_number: newRow.part_number + }) + ); + return stmtPutPart(newRow), partRow?.blob_id; + } + ), + completeMultipartUpload: db.txn( + (key, upload_id, selectedParts, minPartSize) => { + let uploadRow = get(stmtGetUploadMetadata({ key, upload_id })); + if (uploadRow === void 0) + throw new InternalError(); + if (uploadRow.state > MultipartUploadState.IN_PROGRESS) + throw new NoSuchUpload(); + let partNumberSet = /* @__PURE__ */ new Set(); + for (let { part } of selectedParts) { + if (partNumberSet.has(part)) + throw new InternalError(); + partNumberSet.add(part); + } + let uploadedPartRows = stmtListPartsByUploadId({ upload_id }), uploadedParts = /* @__PURE__ */ new Map(); + for (let row of uploadedPartRows) + uploadedParts.set(row.part_number, row); + let parts = selectedParts.map((selectedPart) => { + let uploadedPart = uploadedParts.get(selectedPart.part); + if (uploadedPart?.etag !== selectedPart.etag) + throw new InvalidPart(); + return uploadedPart; + }); + for (let part of parts.slice(0, -1)) + if (part.size < minPartSize) + throw new EntityTooSmall(); + parts.sort((a, b) => a.part_number - b.part_number); + let partSize; + for (let part of parts.slice(0, -1)) + if (partSize ??= part.size, part.size < minPartSize || part.size !== partSize) + throw new BadUpload(); + if (partSize !== void 0 && parts[parts.length - 1].size > partSize) + throw new BadUpload(); + let oldBlobIds = [], maybeOldBlobId = get(stmtGetPreviousByKey({ key }))?.blob_id; + if (maybeOldBlobId === null) { + let partRows2 = stmtDeletePartsByKey({ object_key: key }); + for (let partRow of partRows2) + oldBlobIds.push(partRow.blob_id); + } else + maybeOldBlobId !== void 0 && oldBlobIds.push(maybeOldBlobId); + let totalSize = parts.reduce((acc, { size }) => acc + size, 0), etag = generateMultipartEtag( + parts.map(({ checksum_md5 }) => checksum_md5) + ), newRow = { + key, + blob_id: null, + version: generateVersion(), + size: totalSize, + etag, + uploaded: Date.now(), + checksums: "{}", + http_metadata: uploadRow.http_metadata, + custom_metadata: uploadRow.custom_metadata + }; + stmtPut(newRow); + for (let part of parts) + stmtLinkPart({ + upload_id, + part_number: part.part_number, + object_key: key + }); + let partRows = stmtDeleteUnlinkedPartsByUploadId({ upload_id }); + for (let partRow of partRows) + oldBlobIds.push(partRow.blob_id); + return stmtUpdateUploadState({ + upload_id, + state: MultipartUploadState.COMPLETED + }), { newRow, oldBlobIds }; + } + ), + abortMultipartUpload: db.txn((key, upload_id) => { + let uploadRow = get(stmtGetUploadState({ key, upload_id })); + if (uploadRow === void 0) + throw new InternalError(); + if (uploadRow.state > MultipartUploadState.IN_PROGRESS) + return []; + let oldBlobIds = all(stmtDeletePartsByUploadId({ upload_id })).map(({ blob_id }) => blob_id); + return stmtUpdateUploadState({ + upload_id, + state: MultipartUploadState.ABORTED + }), oldBlobIds; + }) + }; +} +var R2BucketObject = class extends MiniflareDurableObject { + #stmts; + // Multipart uploads are stored as multiple blobs. Therefore, when reading a + // multipart upload, we'll be reading multiple blobs. When an object is + // deleted, all its blobs are deleted in the background. + // + // Normally for single part objects, this is fine, since we'd open a handle to + // a single blob, which we'd have until we closed it, at which point the blob + // may be deleted. With multipart, we don't want to open handles for all blobs + // as we could hit open file descriptor limits. Similarly, we don't want to + // read all blobs first, as we'd have to buffer them. + // + // Instead, we set up in-process locking on blobs needed for multipart reads. + // When we start a multipart read, we acquire all the blobs we need, then + // release them as we've streamed each part. Multiple multipart reads may be + // in-progress at any given time, so we use a wait group. + // + // This assumes we only ever have a single Miniflare instance operating on a + // blob store, which is always true for in-memory stores, and usually true for + // on-disk ones. If we really wanted to do this properly, we could store the + // bookkeeping for the wait group in SQLite, but then we'd have to implement + // some inter-process signalling/subscription system. + #inUseBlobs = /* @__PURE__ */ new Map(); + constructor(state, env) { + super(state, env), this.db.exec("PRAGMA case_sensitive_like = TRUE"), this.db.exec(SQL_SCHEMA), this.#stmts = sqlStmts(this.db); + } + #acquireBlob(blobId) { + let waitGroup = this.#inUseBlobs.get(blobId); + waitGroup === void 0 ? (waitGroup = new WaitGroup(), this.#inUseBlobs.set(blobId, waitGroup), waitGroup.add(), waitGroup.wait().then(() => this.#inUseBlobs.delete(blobId))) : waitGroup.add(); + } + #releaseBlob(blobId) { + this.#inUseBlobs.get(blobId)?.done(); + } + #backgroundDelete(blobId) { + this.timers.queueMicrotask(async () => (await this.#inUseBlobs.get(blobId)?.wait(), this.blob.delete(blobId).catch((e) => { + console.error("R2BucketObject##backgroundDelete():", e); + }))); + } + #assembleMultipartValue(parts, queryRange) { + let requiredParts = [], start = 0; + for (let part of parts) { + let partRange = { start, end: start + part.size - 1 }; + if (rangeOverlaps(partRange, queryRange)) { + let range = { + start: Math.max(partRange.start, queryRange.start) - partRange.start, + end: Math.min(partRange.end, queryRange.end) - partRange.start + }; + this.#acquireBlob(part.blob_id), requiredParts.push({ blobId: part.blob_id, range }); + } + start = partRange.end + 1; + } + let identity2 = new TransformStream(); + return (async () => { + let i = 0; + try { + for (; i < requiredParts.length; i++) { + let { blobId, range } = requiredParts[i], value = await this.blob.get(blobId, range), msg = `Expected to find blob "${blobId}" for multipart value`; + assert2(value !== null, msg), await value.pipeTo(identity2.writable, { preventClose: !0 }), this.#releaseBlob(blobId); + } + await identity2.writable.close(); + } catch (e) { + await identity2.writable.abort(e); + } finally { + for (; i < requiredParts.length; i++) + this.#releaseBlob(requiredParts[i].blobId); + } + })(), identity2.readable; + } + async #head(key) { + validate.key(key); + let row = get(this.#stmts.getByKey({ key })); + if (row === void 0) + throw new NoSuchKey(); + let range = { offset: 0, length: row.size }; + return new InternalR2Object(row, range); + } + async #get(key, opts) { + validate.key(key); + let result = this.#stmts.getPartsByKey(key); + if (result === void 0) + throw new NoSuchKey(); + let { row, parts } = result, defaultR2Range = { offset: 0, length: row.size }; + try { + validate.condition(row, opts.onlyIf); + } catch (e) { + throw e instanceof PreconditionFailed && e.attach(new InternalR2Object(row, defaultR2Range)), e; + } + let range = validate.range(opts, row.size), r2Range; + if (range === void 0) + r2Range = defaultR2Range; + else { + let start = range.start, end = Math.min(range.end, row.size); + r2Range = { offset: start, length: end - start + 1 }; + } + let value; + if (row.blob_id === null) { + assert2(parts !== void 0); + let defaultRange = { start: 0, end: row.size - 1 }; + value = this.#assembleMultipartValue(parts, range ?? defaultRange); + } else if (value = await this.blob.get(row.blob_id, range), value === null) + throw new NoSuchKey(); + return new InternalR2ObjectBody(row, value, r2Range); + } + async #put(key, value, valueSize, opts) { + let algorithms = []; + for (let { name, field } of R2_HASH_ALGORITHMS) + (field === "md5" || opts[field] !== void 0) && algorithms.push(name); + let digesting = new DigestingStream(algorithms), blobId = await this.blob.put(value.pipeThrough(digesting)), digests = await digesting.digests, md5Digest = digests.get("MD5"); + assert2(md5Digest !== void 0); + let md5DigestHex = md5Digest.toString("hex"), checksums = validate.key(key).size(valueSize).metadataSize(opts.customMetadata).hash(digests, opts), row = { + key, + blob_id: blobId, + version: generateVersion(), + size: valueSize, + etag: md5DigestHex, + uploaded: Date.now(), + checksums: JSON.stringify(checksums), + http_metadata: JSON.stringify(opts.httpMetadata ?? {}), + custom_metadata: JSON.stringify(opts.customMetadata ?? {}) + }, oldBlobIds; + try { + oldBlobIds = this.#stmts.put(row, opts.onlyIf); + } catch (e) { + throw this.#backgroundDelete(blobId), e; + } + if (oldBlobIds !== void 0) + for (let blobId2 of oldBlobIds) + this.#backgroundDelete(blobId2); + return new InternalR2Object(row); + } + #delete(keys) { + Array.isArray(keys) || (keys = [keys]); + for (let key of keys) + validate.key(key); + let oldBlobIds = this.#stmts.deleteByKeys(keys); + for (let blobId of oldBlobIds) + this.#backgroundDelete(blobId); + } + #listWithoutDelimiterQuery(excludeHttp, excludeCustom) { + return excludeHttp && excludeCustom ? this.#stmts.listWithoutDelimiter : excludeHttp ? this.#stmts.listCustomMetadataWithoutDelimiter : excludeCustom ? this.#stmts.listHttpMetadataWithoutDelimiter : this.#stmts.listHttpCustomMetadataWithoutDelimiter; + } + async #list(opts) { + let prefix = opts.prefix ?? "", limit = opts.limit ?? R2Limits.MAX_LIST_KEYS; + validate.limit(limit); + let include = opts.include ?? []; + include.length > 0 && (limit = Math.min(limit, 100)); + let excludeHttp = !include.includes("httpMetadata"), excludeCustom = !include.includes("customMetadata"), rowObject = (row) => ((row.http_metadata === void 0 || excludeHttp) && (row.http_metadata = "{}"), (row.custom_metadata === void 0 || excludeCustom) && (row.custom_metadata = "{}"), new InternalR2Object(row)), startAfter = opts.startAfter; + if (opts.cursor !== void 0) { + let cursorStartAfter = base64Decode(opts.cursor); + (startAfter === void 0 || cursorStartAfter > startAfter) && (startAfter = cursorStartAfter); + } + let delimiter = opts.delimiter; + delimiter === "" && (delimiter = void 0); + let params = { + prefix, + start_after: startAfter ?? null, + // Increase the queried limit by 1, if we return this many results, we + // know there are more rows. We'll truncate to the original limit before + // returning results. + limit: limit + 1 + }, objects, delimitedPrefixes = [], nextCursorStartAfter; + if (delimiter !== void 0) { + let rows = all(this.#stmts.listMetadata({ ...params, delimiter })), hasMoreRows = rows.length === limit + 1; + rows.splice(limit, 1), objects = []; + for (let row of rows) + row.delimited_prefix_or_key.startsWith("dlp:") ? delimitedPrefixes.push(row.delimited_prefix_or_key.substring(4)) : objects.push(rowObject({ ...row, key: row.last_key })); + hasMoreRows && (nextCursorStartAfter = rows[limit - 1].last_key); + } else { + let query = this.#listWithoutDelimiterQuery(excludeHttp, excludeCustom), rows = all(query(params)), hasMoreRows = rows.length === limit + 1; + rows.splice(limit, 1), objects = rows.map(rowObject), hasMoreRows && (nextCursorStartAfter = rows[limit - 1].key); + } + let nextCursor = maybeApply(base64Encode, nextCursorStartAfter); + return { + objects, + truncated: nextCursor !== void 0, + cursor: nextCursor, + delimitedPrefixes + }; + } + async #createMultipartUpload(key, opts) { + validate.key(key); + let uploadId = generateId(); + return this.#stmts.createMultipartUpload({ + key, + upload_id: uploadId, + http_metadata: JSON.stringify(opts.httpMetadata ?? {}), + custom_metadata: JSON.stringify(opts.customMetadata ?? {}) + }), { uploadId }; + } + async #uploadPart(key, uploadId, partNumber, value, valueSize) { + validate.key(key); + let digesting = new DigestingStream(["MD5"]), blobId = await this.blob.put(value.pipeThrough(digesting)), md5Digest = (await digesting.digests).get("MD5"); + assert2(md5Digest !== void 0); + let etag = generateId(), maybeOldBlobId; + try { + maybeOldBlobId = this.#stmts.putPart(key, { + upload_id: uploadId, + part_number: partNumber, + blob_id: blobId, + size: valueSize, + etag, + checksum_md5: md5Digest.toString("hex") + }); + } catch (e) { + throw this.#backgroundDelete(blobId), e; + } + return maybeOldBlobId !== void 0 && this.#backgroundDelete(maybeOldBlobId), { etag }; + } + async #completeMultipartUpload(key, uploadId, parts) { + validate.key(key); + let minPartSize = this.beingTested ? R2Limits.MIN_MULTIPART_PART_SIZE_TEST : R2Limits.MIN_MULTIPART_PART_SIZE, { newRow, oldBlobIds } = this.#stmts.completeMultipartUpload( + key, + uploadId, + parts, + minPartSize + ); + for (let blobId of oldBlobIds) + this.#backgroundDelete(blobId); + return new InternalR2Object(newRow); + } + async #abortMultipartUpload(key, uploadId) { + validate.key(key); + let oldBlobIds = this.#stmts.abortMultipartUpload(key, uploadId); + for (let blobId of oldBlobIds) + this.#backgroundDelete(blobId); + } + get = async (req) => { + let metadata = decodeHeaderMetadata(req), result; + if (metadata.method === "head") + result = await this.#head(metadata.object); + else if (metadata.method === "get") + result = await this.#get(metadata.object, metadata); + else if (metadata.method === "list") + result = await this.#list(metadata); + else + throw new InternalError(); + return encodeResult(result); + }; + put = async (req) => { + let { metadata, metadataSize, value } = await decodeMetadata(req); + if (metadata.method === "delete") + return await this.#delete( + "object" in metadata ? metadata.object : metadata.objects + ), new Response(); + if (metadata.method === "put") { + let contentLength = parseInt(req.headers.get("Content-Length")); + assert2(!isNaN(contentLength)); + let valueSize = contentLength - metadataSize, result = await this.#put( + metadata.object, + value, + valueSize, + metadata + ); + return encodeResult(result); + } else if (metadata.method === "createMultipartUpload") { + let result = await this.#createMultipartUpload( + metadata.object, + metadata + ); + return encodeJSONResult(result); + } else if (metadata.method === "uploadPart") { + let contentLength = parseInt(req.headers.get("Content-Length")); + assert2(!isNaN(contentLength)); + let valueSize = contentLength - metadataSize, result = await this.#uploadPart( + metadata.object, + metadata.uploadId, + metadata.partNumber, + value, + valueSize + ); + return encodeJSONResult(result); + } else if (metadata.method === "completeMultipartUpload") { + let result = await this.#completeMultipartUpload( + metadata.object, + metadata.uploadId, + metadata.parts + ); + return encodeResult(result); + } else { + if (metadata.method === "abortMultipartUpload") + return await this.#abortMultipartUpload(metadata.object, metadata.uploadId), new Response(); + throw new InternalError(); + } + }; +}; +__decorateClass([ + GET("/") +], R2BucketObject.prototype, "get", 2), __decorateClass([ + PUT("/") +], R2BucketObject.prototype, "put", 2); +export { + R2BucketObject +}; +//# sourceMappingURL=bucket.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js.map b/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js.map new file mode 100644 index 0000000..2a72b57 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/r2/bucket.worker.ts", "../../../../src/workers/r2/constants.ts", "../../../../src/workers/r2/errors.worker.ts", "../../../../src/workers/r2/r2Object.worker.ts", "../../../../src/workers/r2/schemas.worker.ts", "../../../../src/workers/r2/validator.worker.ts"], + "mappings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,KAAK;AAAA,QACzB,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,MACD;AACA,aAAO,aAAa,MAAM;AAAA,IAC3B,WAAW,SAAS,WAAW,yBAAyB;AACvD,UAAM,SAAS,MAAM,KAAK;AAAA,QACzB,SAAS;AAAA,QACT;AAAA,MACD;AACA,aAAO,iBAAiB,MAAM;AAAA,IAC/B,WAAW,SAAS,WAAW,cAAc;AAG5C,UAAM,gBAAgB,SAAS,IAAI,QAAQ,IAAI,gBAAgB,CAAE;AAEjE,MAAAA,QAAO,CAAC,MAAM,aAAa,CAAC;AAC5B,UAAM,YAAY,gBAAgB,cAC5B,SAAS,MAAM,KAAK;AAAA,QACzB,SAAS;AAAA,QACT,SAAS;AAAA,QACT,SAAS;AAAA,QACT;AAAA,QACA;AAAA,MACD;AACA,aAAO,iBAAiB,MAAM;AAAA,IAC/B,WAAW,SAAS,WAAW,2BAA2B;AACzD,UAAM,SAAS,MAAM,KAAK;AAAA,QACzB,SAAS;AAAA,QACT,SAAS;AAAA,QACT,SAAS;AAAA,MACV;AACA,aAAO,aAAa,MAAM;AAAA,IAC3B,OAAO;AAAA,UAAI,SAAS,WAAW;AAC9B,qBAAM,KAAK,sBAAsB,SAAS,QAAQ,SAAS,QAAQ,GAC5D,IAAI,SAAS;AAEpB,YAAM,IAAI,cAAc;AAAA;AAAA,EAE1B;AACD;AA7EC;AAAA,EADC,IAAI,GAAG;AAAA,GAvaI,eAwaZ,sBAkBA;AAAA,EADC,IAAI,GAAG;AAAA,GAzbI,eA0bZ;", + "names": ["assert", "Buffer", "identity", "Buffer", "ifMatch", "ifModifiedSince", "Buffer", "Buffer", "assert", "partRows", "identity", "blobId"] +} diff --git a/node_modules/miniflare/dist/src/workers/ratelimit/ratelimit.worker.js b/node_modules/miniflare/dist/src/workers/ratelimit/ratelimit.worker.js new file mode 100644 index 0000000..fb5e4d8 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/ratelimit/ratelimit.worker.js @@ -0,0 +1,54 @@ +// src/workers/ratelimit/ratelimit.worker.ts +var RatelimitOptionKeys = ["key", "limit", "period"], RatelimitPeriodValues = [10, 60]; +function validate(test, message) { + if (!test) + throw new Error(message); +} +var Ratelimit = class { + namespaceId; + limitVal; + period; + buckets; + epoch; + constructor(config) { + this.namespaceId = config.namespaceId, this.limitVal = config.limit, this.period = config.period, this.buckets = /* @__PURE__ */ new Map(), this.epoch = 0; + } + // method that counts and checks against the limit in in-memory buckets + async limit(options) { + validate( + typeof options == "object" && options !== null, + "invalid rate limit options" + ); + let invalidProps = Object.keys(options ?? {}).filter( + (key2) => !RatelimitOptionKeys.includes(key2) + ); + validate( + invalidProps.length == 0, + `bad rate limit options: [${invalidProps.join(",")}]` + ); + let { + key = "", + limit = this.limitVal, + period = this.period + } = options; + validate(typeof key == "string", `invalid key: ${key}`), validate(typeof limit == "number", `limit must be a number: ${limit}`), validate(typeof period == "number", `period must be a number: ${period}`), validate( + RatelimitPeriodValues.includes(period), + `unsupported period: ${period}` + ); + let epoch = Math.floor(Date.now() / (period * 1e3)); + epoch != this.epoch && (this.epoch = epoch, this.buckets.clear()); + let val = this.buckets.get(key) || 0; + return val >= limit ? { + success: !1 + } : (this.buckets.set(key, val + 1), { + success: !0 + }); + } +}; +function ratelimit_worker_default(env) { + return new Ratelimit(env); +} +export { + ratelimit_worker_default as default +}; +//# sourceMappingURL=ratelimit.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/ratelimit/ratelimit.worker.js.map b/node_modules/miniflare/dist/src/workers/ratelimit/ratelimit.worker.js.map new file mode 100644 index 0000000..f20da68 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/ratelimit/ratelimit.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/ratelimit/ratelimit.worker.ts"], + "mappings": ";AAWA,IAAM,sBAAsB,CAAC,OAAO,SAAS,QAAQ,GAC/C,wBAAwB,CAAC,IAAI,EAAE;AAQrC,SAAS,SAAS,MAAe,S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AR,yBAAkB,KAAsB;AAC9C,SAAO,IAAI,UAAU,GAAG;AACzB;", + "names": ["key"] +} diff --git a/node_modules/miniflare/dist/src/workers/shared/index.worker.js b/node_modules/miniflare/dist/src/workers/shared/index.worker.js new file mode 100644 index 0000000..a75feed --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/index.worker.js @@ -0,0 +1,706 @@ +// src/workers/shared/blob.worker.ts +import assert from "node-internal:internal_assert"; +import { Buffer as Buffer2 } from "node-internal:internal_buffer"; + +// src/workers/shared/data.ts +import { Buffer } from "node-internal:internal_buffer"; +function viewToBuffer(view) { + return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength); +} +function base64Encode(value) { + return Buffer.from(value, "utf8").toString("base64"); +} +function base64Decode(encoded) { + return Buffer.from(encoded, "base64").toString("utf8"); +} +var dotRegexp = /(^|\/|\\)(\.+)(\/|\\|$)/g, illegalRegexp = /[?<>*"'^/\\:|\x00-\x1f\x80-\x9f]/g, windowsReservedRegexp = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i, leadingRegexp = /^[ /\\]+/, trailingRegexp = /[ /\\]+$/; +function dotReplacement(match, g1, g2, g3) { + return `${g1}${"".padStart(g2.length, "_")}${g3}`; +} +function underscoreReplacement(match) { + return "".padStart(match.length, "_"); +} +function sanitisePath(unsafe) { + return unsafe.replace(dotRegexp, dotReplacement).replace(dotRegexp, dotReplacement).replace(illegalRegexp, "_").replace(windowsReservedRegexp, "_").replace(leadingRegexp, underscoreReplacement).replace(trailingRegexp, underscoreReplacement).substring(0, 255); +} + +// src/workers/shared/blob.worker.ts +var ENCODER = new TextEncoder(); +async function readPrefix(stream, prefixLength) { + let reader = await stream.getReader({ mode: "byob" }), result = await reader.readAtLeast( + prefixLength, + new Uint8Array(prefixLength) + ); + assert(result.value !== void 0), reader.releaseLock(); + let rest = stream.pipeThrough(new IdentityTransformStream()); + return [result.value, rest]; +} +function rangeHeaders(range) { + return { Range: `bytes=${range.start}-${range.end}` }; +} +function assertFullRangeRequest(range, contentLength) { + assert( + range.start === 0 && range.end === contentLength - 1, + "Received full content, but requested partial content" + ); +} +async function fetchSingleRange(fetcher, url, range) { + let headers = range === void 0 ? {} : rangeHeaders(range), res = await fetcher.fetch(url, { headers }); + if (res.status === 404) + return null; + if (assert(res.ok && res.body !== null), range !== void 0 && res.status !== 206) { + let contentLength = parseInt(res.headers.get("Content-Length")); + assert(!Number.isNaN(contentLength)), assertFullRangeRequest(range, contentLength); + } + return res.body; +} +async function writeMultipleRanges(fetcher, url, ranges, boundary, writable, contentLength, contentType) { + for (let i = 0; i < ranges.length; i++) { + let range = ranges[i], writer2 = writable.getWriter(); + i > 0 && await writer2.write(ENCODER.encode(`\r +`)), await writer2.write(ENCODER.encode(`--${boundary}\r +`)), contentType !== void 0 && await writer2.write(ENCODER.encode(`Content-Type: ${contentType}\r +`)); + let start = range.start, end = Math.min(range.end, contentLength - 1); + await writer2.write( + ENCODER.encode( + `Content-Range: bytes ${start}-${end}/${contentLength}\r +\r +` + ) + ), writer2.releaseLock(); + let res = await fetcher.fetch(url, { headers: rangeHeaders(range) }); + assert( + res.ok && res.body !== null, + `Failed to fetch ${url}[${range.start},${range.end}], received ${res.status} ${res.statusText}` + ), res.status !== 206 && assertFullRangeRequest(range, contentLength), await res.body.pipeTo(writable, { preventClose: !0 }); + } + let writer = writable.getWriter(); + ranges.length > 0 && await writer.write(ENCODER.encode(`\r +`)), await writer.write(ENCODER.encode(`--${boundary}--`)), await writer.close(); +} +async function fetchMultipleRanges(fetcher, url, ranges, opts) { + let res = await fetcher.fetch(url, { method: "HEAD" }); + if (res.status === 404) + return null; + assert(res.ok); + let contentLength = parseInt(res.headers.get("Content-Length")); + assert(!Number.isNaN(contentLength)); + let boundary = `miniflare-boundary-${crypto.randomUUID()}`, multipartContentType = `multipart/byteranges; boundary=${boundary}`, { readable, writable } = new IdentityTransformStream(); + return writeMultipleRanges( + fetcher, + url, + ranges, + boundary, + writable, + contentLength, + opts?.contentType + ).catch((e) => console.error("Error writing multipart stream:", e)), { multipartContentType, body: readable }; +} +async function fetchRange(fetcher, url, range, opts) { + return Array.isArray(range) ? fetchMultipleRanges(fetcher, url, range, opts) : fetchSingleRange(fetcher, url, range); +} +function generateBlobId() { + let idBuffer = Buffer2.alloc(40); + return crypto.getRandomValues( + new Uint8Array(idBuffer.buffer, idBuffer.byteOffset, 32) + ), idBuffer.writeBigInt64BE( + BigInt(performance.timeOrigin + performance.now()), + 32 + ), idBuffer.toString("hex"); +} +var BlobStore = class { + // Database for binary large objects. Provides single and multi-ranged + // streaming reads and writes. + // + // Blobs have unguessable identifiers, can be deleted, but are otherwise + // immutable. These properties make it possible to perform atomic updates with + // the SQLite metadata store. No other operations will be able to interact + // with the blob until it's committed to the metadata store, because they + // won't be able to guess the ID, and we don't allow listing blobs. + // + // For example, if we put a blob in the store, then fail to insert the blob ID + // into the SQLite database for some reason during a transaction (e.g. + // `onlyIf` condition failed), no other operations can read that blob because + // the ID is lost (we'll just background-delete the blob in this case). + #fetcher; + #baseURL; + #stickyBlobs; + constructor(fetcher, namespace, stickyBlobs) { + namespace = encodeURIComponent(sanitisePath(namespace)), this.#fetcher = fetcher, this.#baseURL = `http://placeholder/${namespace}/blobs/`, this.#stickyBlobs = stickyBlobs; + } + idURL(id) { + let url = new URL(this.#baseURL + id); + return url.toString().startsWith(this.#baseURL) ? url : null; + } + async get(id, range, opts) { + let idURL = this.idURL(id); + return idURL === null ? null : fetchRange(this.#fetcher, idURL, range, opts); + } + async put(stream) { + let id = generateBlobId(), idURL = this.idURL(id); + return assert(idURL !== null), await this.#fetcher.fetch(idURL, { + method: "PUT", + body: stream + }), id; + } + async delete(id) { + if (this.#stickyBlobs) + return; + let idURL = this.idURL(id); + if (idURL === null) + return; + let res = await this.#fetcher.fetch(idURL, { method: "DELETE" }); + assert(res.ok || res.status === 404); + } +}; + +// src/workers/shared/constants.ts +var SharedHeaders = { + LOG_LEVEL: "MF-Log-Level" +}, SharedBindings = { + TEXT_NAMESPACE: "MINIFLARE_NAMESPACE", + DURABLE_OBJECT_NAMESPACE_OBJECT: "MINIFLARE_OBJECT", + MAYBE_SERVICE_BLOBS: "MINIFLARE_BLOBS", + MAYBE_SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK", + MAYBE_JSON_ENABLE_CONTROL_ENDPOINTS: "MINIFLARE_ENABLE_CONTROL_ENDPOINTS", + MAYBE_JSON_ENABLE_STICKY_BLOBS: "MINIFLARE_STICKY_BLOBS" +}, LogLevel = /* @__PURE__ */ ((LogLevel3) => (LogLevel3[LogLevel3.NONE = 0] = "NONE", LogLevel3[LogLevel3.ERROR = 1] = "ERROR", LogLevel3[LogLevel3.WARN = 2] = "WARN", LogLevel3[LogLevel3.INFO = 3] = "INFO", LogLevel3[LogLevel3.DEBUG = 4] = "DEBUG", LogLevel3[LogLevel3.VERBOSE = 5] = "VERBOSE", LogLevel3))(LogLevel || {}); + +// src/workers/shared/keyvalue.worker.ts +import assert3 from "node-internal:internal_assert"; + +// src/workers/shared/sql.worker.ts +import assert2 from "node-internal:internal_assert"; +function isTypedValue(value) { + return value === null || typeof value == "string" || typeof value == "number" || value instanceof ArrayBuffer; +} +function createStatementFactory(sql) { + return (query) => { + let keyIndices = /* @__PURE__ */ new Map(); + query = query.replace(/[:@$]([a-z0-9_]+)/gi, (_, name) => { + let index = keyIndices.get(name); + return index === void 0 && (index = keyIndices.size, keyIndices.set(name, index)), `?${index + 1}`; + }); + let stmt = sql.prepare(query); + return (argsObject) => { + let entries = Object.entries(argsObject); + assert2.strictEqual( + entries.length, + keyIndices.size, + "Expected same number of keys in bindings and query" + ); + let argsArray = new Array(entries.length); + for (let [key, value] of entries) { + let index = keyIndices.get(key); + assert2(index !== void 0, `Unexpected binding key: ${key}`), argsArray[index] = value; + } + return stmt(...argsArray); + }; + }; +} +function createTransactionFactory(storage) { + return (closure) => (...args) => storage.transactionSync(() => closure(...args)); +} +function createTypedSql(storage) { + let sql = storage.sql; + return sql.stmt = createStatementFactory(sql), sql.txn = createTransactionFactory(storage), sql; +} +function get(cursor) { + let result; + for (let row of cursor) + result ??= row; + return result; +} +function all(cursor) { + return Array.from(cursor); +} +function drain(cursor) { + for (let _ of cursor) + ; +} + +// src/workers/shared/keyvalue.worker.ts +var SQL_SCHEMA = ` +CREATE TABLE IF NOT EXISTS _mf_entries ( + key TEXT PRIMARY KEY, + blob_id TEXT NOT NULL, + expiration INTEGER, + metadata TEXT +); +CREATE INDEX IF NOT EXISTS _mf_entries_expiration_idx ON _mf_entries(expiration); +`; +function sqlStmts(db) { + let stmtGetBlobIdByKey = db.stmt( + "SELECT blob_id FROM _mf_entries WHERE key = :key" + ), stmtPut = db.stmt( + `INSERT OR REPLACE INTO _mf_entries (key, blob_id, expiration, metadata) + VALUES (:key, :blob_id, :expiration, :metadata)` + ); + return { + getByKey: db.prepare( + "SELECT key, blob_id, expiration, metadata FROM _mf_entries WHERE key = ?1" + ), + put: db.txn((newEntry) => { + let key = newEntry.key, previousEntry = get(stmtGetBlobIdByKey({ key })); + return stmtPut(newEntry), previousEntry?.blob_id; + }), + deleteByKey: db.stmt( + "DELETE FROM _mf_entries WHERE key = :key RETURNING blob_id, expiration" + ), + deleteExpired: db.stmt( + // `expiration` may be `NULL`, but `NULL < ...` should be falsy + "DELETE FROM _mf_entries WHERE expiration < :now RETURNING blob_id" + ), + list: db.stmt( + `SELECT key, expiration, metadata FROM _mf_entries + WHERE substr(key, 1, length(:prefix)) = :prefix + AND key > :start_after + AND (expiration IS NULL OR expiration >= :now) + ORDER BY key LIMIT :limit` + ) + }; +} +function rowEntry(entry) { + return { + key: entry.key, + expiration: entry.expiration ?? void 0, + metadata: entry.metadata === null ? void 0 : JSON.parse(entry.metadata) + }; +} +var KeyValueStorage = class { + #stmts; + #blob; + #timers; + constructor(object) { + object.db.exec("PRAGMA case_sensitive_like = TRUE"), object.db.exec(SQL_SCHEMA), this.#stmts = sqlStmts(object.db), this.#blob = object.blob, this.#timers = object.timers; + } + #hasExpired(entry) { + return entry.expiration !== null && entry.expiration <= this.#timers.now(); + } + #backgroundDelete(blobId) { + this.#timers.queueMicrotask( + () => this.#blob.delete(blobId).catch(() => { + }) + ); + } + async get(key, optsFactory) { + let row = get(this.#stmts.getByKey(key)); + if (row === void 0) + return null; + if (this.#hasExpired(row)) + return drain(this.#stmts.deleteByKey({ key })), this.#backgroundDelete(row.blob_id), null; + let entry = rowEntry(row), opts = entry.metadata && optsFactory?.(entry.metadata); + if (opts?.ranges === void 0 || opts.ranges.length <= 1) { + let value = await this.#blob.get(row.blob_id, opts?.ranges?.[0]); + return value === null ? null : { ...entry, value }; + } else { + let value = await this.#blob.get(row.blob_id, opts.ranges, opts); + return value === null ? null : { ...entry, value }; + } + } + async put(entry) { + assert3(entry.key !== ""); + let blobId = await this.#blob.put(entry.value); + entry.signal?.aborted && (this.#backgroundDelete(blobId), entry.signal.throwIfAborted()); + let maybeOldBlobId = this.#stmts.put({ + key: entry.key, + blob_id: blobId, + expiration: entry.expiration ?? null, + metadata: entry.metadata === void 0 ? null : JSON.stringify(await entry.metadata) + }); + maybeOldBlobId !== void 0 && this.#backgroundDelete(maybeOldBlobId); + } + async delete(key) { + let cursor = this.#stmts.deleteByKey({ key }), row = get(cursor); + return row === void 0 ? !1 : (this.#backgroundDelete(row.blob_id), !this.#hasExpired(row)); + } + async list(opts) { + let now = this.#timers.now(), prefix = opts.prefix ?? "", start_after = opts.cursor === void 0 ? "" : base64Decode(opts.cursor), limit = opts.limit + 1, rowsCursor = this.#stmts.list({ + now, + prefix, + start_after, + limit + }), rows = Array.from(rowsCursor), expiredRows = this.#stmts.deleteExpired({ now }); + for (let row of expiredRows) + this.#backgroundDelete(row.blob_id); + let hasMoreRows = rows.length === opts.limit + 1; + rows.splice(opts.limit, 1); + let keys = rows.map((row) => rowEntry(row)), nextCursor = hasMoreRows ? base64Encode(rows[opts.limit - 1].key) : void 0; + return { keys, cursor: nextCursor }; + } +}; + +// src/workers/shared/matcher.ts +function testRegExps(matcher, value) { + for (let exclude of matcher.exclude) + if (exclude.test(value)) + return !1; + for (let include of matcher.include) + if (include.test(value)) + return !0; + return !1; +} + +// src/workers/shared/object.worker.ts +import assert5 from "node-internal:internal_assert"; + +// src/workers/shared/router.worker.ts +var HttpError = class extends Error { + constructor(code, message) { + super(message); + this.code = code; + Object.setPrototypeOf(this, new.target.prototype), this.name = `${new.target.name} [${code}]`; + } + toResponse() { + return new Response(this.message, { + status: this.code, + // Custom statusMessage is required for runtime error messages + statusText: this.message.substring(0, 512) + }); + } +}, kRoutesTemplate = Symbol("kRoutesTemplate"), Router = class { + // Routes added by @METHOD decorators + #routes; + constructor() { + this.#routes = new.target.prototype[kRoutesTemplate]; + } + async fetch(req) { + let url = new URL(req.url), methodRoutes = this.#routes?.get(req.method); + if (methodRoutes === void 0) + return new Response(null, { status: 405 }); + let handlers = this; + try { + for (let [path, key] of methodRoutes) { + let match = path.exec(url.pathname); + if (match !== null) + return await handlers[key](req, match.groups, url); + } + return new Response(null, { status: 404 }); + } catch (e) { + if (e instanceof HttpError) + return e.toResponse(); + throw e; + } + } +}; +function pathToRegexp(path) { + return path === void 0 ? /^.*$/ : (path.endsWith("/") || (path += "/?"), path = path.replace(/\//g, "\\/"), path = path.replace(/:(\w+)/g, "(?<$1>[^\\/]+)"), new RegExp(`^${path}$`)); +} +var createRouteDecorator = (method) => (path) => (prototype, key) => { + let route = [pathToRegexp(path), key], routes = prototype[kRoutesTemplate] ??= /* @__PURE__ */ new Map(), methodRoutes = routes.get(method); + methodRoutes ? methodRoutes.push(route) : routes.set(method, [route]); +}, GET = createRouteDecorator("GET"), HEAD = createRouteDecorator("HEAD"), POST = createRouteDecorator("POST"), PUT = createRouteDecorator("PUT"), DELETE = createRouteDecorator("DELETE"), PURGE = createRouteDecorator("PURGE"), PATCH = createRouteDecorator("PATCH"); + +// src/workers/shared/timers.worker.ts +import assert4 from "node-internal:internal_assert"; +var kFakeTimerHandle = Symbol("kFakeTimerHandle"), Timers = class { + // Fake unix time in milliseconds. If defined, fake timers will be enabled. + #fakeTimestamp; + #fakeNextTimerHandle = 0; + #fakePendingTimeouts = /* @__PURE__ */ new Map(); + #fakeRunningTasks = /* @__PURE__ */ new Set(); + // Timers API + now = () => this.#fakeTimestamp ?? Date.now(); + setTimeout(closure, delay, ...args) { + if (this.#fakeTimestamp === void 0) + return setTimeout(closure, delay, ...args); + let handle = this.#fakeNextTimerHandle++, argsClosure = () => closure(...args); + if (delay === 0) + this.queueMicrotask(argsClosure); + else { + let timeout = { + triggerTimestamp: this.#fakeTimestamp + delay, + closure: argsClosure + }; + this.#fakePendingTimeouts.set(handle, timeout); + } + return { [kFakeTimerHandle]: handle }; + } + clearTimeout(handle) { + if (typeof handle == "number") + return clearTimeout(handle); + this.#fakePendingTimeouts.delete(handle[kFakeTimerHandle]); + } + queueMicrotask(closure) { + if (this.#fakeTimestamp === void 0) + return queueMicrotask(closure); + let result = closure(); + result instanceof Promise && (this.#fakeRunningTasks.add(result), result.finally(() => this.#fakeRunningTasks.delete(result))); + } + // Fake Timers Control API + #runPendingTimeouts() { + if (this.#fakeTimestamp !== void 0) + for (let [handle, timeout] of this.#fakePendingTimeouts) + timeout.triggerTimestamp <= this.#fakeTimestamp && (this.#fakePendingTimeouts.delete(handle), this.queueMicrotask(timeout.closure)); + } + enableFakeTimers(timestamp) { + this.#fakeTimestamp = timestamp, this.#runPendingTimeouts(); + } + disableFakeTimers() { + this.#fakeTimestamp = void 0, this.#fakePendingTimeouts.clear(); + } + advanceFakeTime(delta) { + assert4( + this.#fakeTimestamp !== void 0, + "Expected fake timers to be enabled before `advanceFakeTime()` call" + ), this.#fakeTimestamp += delta, this.#runPendingTimeouts(); + } + async waitForFakeTasks() { + for (; this.#fakeRunningTasks.size > 0; ) + await Promise.all(this.#fakeRunningTasks); + } +}; + +// src/workers/shared/types.ts +function reduceError(e) { + return { + name: e?.name, + message: e?.message ?? String(e), + stack: e?.stack, + cause: e?.cause === void 0 ? void 0 : reduceError(e.cause) + }; +} +function maybeApply(f, maybeValue) { + return maybeValue === void 0 ? void 0 : f(maybeValue); +} + +// src/workers/shared/object.worker.ts +var MiniflareDurableObject = class extends Router { + constructor(state, env) { + super(); + this.state = state; + this.env = env; + } + timers = new Timers(); + // If this Durable Object receives a control op, assume it's being tested. + // We use this to adjust some limits in tests. + beingTested = !1; + #db; + get db() { + return this.#db ??= createTypedSql(this.state.storage); + } + #name; + get name() { + return assert5( + this.#name !== void 0, + "Expected `MiniflareDurableObject#fetch()` call before `name` access" + ), this.#name; + } + #blob; + get blob() { + if (this.#blob !== void 0) + return this.#blob; + let maybeBlobsService = this.env[SharedBindings.MAYBE_SERVICE_BLOBS], stickyBlobs = !!this.env[SharedBindings.MAYBE_JSON_ENABLE_STICKY_BLOBS]; + return assert5( + maybeBlobsService !== void 0, + `Expected ${SharedBindings.MAYBE_SERVICE_BLOBS} service binding` + ), this.#blob = new BlobStore(maybeBlobsService, this.name, stickyBlobs), this.#blob; + } + async logWithLevel(level, message) { + await this.env[SharedBindings.MAYBE_SERVICE_LOOPBACK]?.fetch( + "http://localhost/core/log", + { + method: "POST", + headers: { [SharedHeaders.LOG_LEVEL]: level.toString() }, + body: message + } + ); + } + async #handleControlOp({ + name, + args + }) { + if (this.beingTested = !0, name === "sqlQuery") { + assert5(args !== void 0); + let [query, ...params] = args; + assert5(typeof query == "string"), assert5(params.every(isTypedValue)); + let results = all(this.db.prepare(query)(...params)); + return Response.json(results); + } else if (name === "getBlob") { + assert5(args !== void 0); + let [id] = args; + assert5(typeof id == "string"); + let stream = await this.blob.get(id); + return new Response(stream, { status: stream === null ? 404 : 200 }); + } else { + let func = this.timers[name]; + assert5(typeof func == "function"); + let result = await func.apply(this.timers, args); + return Response.json(result ?? null); + } + } + async fetch(req) { + if (this.env[SharedBindings.MAYBE_JSON_ENABLE_CONTROL_ENDPOINTS] === !0) { + let controlOp = req?.cf?.miniflare?.controlOp; + if (controlOp !== void 0) + return this.#handleControlOp(controlOp); + } + let name = req.cf?.miniflare?.name; + assert5(name !== void 0, "Expected `cf.miniflare.name`"), this.#name = name; + try { + return await super.fetch(req); + } catch (e) { + let error = reduceError(e), fallback = error.stack ?? error.message, loopbackService = this.env[SharedBindings.MAYBE_SERVICE_LOOPBACK]; + return loopbackService !== void 0 ? loopbackService.fetch("http://localhost/core/error", { + method: "POST", + body: JSON.stringify(error) + }).catch(() => { + console.error(fallback); + }) : console.error(fallback), new Response(fallback, { status: 500 }); + } finally { + req.body !== null && !req.bodyUsed && await req.body.pipeTo(new WritableStream()); + } + } +}; + +// src/workers/shared/range.ts +var rangePrefixRegexp = /^ *bytes *=/i, rangeRegexp = /^ *(?\d+)? *- *(?\d+)? *$/; +function parseRanges(rangeHeader, length) { + let prefixMatch = rangePrefixRegexp.exec(rangeHeader); + if (prefixMatch === null) + return; + if (rangeHeader = rangeHeader.substring(prefixMatch[0].length), rangeHeader.trimStart() === "") + return []; + let ranges = rangeHeader.split(","), result = []; + for (let range of ranges) { + let match = rangeRegexp.exec(range); + if (match === null) + return; + let { start, end } = match.groups; + if (start !== void 0 && end !== void 0) { + let rangeStart = parseInt(start), rangeEnd = parseInt(end); + if (rangeStart > rangeEnd || rangeStart >= length) + return; + rangeEnd >= length && (rangeEnd = length - 1), result.push({ start: rangeStart, end: rangeEnd }); + } else if (start !== void 0 && end === void 0) { + let rangeStart = parseInt(start); + if (rangeStart >= length) + return; + result.push({ start: rangeStart, end: length - 1 }); + } else if (start === void 0 && end !== void 0) { + let suffix = parseInt(end); + if (suffix >= length) + return []; + if (suffix === 0) + continue; + result.push({ start: length - suffix, end: length - 1 }); + } else + return; + } + return result; +} + +// src/workers/shared/sync.ts +import assert6 from "node-internal:internal_assert"; +var DeferredPromise = class extends Promise { + resolve; + reject; + constructor(executor = () => { + }) { + let promiseResolve, promiseReject; + super((resolve, reject) => (promiseResolve = resolve, promiseReject = reject, executor(resolve, reject))), this.resolve = promiseResolve, this.reject = promiseReject; + } +}, Mutex = class { + locked = !1; + resolveQueue = []; + drainQueue = []; + lock() { + if (!this.locked) { + this.locked = !0; + return; + } + return new Promise((resolve) => this.resolveQueue.push(resolve)); + } + unlock() { + if (assert6(this.locked), this.resolveQueue.length > 0) + this.resolveQueue.shift()?.(); + else { + this.locked = !1; + let resolve; + for (; (resolve = this.drainQueue.shift()) !== void 0; ) + resolve(); + } + } + get hasWaiting() { + return this.resolveQueue.length > 0; + } + async runWith(closure) { + let acquireAwaitable = this.lock(); + acquireAwaitable instanceof Promise && await acquireAwaitable; + try { + let awaitable = closure(); + return awaitable instanceof Promise ? await awaitable : awaitable; + } finally { + this.unlock(); + } + } + async drained() { + if (!(this.resolveQueue.length === 0 && !this.locked)) + return new Promise((resolve) => this.drainQueue.push(resolve)); + } +}, WaitGroup = class { + counter = 0; + resolveQueue = []; + add() { + this.counter++; + } + done() { + if (assert6(this.counter > 0), this.counter--, this.counter === 0) { + let resolve; + for (; (resolve = this.resolveQueue.shift()) !== void 0; ) + resolve(); + } + } + wait() { + return this.counter === 0 ? Promise.resolve() : new Promise((resolve) => this.resolveQueue.push(resolve)); + } +}; +export { + BlobStore, + DELETE, + DeferredPromise, + GET, + HEAD, + HttpError, + KeyValueStorage, + LogLevel, + MiniflareDurableObject, + Mutex, + PATCH, + POST, + PURGE, + PUT, + Router, + SharedBindings, + SharedHeaders, + Timers, + WaitGroup, + all, + base64Decode, + base64Encode, + drain, + get, + maybeApply, + parseRanges, + readPrefix, + reduceError, + testRegExps, + viewToBuffer +}; +/*! Path sanitisation regexps adapted from node-sanitize-filename: + * https://github.com/parshap/node-sanitize-filename/blob/209c39b914c8eb48ee27bcbde64b2c7822fdf3de/index.js#L4-L37 + * + * Licensed under the ISC license: + * + * Copyright Parsha Pourkhomami + * + * 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. + */ +//# sourceMappingURL=index.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/shared/index.worker.js.map b/node_modules/miniflare/dist/src/workers/shared/index.worker.js.map new file mode 100644 index 0000000..e918946 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/index.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/shared/blob.worker.ts", "../../../../src/workers/shared/data.ts", "../../../../src/workers/shared/constants.ts", "../../../../src/workers/shared/keyvalue.worker.ts", "../../../../src/workers/shared/sql.worker.ts", "../../../../src/workers/shared/matcher.ts", "../../../../src/workers/shared/object.worker.ts", "../../../../src/workers/shared/router.worker.ts", "../../../../src/workers/shared/timers.worker.ts", "../../../../src/workers/shared/types.ts", "../../../../src/workers/shared/range.ts", "../../../../src/workers/shared/sync.ts"], + "mappings": ";AAAA,OAAO,YAAY;AACnB,SAAS,UAAAA,eAAc;;;ACDvB,SAAS,cAAc;AAEhB,SAAS,aAAa,MAAoC;AAChE,SAAO,KAAK,OAAO,MAAM,KAAK,YAAY,KAAK,aAAa,KAAK,UAAU;AAC5E;AAEO,SAAS,aAAa,OAAuB;AACnD,SAAO,OAAO,KAAK,OAAO,MAAM,EAAE,SAAS,QAAQ;AACpD;AACO,SAAS,aAAa,SAAyB;AACrD,SAAO,OAAO,KAAK,SAAS,QAAQ,EAAE,SAAS,MAAM;AACtD;AAiBA,IAAM,YAAY,4BACZ,gBAAgB,qCAChB,wBAAwB,iDACxB,gBAAgB,YAChB,iBAA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OAAsB;AACrB,WAAI,KAAK,YAAY,IAAU,QAAQ,QAAQ,IACxC,IAAI,QAAQ,CAAC,YAAY,KAAK,aAAa,KAAK,OAAO,CAAC;AAAA,EAChE;AACD;", + "names": ["Buffer", "writer", "Buffer", "LogLevel", "assert", "assert", "assert", "assert", "assert", "assert", "assert"] +} diff --git a/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js b/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js new file mode 100644 index 0000000..824eed7 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js @@ -0,0 +1,21 @@ +// src/workers/shared/constants.ts +var SharedBindings = { + TEXT_NAMESPACE: "MINIFLARE_NAMESPACE", + DURABLE_OBJECT_NAMESPACE_OBJECT: "MINIFLARE_OBJECT", + MAYBE_SERVICE_BLOBS: "MINIFLARE_BLOBS", + MAYBE_SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK", + MAYBE_JSON_ENABLE_CONTROL_ENDPOINTS: "MINIFLARE_ENABLE_CONTROL_ENDPOINTS", + MAYBE_JSON_ENABLE_STICKY_BLOBS: "MINIFLARE_STICKY_BLOBS" +}; + +// src/workers/shared/object-entry.worker.ts +var object_entry_worker_default = { + async fetch(request, env) { + let name = env[SharedBindings.TEXT_NAMESPACE], objectNamespace = env[SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT], id = objectNamespace.idFromName(name), stub = objectNamespace.get(id), cf = { miniflare: { name } }; + return await stub.fetch(request, { cf }); + } +}; +export { + object_entry_worker_default as default +}; +//# sourceMappingURL=object-entry.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js.map b/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js.map new file mode 100644 index 0000000..45d138b --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/shared/constants.ts", "../../../../src/workers/shared/object-entry.worker.ts"], + "mappings": ";AAIO,IAAM,iBAAiB;AAAA,EAC7B,gBAAgB;AAAA,EAChB,iCAAiC;AAAA,EACjC,qBAAqB;AAAA,EACrB,wBAAwB;AAAA,EACxB,qCAAqC;AAAA,EACrC,gCAAgC;AACjC;;;ACHA,IAAO,8BAA8B;AAAA,EACpC,MAAM,MAAM,SAAS,KAAK;AACzB,QAAM,OAAO,IAAI,eAAe,cAAc,GACxC,kBAAkB,IAAI,eAAe,+BAA+B,GACpE,KAAK,gBAAgB,WAAW,IAAI,GACpC,OAAO,gBAAgB,IAAI,EAAE,GAC7B,KAA+B,EAAE,WAAW,EAAE,KAAK,EAAE;AAC3D,WAAO,MAAM,KAAK,MAAM,SAAS,EAAE,GAAkC,CAAC;AAAA,EACvE;AACD;", + "names": [] +} diff --git a/node_modules/miniflare/dist/src/workers/shared/zod.worker.js b/node_modules/miniflare/dist/src/workers/shared/zod.worker.js new file mode 100644 index 0000000..5f78b6c --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/zod.worker.js @@ -0,0 +1,2719 @@ +// src/workers/shared/zod.worker.ts +import { Buffer } from "node-internal:internal_buffer"; + +// ../../node_modules/.pnpm/zod@3.22.3/node_modules/zod/lib/index.mjs +var util; +(function(util2) { + util2.assertEqual = (val) => val; + function assertIs(_arg) { + } + util2.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util2.assertNever = assertNever, util2.arrayToEnum = (items) => { + let obj = {}; + for (let item of items) + obj[item] = item; + return obj; + }, util2.getValidEnumValues = (obj) => { + let validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] != "number"), filtered = {}; + for (let k of validKeys) + filtered[k] = obj[k]; + return util2.objectValues(filtered); + }, util2.objectValues = (obj) => util2.objectKeys(obj).map(function(e) { + return obj[e]; + }), util2.objectKeys = typeof Object.keys == "function" ? (obj) => Object.keys(obj) : (object) => { + let keys = []; + for (let key in object) + Object.prototype.hasOwnProperty.call(object, key) && keys.push(key); + return keys; + }, util2.find = (arr, checker) => { + for (let item of arr) + if (checker(item)) + return item; + }, util2.isInteger = typeof Number.isInteger == "function" ? (val) => Number.isInteger(val) : (val) => typeof val == "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => typeof val == "string" ? `'${val}'` : val).join(separator); + } + util2.joinValues = joinValues, util2.jsonStringifyReplacer = (_, value) => typeof value == "bigint" ? value.toString() : value; +})(util || (util = {})); +var objectUtil; +(function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => ({ + ...first, + ...second + // second overwrites first + }); +})(objectUtil || (objectUtil = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]), getParsedType = (data) => { + switch (typeof data) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + return Array.isArray(data) ? ZodParsedType.array : data === null ? ZodParsedType.null : data.then && typeof data.then == "function" && data.catch && typeof data.catch == "function" ? ZodParsedType.promise : typeof Map < "u" && data instanceof Map ? ZodParsedType.map : typeof Set < "u" && data instanceof Set ? ZodParsedType.set : typeof Date < "u" && data instanceof Date ? ZodParsedType.date : ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}, ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]), quotelessJson = (obj) => JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:"), ZodError = class extends Error { + constructor(issues) { + super(), this.issues = [], this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }, this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + let actualProto = new.target.prototype; + Object.setPrototypeOf ? Object.setPrototypeOf(this, actualProto) : this.__proto__ = actualProto, this.name = "ZodError", this.issues = issues; + } + get errors() { + return this.issues; + } + format(_mapper) { + let mapper = _mapper || function(issue) { + return issue.message; + }, fieldErrors = { _errors: [] }, processError = (error) => { + for (let issue of error.issues) + if (issue.code === "invalid_union") + issue.unionErrors.map(processError); + else if (issue.code === "invalid_return_type") + processError(issue.returnTypeError); + else if (issue.code === "invalid_arguments") + processError(issue.argumentsError); + else if (issue.path.length === 0) + fieldErrors._errors.push(mapper(issue)); + else { + let curr = fieldErrors, i = 0; + for (; i < issue.path.length; ) { + let el = issue.path[i]; + i === issue.path.length - 1 ? (curr[el] = curr[el] || { _errors: [] }, curr[el]._errors.push(mapper(issue))) : curr[el] = curr[el] || { _errors: [] }, curr = curr[el], i++; + } + } + }; + return processError(this), fieldErrors; + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + let fieldErrors = {}, formErrors = []; + for (let sub of this.issues) + sub.path.length > 0 ? (fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [], fieldErrors[sub.path[0]].push(mapper(sub))) : formErrors.push(mapper(sub)); + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +}; +ZodError.create = (issues) => new ZodError(issues); +var errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + issue.received === ZodParsedType.undefined ? message = "Required" : message = `Expected ${issue.expected}, received ${issue.received}`; + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = "Invalid input"; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = "Invalid function arguments"; + break; + case ZodIssueCode.invalid_return_type: + message = "Invalid function return type"; + break; + case ZodIssueCode.invalid_date: + message = "Invalid date"; + break; + case ZodIssueCode.invalid_string: + typeof issue.validation == "object" ? "includes" in issue.validation ? (message = `Invalid input: must include "${issue.validation.includes}"`, typeof issue.validation.position == "number" && (message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`)) : "startsWith" in issue.validation ? message = `Invalid input: must start with "${issue.validation.startsWith}"` : "endsWith" in issue.validation ? message = `Invalid input: must end with "${issue.validation.endsWith}"` : util.assertNever(issue.validation) : issue.validation !== "regex" ? message = `Invalid ${issue.validation}` : message = "Invalid"; + break; + case ZodIssueCode.too_small: + issue.type === "array" ? message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "more than"} ${issue.minimum} element(s)` : issue.type === "string" ? message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "over"} ${issue.minimum} character(s)` : issue.type === "number" ? message = `Number must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${issue.minimum}` : issue.type === "date" ? message = `Date must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number(issue.minimum))}` : message = "Invalid input"; + break; + case ZodIssueCode.too_big: + issue.type === "array" ? message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "less than"} ${issue.maximum} element(s)` : issue.type === "string" ? message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "under"} ${issue.maximum} character(s)` : issue.type === "number" ? message = `Number must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : issue.type === "bigint" ? message = `BigInt must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : issue.type === "date" ? message = `Date must be ${issue.exact ? "exactly" : issue.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(issue.maximum))}` : message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = "Invalid input"; + break; + case ZodIssueCode.invalid_intersection_types: + message = "Intersection results could not be merged"; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError, util.assertNever(issue); + } + return { message }; +}, overrideErrorMap = errorMap; +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} +var makeIssue = (params) => { + let { data, path, errorMaps, issueData } = params, fullPath = [...path, ...issueData.path || []], fullIssue = { + ...issueData, + path: fullPath + }, errorMessage = "", maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (let map of maps) + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + return { + ...issueData, + path: fullPath, + message: issueData.message || errorMessage + }; +}, EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + let issue = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + // then global default map + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue); +} +var ParseStatus = class { + constructor() { + this.value = "valid"; + } + dirty() { + this.value === "valid" && (this.value = "dirty"); + } + abort() { + this.value !== "aborted" && (this.value = "aborted"); + } + static mergeArray(status, results) { + let arrayValue = []; + for (let s of results) { + if (s.status === "aborted") + return INVALID; + s.status === "dirty" && status.dirty(), arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + let syncPairs = []; + for (let pair of pairs) + syncPairs.push({ + key: await pair.key, + value: await pair.value + }); + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + let finalObject = {}; + for (let pair of pairs) { + let { key, value } = pair; + if (key.status === "aborted" || value.status === "aborted") + return INVALID; + key.status === "dirty" && status.dirty(), value.status === "dirty" && status.dirty(), key.value !== "__proto__" && (typeof value.value < "u" || pair.alwaysSet) && (finalObject[key.value] = value.value); + } + return { status: status.value, value: finalObject }; + } +}, INVALID = Object.freeze({ + status: "aborted" +}), DIRTY = (value) => ({ status: "dirty", value }), OK = (value) => ({ status: "valid", value }), isAborted = (x) => x.status === "aborted", isDirty = (x) => x.status === "dirty", isValid = (x) => x.status === "valid", isAsync = (x) => typeof Promise < "u" && x instanceof Promise, errorUtil; +(function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message == "string" ? { message } : message || {}, errorUtil2.toString = (message) => typeof message == "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); +var ParseInputLazyPath = class { + constructor(parent, value, path, key) { + this._cachedPath = [], this.parent = parent, this.data = value, this._path = path, this._key = key; + } + get path() { + return this._cachedPath.length || (this._key instanceof Array ? this._cachedPath.push(...this._path, ...this._key) : this._cachedPath.push(...this._path, this._key)), this._cachedPath; + } +}, handleResult = (ctx, result) => { + if (isValid(result)) + return { success: !0, data: result.value }; + if (!ctx.common.issues.length) + throw new Error("Validation failed but no issues detected."); + return { + success: !1, + get error() { + if (this._error) + return this._error; + let error = new ZodError(ctx.common.issues); + return this._error = error, this._error; + } + }; +}; +function processCreateParams(params) { + if (!params) + return {}; + let { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + return errorMap2 ? { errorMap: errorMap2, description } : { errorMap: (iss, ctx) => iss.code !== "invalid_type" ? { message: ctx.defaultError } : typeof ctx.data > "u" ? { message: required_error ?? ctx.defaultError } : { message: invalid_type_error ?? ctx.defaultError }, description }; +} +var ZodType = class { + constructor(def) { + this.spa = this.safeParseAsync, this._def = def, this.parse = this.parse.bind(this), this.safeParse = this.safeParse.bind(this), this.parseAsync = this.parseAsync.bind(this), this.safeParseAsync = this.safeParseAsync.bind(this), this.spa = this.spa.bind(this), this.refine = this.refine.bind(this), this.refinement = this.refinement.bind(this), this.superRefine = this.superRefine.bind(this), this.optional = this.optional.bind(this), this.nullable = this.nullable.bind(this), this.nullish = this.nullish.bind(this), this.array = this.array.bind(this), this.promise = this.promise.bind(this), this.or = this.or.bind(this), this.and = this.and.bind(this), this.transform = this.transform.bind(this), this.brand = this.brand.bind(this), this.default = this.default.bind(this), this.catch = this.catch.bind(this), this.describe = this.describe.bind(this), this.pipe = this.pipe.bind(this), this.readonly = this.readonly.bind(this), this.isNullable = this.isNullable.bind(this), this.isOptional = this.isOptional.bind(this); + } + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + let result = this._parse(input); + if (isAsync(result)) + throw new Error("Synchronous parse encountered promise."); + return result; + } + _parseAsync(input) { + let result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + let result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + var _a; + let ctx = { + common: { + issues: [], + async: (_a = params?.async) !== null && _a !== void 0 ? _a : !1, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }, result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + async parseAsync(data, params) { + let result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + let ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: !0 + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }, maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }), result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + let getIssueProperties = (val) => typeof message == "string" || typeof message > "u" ? { message } : typeof message == "function" ? message(val) : message; + return this._refinement((val, ctx) => { + let result = check(val), setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + return typeof Promise < "u" && result instanceof Promise ? result.then((data) => data ? !0 : (setError(), !1)) : result ? !0 : (setError(), !1); + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => check(val) ? !0 : (ctx.addIssue(typeof refinementData == "function" ? refinementData(val, ctx) : refinementData), !1)); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + let defaultValueFunc = typeof def == "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + let catchValueFunc = typeof def == "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + let This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } +}, cuidRegex = /^c[^\s-]{8,}$/i, cuid2Regex = /^[a-z][a-z0-9]*$/, ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/, uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i, emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i, emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u, ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/, ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, datetimeRegex = (args) => args.precision ? args.offset ? new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`) : new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`) : args.precision === 0 ? args.offset ? new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$") : new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$") : args.offset ? new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$") : new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"); +function isValidIP(ip, version) { + return !!((version === "v4" || !version) && ipv4Regex.test(ip) || (version === "v6" || !version) && ipv6Regex.test(ip)); +} +var ZodString = class extends ZodType { + constructor() { + super(...arguments), this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }), this.nonempty = (message) => this.min(1, errorUtil.errToObj(message)), this.trim = () => new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }), this.toLowerCase = () => new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }), this.toUpperCase = () => new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + _parse(input) { + if (this._def.coerce && (input.data = String(input.data)), this._getType(input) !== ZodParsedType.string) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext( + ctx2, + { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + } + // + ), INVALID; + } + let status = new ParseStatus(), ctx; + for (let check of this._def.checks) + if (check.kind === "min") + input.data.length < check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: !0, + exact: !1, + message: check.message + }), status.dirty()); + else if (check.kind === "max") + input.data.length > check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: !0, + exact: !1, + message: check.message + }), status.dirty()); + else if (check.kind === "length") { + let tooBig = input.data.length > check.value, tooSmall = input.data.length < check.value; + (tooBig || tooSmall) && (ctx = this._getOrReturnCtx(input, ctx), tooBig ? addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: !0, + exact: !0, + message: check.message + }) : tooSmall && addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: !0, + exact: !0, + message: check.message + }), status.dirty()); + } else if (check.kind === "email") + emailRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()); + else if (check.kind === "emoji") + emojiRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()); + else if (check.kind === "uuid") + uuidRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()); + else if (check.kind === "cuid") + cuidRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()); + else if (check.kind === "cuid2") + cuid2Regex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()); + else if (check.kind === "ulid") + ulidRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()); + else if (check.kind === "url") + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty(); + } + else + check.kind === "regex" ? (check.regex.lastIndex = 0, check.regex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty())) : check.kind === "trim" ? input.data = input.data.trim() : check.kind === "includes" ? input.data.includes(check.value, check.position) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message + }), status.dirty()) : check.kind === "toLowerCase" ? input.data = input.data.toLowerCase() : check.kind === "toUpperCase" ? input.data = input.data.toUpperCase() : check.kind === "startsWith" ? input.data.startsWith(check.value) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message + }), status.dirty()) : check.kind === "endsWith" ? input.data.endsWith(check.value) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message + }), status.dirty()) : check.kind === "datetime" ? datetimeRegex(check).test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }), status.dirty()) : check.kind === "ip" ? isValidIP(input.data, check.version) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()) : util.assertNever(check); + return { status: status.value, value: input.data }; + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + datetime(options) { + var _a; + return typeof options == "string" ? this._addCheck({ + kind: "datetime", + precision: null, + offset: !1, + message: options + }) : this._addCheck({ + kind: "datetime", + precision: typeof options?.precision > "u" ? null : options?.precision, + offset: (_a = options?.offset) !== null && _a !== void 0 ? _a : !1, + ...errorUtil.errToObj(options?.message) + }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get minLength() { + let min = null; + for (let ch of this._def.checks) + ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value); + return min; + } + get maxLength() { + let max = null; + for (let ch of this._def.checks) + ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value); + return max; + } +}; +ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params?.coerce) !== null && _a !== void 0 ? _a : !1, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder(val, step) { + let valDecCount = (val.toString().split(".")[1] || "").length, stepDecCount = (step.toString().split(".")[1] || "").length, decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount, valInt = parseInt(val.toFixed(decCount).replace(".", "")), stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / Math.pow(10, decCount); +} +var ZodNumber = class extends ZodType { + constructor() { + super(...arguments), this.min = this.gte, this.max = this.lte, this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce && (input.data = Number(input.data)), this._getType(input) !== ZodParsedType.number) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }), INVALID; + } + let ctx, status = new ParseStatus(); + for (let check of this._def.checks) + check.kind === "int" ? util.isInteger(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message + }), status.dirty()) : check.kind === "min" ? (check.inclusive ? input.data < check.value : input.data <= check.value) && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: !1, + message: check.message + }), status.dirty()) : check.kind === "max" ? (check.inclusive ? input.data > check.value : input.data >= check.value) && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: !1, + message: check.message + }), status.dirty()) : check.kind === "multipleOf" ? floatSafeRemainder(input.data, check.value) !== 0 && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }), status.dirty()) : check.kind === "finite" ? Number.isFinite(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message + }), status.dirty()) : util.assertNever(check); + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, !0, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, !1, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, !0, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, !1, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: !1, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: !1, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: !0, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: !0, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: !0, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: !0, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (let ch of this._def.checks) + ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value); + return min; + } + get maxValue() { + let max = null; + for (let ch of this._def.checks) + ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value); + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null, min = null; + for (let ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") + return !0; + ch.kind === "min" ? (min === null || ch.value > min) && (min = ch.value) : ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value); + } + return Number.isFinite(min) && Number.isFinite(max); + } +}; +ZodNumber.create = (params) => new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || !1, + ...processCreateParams(params) +}); +var ZodBigInt = class extends ZodType { + constructor() { + super(...arguments), this.min = this.gte, this.max = this.lte; + } + _parse(input) { + if (this._def.coerce && (input.data = BigInt(input.data)), this._getType(input) !== ZodParsedType.bigint) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx2.parsedType + }), INVALID; + } + let ctx, status = new ParseStatus(); + for (let check of this._def.checks) + check.kind === "min" ? (check.inclusive ? input.data < check.value : input.data <= check.value) && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message + }), status.dirty()) : check.kind === "max" ? (check.inclusive ? input.data > check.value : input.data >= check.value) && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }), status.dirty()) : check.kind === "multipleOf" ? input.data % check.value !== BigInt(0) && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }), status.dirty()) : util.assertNever(check); + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, !0, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, !1, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, !0, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, !1, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: !1, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: !1, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: !0, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: !0, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (let ch of this._def.checks) + ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value); + return min; + } + get maxValue() { + let max = null; + for (let ch of this._def.checks) + ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value); + return max; + } +}; +ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params?.coerce) !== null && _a !== void 0 ? _a : !1, + ...processCreateParams(params) + }); +}; +var ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce && (input.data = Boolean(input.data)), this._getType(input) !== ZodParsedType.boolean) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodBoolean.create = (params) => new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || !1, + ...processCreateParams(params) +}); +var ZodDate = class extends ZodType { + _parse(input) { + if (this._def.coerce && (input.data = new Date(input.data)), this._getType(input) !== ZodParsedType.date) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }), INVALID; + } + if (isNaN(input.data.getTime())) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }), INVALID; + } + let status = new ParseStatus(), ctx; + for (let check of this._def.checks) + check.kind === "min" ? input.data.getTime() < check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: !0, + exact: !1, + minimum: check.value, + type: "date" + }), status.dirty()) : check.kind === "max" ? input.data.getTime() > check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: !0, + exact: !1, + maximum: check.value, + type: "date" + }), status.dirty()) : util.assertNever(check); + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (let ch of this._def.checks) + ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value); + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (let ch of this._def.checks) + ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value); + return max != null ? new Date(max) : null; + } +}; +ZodDate.create = (params) => new ZodDate({ + checks: [], + coerce: params?.coerce || !1, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) +}); +var ZodSymbol = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.symbol) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodSymbol.create = (params) => new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) +}); +var ZodUndefined = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.undefined) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodUndefined.create = (params) => new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) +}); +var ZodNull = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.null) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodNull.create = (params) => new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) +}); +var ZodAny = class extends ZodType { + constructor() { + super(...arguments), this._any = !0; + } + _parse(input) { + return OK(input.data); + } +}; +ZodAny.create = (params) => new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) +}); +var ZodUnknown = class extends ZodType { + constructor() { + super(...arguments), this._unknown = !0; + } + _parse(input) { + return OK(input.data); + } +}; +ZodUnknown.create = (params) => new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) +}); +var ZodNever = class extends ZodType { + _parse(input) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }), INVALID; + } +}; +ZodNever.create = (params) => new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) +}); +var ZodVoid = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.undefined) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodVoid.create = (params) => new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) +}); +var ZodArray = class extends ZodType { + _parse(input) { + let { ctx, status } = this._processInputParams(input), def = this._def; + if (ctx.parsedType !== ZodParsedType.array) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }), INVALID; + if (def.exactLength !== null) { + let tooBig = ctx.data.length > def.exactLength.value, tooSmall = ctx.data.length < def.exactLength.value; + (tooBig || tooSmall) && (addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: !0, + exact: !0, + message: def.exactLength.message + }), status.dirty()); + } + if (def.minLength !== null && ctx.data.length < def.minLength.value && (addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: !0, + exact: !1, + message: def.minLength.message + }), status.dirty()), def.maxLength !== null && ctx.data.length > def.maxLength.value && (addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: !0, + exact: !1, + message: def.maxLength.message + }), status.dirty()), ctx.common.async) + return Promise.all([...ctx.data].map((item, i) => def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)))).then((result2) => ParseStatus.mergeArray(status, result2)); + let result = [...ctx.data].map((item, i) => def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i))); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodArray.create = (schema, params) => new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) +}); +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + let newShape = {}; + for (let key in schema.shape) { + let fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape + }); + } else + return schema instanceof ZodArray ? new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element) + }) : schema instanceof ZodOptional ? ZodOptional.create(deepPartialify(schema.unwrap())) : schema instanceof ZodNullable ? ZodNullable.create(deepPartialify(schema.unwrap())) : schema instanceof ZodTuple ? ZodTuple.create(schema.items.map((item) => deepPartialify(item))) : schema; +} +var ZodObject = class extends ZodType { + constructor() { + super(...arguments), this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + let shape = this._def.shape(), keys = util.objectKeys(shape); + return this._cached = { shape, keys }; + } + _parse(input) { + if (this._getType(input) !== ZodParsedType.object) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }), INVALID; + } + let { status, ctx } = this._processInputParams(input), { shape, keys: shapeKeys } = this._getCached(), extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) + for (let key in ctx.data) + shapeKeys.includes(key) || extraKeys.push(key); + let pairs = []; + for (let key of shapeKeys) { + let keyValidator = shape[key], value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + let unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") + for (let key of extraKeys) + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + else if (unknownKeys === "strict") + extraKeys.length > 0 && (addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }), status.dirty()); + else if (unknownKeys !== "strip") + throw new Error("Internal ZodObject error: invalid unknownKeys value."); + } else { + let catchall = this._def.catchall; + for (let key of extraKeys) { + let value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + return ctx.common.async ? Promise.resolve().then(async () => { + let syncPairs = []; + for (let pair of pairs) { + let key = await pair.key; + syncPairs.push({ + key, + value: await pair.value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => ParseStatus.mergeObjectSync(status, syncPairs)) : ParseStatus.mergeObjectSync(status, pairs); + } + get shape() { + return this._def.shape(); + } + strict(message) { + return errorUtil.errToObj, new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + let defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; + return issue.code === "unrecognized_keys" ? { + message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError + } : { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + return new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index + }); + } + pick(mask) { + let shape = {}; + return util.objectKeys(mask).forEach((key) => { + mask[key] && this.shape[key] && (shape[key] = this.shape[key]); + }), new ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + let shape = {}; + return util.objectKeys(this.shape).forEach((key) => { + mask[key] || (shape[key] = this.shape[key]); + }), new ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + let newShape = {}; + return util.objectKeys(this.shape).forEach((key) => { + let fieldSchema = this.shape[key]; + mask && !mask[key] ? newShape[key] = fieldSchema : newShape[key] = fieldSchema.optional(); + }), new ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + let newShape = {}; + return util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) + newShape[key] = this.shape[key]; + else { + let newField = this.shape[key]; + for (; newField instanceof ZodOptional; ) + newField = newField._def.innerType; + newShape[key] = newField; + } + }), new ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +}; +ZodObject.create = (shape, params) => new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) +}); +ZodObject.strictCreate = (shape, params) => new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) +}); +ZodObject.lazycreate = (shape, params) => new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) +}); +var ZodUnion = class extends ZodType { + _parse(input) { + let { ctx } = this._processInputParams(input), options = this._def.options; + function handleResults(results) { + for (let result of results) + if (result.result.status === "valid") + return result.result; + for (let result of results) + if (result.result.status === "dirty") + return ctx.common.issues.push(...result.ctx.common.issues), result.result; + let unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }), INVALID; + } + if (ctx.common.async) + return Promise.all(options.map(async (option) => { + let childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + { + let dirty, issues = []; + for (let option of options) { + let childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }, result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") + return result; + result.status === "dirty" && !dirty && (dirty = { result, ctx: childCtx }), childCtx.common.issues.length && issues.push(childCtx.common.issues); + } + if (dirty) + return ctx.common.issues.push(...dirty.ctx.common.issues), dirty.result; + let unionErrors = issues.map((issues2) => new ZodError(issues2)); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }), INVALID; + } + } + get options() { + return this._def.options; + } +}; +ZodUnion.create = (types, params) => new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) +}); +var getDiscriminator = (type) => type instanceof ZodLazy ? getDiscriminator(type.schema) : type instanceof ZodEffects ? getDiscriminator(type.innerType()) : type instanceof ZodLiteral ? [type.value] : type instanceof ZodEnum ? type.options : type instanceof ZodNativeEnum ? Object.keys(type.enum) : type instanceof ZodDefault ? getDiscriminator(type._def.innerType) : type instanceof ZodUndefined ? [void 0] : type instanceof ZodNull ? [null] : null, ZodDiscriminatedUnion = class extends ZodType { + _parse(input) { + let { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }), INVALID; + let discriminator = this.discriminator, discriminatorValue = ctx.data[discriminator], option = this.optionsMap.get(discriminatorValue); + return option ? ctx.common.async ? option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) : option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) : (addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }), INVALID); + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + let optionsMap = /* @__PURE__ */ new Map(); + for (let type of options) { + let discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues) + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + for (let value of discriminatorValues) { + if (optionsMap.has(value)) + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } +}; +function mergeValues(a, b) { + let aType = getParsedType(a), bType = getParsedType(b); + if (a === b) + return { valid: !0, data: a }; + if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + let bKeys = util.objectKeys(b), sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1), newObj = { ...a, ...b }; + for (let key of sharedKeys) { + let sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) + return { valid: !1 }; + newObj[key] = sharedValue.data; + } + return { valid: !0, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) + return { valid: !1 }; + let newArray = []; + for (let index = 0; index < a.length; index++) { + let itemA = a[index], itemB = b[index], sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) + return { valid: !1 }; + newArray.push(sharedValue.data); + } + return { valid: !0, data: newArray }; + } else + return aType === ZodParsedType.date && bType === ZodParsedType.date && +a == +b ? { valid: !0, data: a } : { valid: !1 }; +} +var ZodIntersection = class extends ZodType { + _parse(input) { + let { status, ctx } = this._processInputParams(input), handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) + return INVALID; + let merged = mergeValues(parsedLeft.value, parsedRight.value); + return merged.valid ? ((isDirty(parsedLeft) || isDirty(parsedRight)) && status.dirty(), { status: status.value, value: merged.data }) : (addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }), INVALID); + }; + return ctx.common.async ? Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)) : handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } +}; +ZodIntersection.create = (left, right, params) => new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) +}); +var ZodTuple = class extends ZodType { + _parse(input) { + let { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }), INVALID; + if (ctx.data.length < this._def.items.length) + return addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: !0, + exact: !1, + type: "array" + }), INVALID; + !this._def.rest && ctx.data.length > this._def.items.length && (addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: !0, + exact: !1, + type: "array" + }), status.dirty()); + let items = [...ctx.data].map((item, itemIndex) => { + let schema = this._def.items[itemIndex] || this._def.rest; + return schema ? schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)) : null; + }).filter((x) => !!x); + return ctx.common.async ? Promise.all(items).then((results) => ParseStatus.mergeArray(status, results)) : ParseStatus.mergeArray(status, items); + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest + }); + } +}; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; +var ZodRecord = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + let { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }), INVALID; + let pairs = [], keyType = this._def.keyType, valueType = this._def.valueType; + for (let key in ctx.data) + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)) + }); + return ctx.common.async ? ParseStatus.mergeObjectAsync(status, pairs) : ParseStatus.mergeObjectSync(status, pairs); + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + return second instanceof ZodType ? new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }) : new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } +}, ZodMap = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + let { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }), INVALID; + let keyType = this._def.keyType, valueType = this._def.valueType, pairs = [...ctx.data.entries()].map(([key, value], index) => ({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) + })); + if (ctx.common.async) { + let finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (let pair of pairs) { + let key = await pair.key, value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") + return INVALID; + (key.status === "dirty" || value.status === "dirty") && status.dirty(), finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + let finalMap = /* @__PURE__ */ new Map(); + for (let pair of pairs) { + let key = pair.key, value = pair.value; + if (key.status === "aborted" || value.status === "aborted") + return INVALID; + (key.status === "dirty" || value.status === "dirty") && status.dirty(), finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +}; +ZodMap.create = (keyType, valueType, params) => new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) +}); +var ZodSet = class extends ZodType { + _parse(input) { + let { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }), INVALID; + let def = this._def; + def.minSize !== null && ctx.data.size < def.minSize.value && (addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: !0, + exact: !1, + message: def.minSize.message + }), status.dirty()), def.maxSize !== null && ctx.data.size > def.maxSize.value && (addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: !0, + exact: !1, + message: def.maxSize.message + }), status.dirty()); + let valueType = this._def.valueType; + function finalizeSet(elements2) { + let parsedSet = /* @__PURE__ */ new Set(); + for (let element of elements2) { + if (element.status === "aborted") + return INVALID; + element.status === "dirty" && status.dirty(), parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + let elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + return ctx.common.async ? Promise.all(elements).then((elements2) => finalizeSet(elements2)) : finalizeSet(elements); + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodSet.create = (valueType, params) => new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) +}); +var ZodFunction = class extends ZodType { + constructor() { + super(...arguments), this.validate = this.implement; + } + _parse(input) { + let { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }), INVALID; + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + let params = { errorMap: ctx.common.contextualErrorMap }, fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + let me = this; + return OK(async function(...args) { + let error = new ZodError([]), parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + throw error.addIssue(makeArgsIssue(args, e)), error; + }), result = await Reflect.apply(fn, this, parsedArgs); + return await me._def.returns._def.type.parseAsync(result, params).catch((e) => { + throw error.addIssue(makeReturnsIssue(result, e)), error; + }); + }); + } else { + let me = this; + return OK(function(...args) { + let parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + let result = Reflect.apply(fn, this, parsedArgs.data), parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + return this.parse(func); + } + strictImplement(func) { + return this.parse(func); + } + static create(args, returns, params) { + return new ZodFunction({ + args: args || ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } +}, ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + let { ctx } = this._processInputParams(input); + return this._def.getter()._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +}; +ZodLazy.create = (getter, params) => new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) +}); +var ZodLiteral = class extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }), INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +}; +ZodLiteral.create = (value, params) => new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) +}); +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +var ZodEnum = class extends ZodType { + _parse(input) { + if (typeof input.data != "string") { + let ctx = this._getOrReturnCtx(input), expectedValues = this._def.values; + return addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }), INVALID; + } + if (this._def.values.indexOf(input.data) === -1) { + let ctx = this._getOrReturnCtx(input), expectedValues = this._def.values; + return addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }), INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + let enumValues = {}; + for (let val of this._def.values) + enumValues[val] = val; + return enumValues; + } + get Values() { + let enumValues = {}; + for (let val of this._def.values) + enumValues[val] = val; + return enumValues; + } + get Enum() { + let enumValues = {}; + for (let val of this._def.values) + enumValues[val] = val; + return enumValues; + } + extract(values) { + return ZodEnum.create(values); + } + exclude(values) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); + } +}; +ZodEnum.create = createZodEnum; +var ZodNativeEnum = class extends ZodType { + _parse(input) { + let nativeEnumValues = util.getValidEnumValues(this._def.values), ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + let expectedValues = util.objectValues(nativeEnumValues); + return addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }), INVALID; + } + if (nativeEnumValues.indexOf(input.data) === -1) { + let expectedValues = util.objectValues(nativeEnumValues); + return addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }), INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +}; +ZodNativeEnum.create = (values, params) => new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) +}); +var ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + let { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === !1) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }), INVALID; + let promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }))); + } +}; +ZodPromise.create = (schema, params) => new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) +}); +var ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + let { status, ctx } = this._processInputParams(input), effect = this._def.effect || null, checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg), arg.fatal ? status.abort() : status.dirty(); + }, + get path() { + return ctx.path; + } + }; + if (checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx), effect.type === "preprocess") { + let processed = effect.transform(ctx.data, checkCtx); + return ctx.common.issues.length ? { + status: "dirty", + value: ctx.data + } : ctx.common.async ? Promise.resolve(processed).then((processed2) => this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + })) : this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + } + if (effect.type === "refinement") { + let executeRefinement = (acc) => { + let result = effect.refinement(acc, checkCtx); + if (ctx.common.async) + return Promise.resolve(result); + if (result instanceof Promise) + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + return acc; + }; + if (ctx.common.async === !1) { + let inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + return inner.status === "aborted" ? INVALID : (inner.status === "dirty" && status.dirty(), executeRefinement(inner.value), { status: status.value, value: inner.value }); + } else + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => inner.status === "aborted" ? INVALID : (inner.status === "dirty" && status.dirty(), executeRefinement(inner.value).then(() => ({ status: status.value, value: inner.value })))); + } + if (effect.type === "transform") + if (ctx.common.async === !1) { + let base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return base; + let result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) + throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead."); + return { status: status.value, value: result }; + } else + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => isValid(base) ? Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })) : base); + util.assertNever(effect); + } +}; +ZodEffects.create = (schema, effect, params) => new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) +}); +ZodEffects.createWithPreprocess = (preprocess, schema, params) => new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) +}); +var ZodOptional = class extends ZodType { + _parse(input) { + return this._getType(input) === ZodParsedType.undefined ? OK(void 0) : this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodOptional.create = (type, params) => new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) +}); +var ZodNullable = class extends ZodType { + _parse(input) { + return this._getType(input) === ZodParsedType.null ? OK(null) : this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodNullable.create = (type, params) => new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) +}); +var ZodDefault = class extends ZodType { + _parse(input) { + let { ctx } = this._processInputParams(input), data = ctx.data; + return ctx.parsedType === ZodParsedType.undefined && (data = this._def.defaultValue()), this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } +}; +ZodDefault.create = (type, params) => new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default == "function" ? params.default : () => params.default, + ...processCreateParams(params) +}); +var ZodCatch = class extends ZodType { + _parse(input) { + let { ctx } = this._processInputParams(input), newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }, result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + return isAsync(result) ? result.then((result2) => ({ + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + })) : { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + removeCatch() { + return this._def.innerType; + } +}; +ZodCatch.create = (type, params) => new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch == "function" ? params.catch : () => params.catch, + ...processCreateParams(params) +}); +var ZodNaN = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.nan) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }), INVALID; + } + return { status: "valid", value: input.data }; + } +}; +ZodNaN.create = (params) => new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) +}); +var BRAND = Symbol("zod_brand"), ZodBranded = class extends ZodType { + _parse(input) { + let { ctx } = this._processInputParams(input), data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } +}, ZodPipeline = class extends ZodType { + _parse(input) { + let { status, ctx } = this._processInputParams(input); + if (ctx.common.async) + return (async () => { + let inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + return inResult.status === "aborted" ? INVALID : inResult.status === "dirty" ? (status.dirty(), DIRTY(inResult.value)) : this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + })(); + { + let inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + return inResult.status === "aborted" ? INVALID : inResult.status === "dirty" ? (status.dirty(), { + status: "dirty", + value: inResult.value + }) : this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } +}, ZodReadonly = class extends ZodType { + _parse(input) { + let result = this._def.innerType._parse(input); + return isValid(result) && (result.value = Object.freeze(result.value)), result; + } +}; +ZodReadonly.create = (type, params) => new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) +}); +var custom = (check, params = {}, fatal) => check ? ZodAny.create().superRefine((data, ctx) => { + var _a, _b; + if (!check(data)) { + let p = typeof params == "function" ? params(data) : typeof params == "string" ? { message: params } : params, _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : !0, p2 = typeof p == "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } +}) : ZodAny.create(), late = { + object: ZodObject.lazycreate +}, ZodFirstPartyTypeKind; +(function(ZodFirstPartyTypeKind2) { + ZodFirstPartyTypeKind2.ZodString = "ZodString", ZodFirstPartyTypeKind2.ZodNumber = "ZodNumber", ZodFirstPartyTypeKind2.ZodNaN = "ZodNaN", ZodFirstPartyTypeKind2.ZodBigInt = "ZodBigInt", ZodFirstPartyTypeKind2.ZodBoolean = "ZodBoolean", ZodFirstPartyTypeKind2.ZodDate = "ZodDate", ZodFirstPartyTypeKind2.ZodSymbol = "ZodSymbol", ZodFirstPartyTypeKind2.ZodUndefined = "ZodUndefined", ZodFirstPartyTypeKind2.ZodNull = "ZodNull", ZodFirstPartyTypeKind2.ZodAny = "ZodAny", ZodFirstPartyTypeKind2.ZodUnknown = "ZodUnknown", ZodFirstPartyTypeKind2.ZodNever = "ZodNever", ZodFirstPartyTypeKind2.ZodVoid = "ZodVoid", ZodFirstPartyTypeKind2.ZodArray = "ZodArray", ZodFirstPartyTypeKind2.ZodObject = "ZodObject", ZodFirstPartyTypeKind2.ZodUnion = "ZodUnion", ZodFirstPartyTypeKind2.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", ZodFirstPartyTypeKind2.ZodIntersection = "ZodIntersection", ZodFirstPartyTypeKind2.ZodTuple = "ZodTuple", ZodFirstPartyTypeKind2.ZodRecord = "ZodRecord", ZodFirstPartyTypeKind2.ZodMap = "ZodMap", ZodFirstPartyTypeKind2.ZodSet = "ZodSet", ZodFirstPartyTypeKind2.ZodFunction = "ZodFunction", ZodFirstPartyTypeKind2.ZodLazy = "ZodLazy", ZodFirstPartyTypeKind2.ZodLiteral = "ZodLiteral", ZodFirstPartyTypeKind2.ZodEnum = "ZodEnum", ZodFirstPartyTypeKind2.ZodEffects = "ZodEffects", ZodFirstPartyTypeKind2.ZodNativeEnum = "ZodNativeEnum", ZodFirstPartyTypeKind2.ZodOptional = "ZodOptional", ZodFirstPartyTypeKind2.ZodNullable = "ZodNullable", ZodFirstPartyTypeKind2.ZodDefault = "ZodDefault", ZodFirstPartyTypeKind2.ZodCatch = "ZodCatch", ZodFirstPartyTypeKind2.ZodPromise = "ZodPromise", ZodFirstPartyTypeKind2.ZodBranded = "ZodBranded", ZodFirstPartyTypeKind2.ZodPipeline = "ZodPipeline", ZodFirstPartyTypeKind2.ZodReadonly = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +var instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom((data) => data instanceof cls, params), stringType = ZodString.create, numberType = ZodNumber.create, nanType = ZodNaN.create, bigIntType = ZodBigInt.create, booleanType = ZodBoolean.create, dateType = ZodDate.create, symbolType = ZodSymbol.create, undefinedType = ZodUndefined.create, nullType = ZodNull.create, anyType = ZodAny.create, unknownType = ZodUnknown.create, neverType = ZodNever.create, voidType = ZodVoid.create, arrayType = ZodArray.create, objectType = ZodObject.create, strictObjectType = ZodObject.strictCreate, unionType = ZodUnion.create, discriminatedUnionType = ZodDiscriminatedUnion.create, intersectionType = ZodIntersection.create, tupleType = ZodTuple.create, recordType = ZodRecord.create, mapType = ZodMap.create, setType = ZodSet.create, functionType = ZodFunction.create, lazyType = ZodLazy.create, literalType = ZodLiteral.create, enumType = ZodEnum.create, nativeEnumType = ZodNativeEnum.create, promiseType = ZodPromise.create, effectsType = ZodEffects.create, optionalType = ZodOptional.create, nullableType = ZodNullable.create, preprocessType = ZodEffects.createWithPreprocess, pipelineType = ZodPipeline.create, ostring = () => stringType().optional(), onumber = () => numberType().optional(), oboolean = () => booleanType().optional(), coerce = { + string: (arg) => ZodString.create({ ...arg, coerce: !0 }), + number: (arg) => ZodNumber.create({ ...arg, coerce: !0 }), + boolean: (arg) => ZodBoolean.create({ + ...arg, + coerce: !0 + }), + bigint: (arg) => ZodBigInt.create({ ...arg, coerce: !0 }), + date: (arg) => ZodDate.create({ ...arg, coerce: !0 }) +}, NEVER = INVALID, z = /* @__PURE__ */ Object.freeze({ + __proto__: null, + defaultErrorMap: errorMap, + setErrorMap, + getErrorMap, + makeIssue, + EMPTY_PATH, + addIssueToContext, + ParseStatus, + INVALID, + DIRTY, + OK, + isAborted, + isDirty, + isValid, + isAsync, + get util() { + return util; + }, + get objectUtil() { + return objectUtil; + }, + ZodParsedType, + getParsedType, + ZodType, + ZodString, + ZodNumber, + ZodBigInt, + ZodBoolean, + ZodDate, + ZodSymbol, + ZodUndefined, + ZodNull, + ZodAny, + ZodUnknown, + ZodNever, + ZodVoid, + ZodArray, + ZodObject, + ZodUnion, + ZodDiscriminatedUnion, + ZodIntersection, + ZodTuple, + ZodRecord, + ZodMap, + ZodSet, + ZodFunction, + ZodLazy, + ZodLiteral, + ZodEnum, + ZodNativeEnum, + ZodPromise, + ZodEffects, + ZodTransformer: ZodEffects, + ZodOptional, + ZodNullable, + ZodDefault, + ZodCatch, + ZodNaN, + BRAND, + ZodBranded, + ZodPipeline, + ZodReadonly, + custom, + Schema: ZodType, + ZodSchema: ZodType, + late, + get ZodFirstPartyTypeKind() { + return ZodFirstPartyTypeKind; + }, + coerce, + any: anyType, + array: arrayType, + bigint: bigIntType, + boolean: booleanType, + date: dateType, + discriminatedUnion: discriminatedUnionType, + effect: effectsType, + enum: enumType, + function: functionType, + instanceof: instanceOfType, + intersection: intersectionType, + lazy: lazyType, + literal: literalType, + map: mapType, + nan: nanType, + nativeEnum: nativeEnumType, + never: neverType, + null: nullType, + nullable: nullableType, + number: numberType, + object: objectType, + oboolean, + onumber, + optional: optionalType, + ostring, + pipeline: pipelineType, + preprocess: preprocessType, + promise: promiseType, + record: recordType, + set: setType, + strictObject: strictObjectType, + string: stringType, + symbol: symbolType, + transformer: effectsType, + tuple: tupleType, + undefined: undefinedType, + union: unionType, + unknown: unknownType, + void: voidType, + NEVER, + ZodIssueCode, + quotelessJson, + ZodError +}); + +// src/workers/shared/zod.worker.ts +var HEX_REGEXP = /^[0-9a-f]*$/i, BASE64_REGEXP = /^[0-9a-z+/=]*$/i, HexDataSchema = z.string().regex(HEX_REGEXP).transform((hex) => Buffer.from(hex, "hex")), Base64DataSchema = z.string().regex(BASE64_REGEXP).transform((base64) => Buffer.from(base64, "base64")); +export { + BASE64_REGEXP, + Base64DataSchema, + HEX_REGEXP, + HexDataSchema, + z +}; +//# sourceMappingURL=zod.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/shared/zod.worker.js.map b/node_modules/miniflare/dist/src/workers/shared/zod.worker.js.map new file mode 100644 index 0000000..77ea152 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/zod.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/shared/zod.worker.ts", "../../../../../../node_modules/.pnpm/zod@3.22.3/node_modules/zod/lib/index.mjs"], + "mappings": ";AAAA,SAAS,cAAc;;;ACAvB,IAAI;AAAA,CACH,SAAUA,OAAM;AACb,EAAAA,MAAK,cAAc,CAAC,QAAQ;AAC5B,WAAS,SAAS,MAAM;AAAA,EAAE;AAC1B,EAAAA,MAAK,WAAW;AAChB,WAAS,YAAY,IAAI;AACrB,UAAM,IAAI,MAAM;AAAA,EACpB;AACA,EAAAA,MAAK,cAAc,aACnBA,MAAK,cAAc,CAAC,UAAU;AAC1B,QAAM,MAAM,CAAC;AACb,aAAW,QAAQ;AACf,UAAI,IAAI,IAAI;AAEhB,WAAO;AAAA,EACX,GACAA,MAAK,qBAAqB,CAAC,QAAQ;AAC/B,QAAM,YAAYA,MAAK,WAAW,GAAG,EAAE,OAAO,CAAC,MAAM,OAAO,IAAI,IAAI,CAAC,CAAC,KAAM,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AAc;AAAA,EACd,cAAc;AAAA,EACd,MAAM;AAAA,EACN,SAAS;AAAA,EACT,KAAK;AAAA,EACL,KAAK;AAAA,EACL,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,MAAQ;AAAA,EACR,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,KAAK;AAAA,EACL,cAAc;AAAA,EACd,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,OAAO;AAAA,EACP,WAAa;AAAA,EACb,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;;;ADh6HM,IAAM,aAAa,gBAEb,gBAAgB,mBAChB,gBAAgB,EAC3B,OAAO,EACP,MAAM,UAAU,EAChB,UAAU,CAAC,QAAQ,OAAO,KAAK,KAAK,KAAK,CAAC,GAC/B,mBAAmB,EAC9B,OAAO,EACP,MAAM,aAAa,EACnB,UAAU,CAAC,WAAW,OAAO,KAAK,QAAQ,QAAQ,CAAC;", + "names": ["util", "objectUtil", "errorUtil", "errorMap", "ctx", "result", "issues", "elements", "processed", "ZodFirstPartyTypeKind"] +} diff --git a/node_modules/miniflare/package.json b/node_modules/miniflare/package.json new file mode 100644 index 0000000..5e262e3 --- /dev/null +++ b/node_modules/miniflare/package.json @@ -0,0 +1,105 @@ +{ + "name": "miniflare", + "version": "3.20240419.1", + "description": "Fun, full-featured, fully-local simulator for Cloudflare Workers", + "keywords": [ + "cloudflare", + "workers", + "worker", + "local", + "cloudworker" + ], + "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/miniflare#readme", + "bugs": { + "url": "https://github.com/cloudflare/workers-sdk/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/cloudflare/workers-sdk.git", + "directory": "packages/miniflare" + }, + "license": "MIT", + "author": "MrBBot ", + "main": "./dist/src/index.js", + "types": "./dist/src/index.d.ts", + "files": [ + "dist/src", + "bootstrap.js" + ], + "bin": { + "miniflare": "bootstrap.js" + }, + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "acorn": "^8.8.0", + "acorn-walk": "^8.2.0", + "capnp-ts": "^0.7.0", + "exit-hook": "^2.2.1", + "glob-to-regexp": "^0.4.1", + "stoppable": "^1.1.0", + "undici": "^5.28.2", + "workerd": "1.20240419.0", + "ws": "^8.11.0", + "youch": "^3.2.2", + "zod": "^3.20.6" + }, + "devDependencies": { + "@ava/typescript": "^4.0.0", + "@cloudflare/workers-types": "^4.20240419.0", + "@microsoft/api-extractor": "^7.36.3", + "@types/debug": "^4.1.7", + "@types/estree": "^1.0.0", + "@types/glob-to-regexp": "^0.4.1", + "@types/http-cache-semantics": "^4.0.1", + "@types/node": "^18.11.9", + "@types/rimraf": "^3.0.2", + "@types/stoppable": "^1.1.1", + "@types/which": "^2.0.1", + "@types/ws": "^8.5.3", + "@typescript-eslint/eslint-plugin": "^6.9.0", + "@typescript-eslint/parser": "^6.9.0", + "ava": "^5.2.0", + "capnpc-ts": "^0.7.0", + "concurrently": "^8.2.2", + "devalue": "^4.3.0", + "devtools-protocol": "^0.0.1182435", + "esbuild": "^0.16.17", + "eslint": "^8.6.0", + "eslint-config-prettier": "^9.0.0", + "eslint-plugin-es": "^4.1.0", + "eslint-plugin-import": "2.26.x", + "eslint-plugin-prettier": "^5.0.1", + "expect-type": "^0.15.0", + "http-cache-semantics": "^4.1.0", + "kleur": "^4.1.5", + "prettier": "^3.0.3", + "rimraf": "^3.0.2", + "source-map": "^0.6.0", + "typescript": "^5.4.5", + "which": "^2.0.2", + "@cloudflare/kv-asset-handler": "0.3.2" + }, + "engines": { + "node": ">=16.13" + }, + "volta": { + "extends": "../../package.json" + }, + "publishConfig": { + "access": "public" + }, + "workers-sdk": { + "prerelease": true + }, + "scripts": { + "build": "node scripts/build.mjs && pnpm run types:build", + "capnp:workerd": "capnpc -o ts src/runtime/config/workerd.capnp", + "clean": "rimraf ./dist ./dist-types", + "dev": "concurrently -n esbuild,typechk,typewrk -c yellow,blue,blue.dim \"node scripts/build.mjs watch\" \"node scripts/types.mjs tsconfig.json watch\" \"node scripts/types.mjs src/workers/tsconfig.json watch\"", + "test": "node scripts/build.mjs && ava && rimraf ./.tmp", + "test:ci": "pnpm run test", + "check:lint": "eslint --max-warnings=0 \"{src,test}/**/*.ts\" \"scripts/**/*.{js,mjs}\" \"types/**/*.ts\"", + "lint:fix": "pnpm run check:lint --fix", + "types:build": "node scripts/types.mjs tsconfig.json && node scripts/types.mjs src/workers/tsconfig.json" + } +} \ No newline at end of file diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..c4498bc --- /dev/null +++ b/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/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/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/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..eea666e --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.1.2", + "description": "Tiny millisecond 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": "4.12.1", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..9a1996b --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,60 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit) + +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/node_modules/mustache/CHANGELOG.md b/node_modules/mustache/CHANGELOG.md new file mode 100644 index 0000000..b1f72d0 --- /dev/null +++ b/node_modules/mustache/CHANGELOG.md @@ -0,0 +1,618 @@ +# Change Log + +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +## [4.2.0] / 28 March 2021 + +### Added + +* [#773]: Add package.json `exports` field, by [@manzt]. + +## [4.1.0] / 6 December 2020 + +### Added + +* [#764]: `render()` now recognizes a config object argument, by [@pineapplemachine]. + +### Fixed + +* [#764]: Ask custom `escape` functions to escape all types of values (including `number`s), by [@pineapplemachine]. + +## [4.0.1] / 15 March 2020 + +### Fixed + + * [#739]: Fix custom delimiters in nested partials, by [@aielo]. + +## [4.0.0] / 16 January 2020 + +Majority of using projects don't have to worry by this being a new major version. + +**TLDR;** if your project manipulates `Writer.prototype.parse | Writer.cache` directly or uses `.to_html()`, you probably have to change that code. + +This release allows the internal template cache to be customised, either by disabling it completely +or provide a custom strategy deciding how the cache should behave when mustache.js parses templates. + +```js +const mustache = require('mustache'); + +// disable caching +Mustache.templateCache = undefined; + +// or use a built-in Map in modern environments +Mustache.templateCache = new Map(); +``` + +Projects that wanted to customise the caching behaviour in earlier versions of mustache.js were forced to +override internal method responsible for parsing templates; `Writer.prototype.parse`. In short, that was unfortunate +because there is more than caching happening in that method. + +We've improved that now by introducing a first class API that only affects template caching. + +The default template cache behaves as before and is still compatible with older JavaScript environments. +For those who wants to provide a custom more sopisiticated caching strategy, one can do that with an object that adheres to the following requirements: + +```ts +{ + set(cacheKey: string, value: string): void + get(cacheKey: string): string | undefined + clear(): void +} +``` + +### Added + +* [#731]: Allow template caching to be customised, by [@AndrewLeedham]. + +### Removed + +* [#735]: Remove `.to_html()`, by [@phillipj]. + +## [3.2.1] / 30 December 2019 + +### Fixed + + * [#733]: Allow the CLI to use JavaScript views when the project has ES6 modules enabled, by [@eobrain]. + +## [3.2.0] / 18 December 2019 + +### Added + +* [#728]: Expose ECMAScript Module in addition to UMD (CommonJS, AMD & global scope), by [@phillipj] and [@zekth]. + +### Using mustache.js as an ES module + +To stay backwards compatible with already using projects, the default exposed module format is still UMD. +That means projects using mustache.js as an CommonJS, AMD or global scope module, from npm or directly from github.com +can keep on doing that for now. + +For those projects who would rather want to use mustache.js as an ES module, the `mustache/mustache.mjs` file has to +be `import`ed directly. + +Below are some usage scenarios for different runtimes. + +#### Modern browser with ES module support + +```html + + +``` + +#### [Node.js](https://nodejs.org) (>= v13.2.0 or using --experimental-modules flag) + +```js +// index.mjs +import mustache from 'mustache/mustache.mjs' + +console.log(mustache.render('Hello {{name}}!', { name: 'Santa' })) +// Hello Santa! +``` + +ES Module support for Node.js will be improved in the future when [Conditional Exports](https://nodejs.org/api/esm.html#esm_conditional_exports) +is enabled by default rather than being behind an experimental flag. + +More info in [Node.js ECMAScript Modules docs](https://nodejs.org/api/esm.html). + +#### [Deno](https://deno.land/) + +```js +// index.ts +import mustache from 'https://unpkg.com/mustache@3.2.0/mustache.mjs' + +console.log(mustache.render('Hello {{name}}!', { name: 'Santa' })) +// Hello Santa! +``` + +## [3.1.0] / 13 September 2019 + +### Added + + * [#717]: Added support .js files as views in command line tool, by [@JEStaubach]. + +### Fixed + + * [#716]: Bugfix for indentation of inline partials, by [@yotammadem]. + +## [3.0.3] / 27 August 2019 + +### Added + + * [#713]: Add test cases for custom functions in partials, by [@wol-soft]. + +### Fixed + + * [#714]: Bugfix for wrong function output in partials with indentation, by [@phillipj]. + +## [3.0.2] / 21 August 2019 + +### Fixed + + * [#705]: Fix indentation of partials, by [@kevindew] and [@yotammadem]. + +### Dev + + * [#701]: Fix test failure for Node 10 and above, by [@andersk]. + * [#704]: Lint all test files just like the source files, by [@phillipj]. + * Start experimenting & comparing GitHub Actions vs Travis CI, by [@phillipj]. + +## [3.0.1] / 11 November 2018 + + * [#679]: Fix partials not rendering tokens when using custom tags, by [@stackchain]. + +## [3.0.0] / 16 September 2018 + +We are very happy to announce a new major version of mustache.js. We want to be very careful not to break projects +out in the wild, and adhering to [Semantic Versioning](http://semver.org/) we have therefore cut this new major version. + +The changes introduced will likely not require any actions for most using projects. The things to look out for that +might cause unexpected rendering results are described in the migration guide below. + +A big shout out and thanks to [@raymond-lam] for this release! Without his contributions with code and issue triaging, +this release would never have happened. + +### Major + +* [#618]: Allow rendering properties of primitive types that are not objects, by [@raymond-lam]. +* [#643]: `Writer.prototype.parse` to cache by tags in addition to template string, by [@raymond-lam]. +* [#664]: Fix `Writer.prototype.parse` cache, by [@seminaoki]. + +### Minor + +* [#673]: Add `tags` parameter to `Mustache.render()`, by [@raymond-lam]. + +### Migrating from mustache.js v2.x to v3.x + +#### Rendering properties of primitive types + +We have ensured properties of primitive types can be rendered at all times. That means `Array.length`, `String.length` +and similar. A corner case where this could cause unexpected output follows: + +View: +``` +{ + stooges: [ + { name: "Moe" }, + { name: "Larry" }, + { name: "Curly" } + ] +} +``` + +Template: +``` +{{#stooges}} + {{name}}: {{name.length}} characters +{{/stooges}} +``` + +Output with v3.0: +``` + Moe: 3 characters + Larry: 5 characters + Curly: 5 characters +``` + +Output with v2.x: +``` + Moe: characters + Larry: characters + Curly: characters +``` + +#### Caching for templates with custom delimiters + +We have improved the templates cache to ensure custom delimiters are taken into consideration for the cache. +This improvement might cause unexpected rendering behaviour for using projects actively using the custom delimiters functionality. + +Previously it was possible to use `Mustache.parse()` as a means to set global custom delimiters. If custom +delimiters were provided as an argument, it would affect all following calls to `Mustache.render()`. +Consider the following: + +```js +const template = "[[item.title]] [[item.value]]"; +mustache.parse(template, ["[[", "]]"]); + +console.log( + mustache.render(template, { + item: { + title: "TEST", + value: 1 + } + }) +); + +>> TEST 1 +``` + +The above illustrates the fact that `Mustache.parse()` made mustache.js cache the template without considering +the custom delimiters provided. This is no longer true. + +We no longer encourage using `Mustache.parse()` for this purpose, but have rather added a fourth argument to +`Mustache.render()` letting you provide custom delimiters when rendering. + +If you still need the pre-parse the template and use custom delimiters at the same time, ensure to provide +the custom delimiters as argument to `Mustache.render()` as well. + +## [2.3.2] / 17 August 2018 + +This release is made to revert changes introduced in [2.3.1] that caused unexpected behaviour for several users. + +### Minor + + * [#670]: Rollback template cache causing unexpected behaviour, by [@raymond-lam]. + +## [2.3.1] / 7 August 2018 + +### Minor + + * [#643]: `Writer.prototype.parse` to cache by tags in addition to template string, by [@raymond-lam]. + * [#664]: Fix `Writer.prototype.parse` cache, by [@seminaoki]. + +### Dev + + * [#666]: Install release tools with npm rather than pre-commit hook & `Rakefile`, by [@phillipj]. + * [#667], [#668]: Stabilize browser test suite, by [@phillipj]. + +### Docs + + * [#644]: Document global Mustache.escape overriding capacity, by [@paultopia]. + * [#657]: Correct `Mustache.parse()` return type documentation, by [@bbrooks]. + +## [2.3.0] / 8 November 2016 + +### Minor + + * [#540]: Add optional `output` argument to mustache CLI, by [@wizawu]. + * [#597]: Add compatibility with amdclean, by [@mightyplow]. + +### Dev + + * [#553]: Assert `null` lookup when rendering an unescaped value, by [@dasilvacontin]. + * [#580], [#610]: Ignore eslint for greenkeeper updates, by [@phillipj]. + * [#560]: Fix CLI tests for Windows, by [@kookookchoozeus]. + * Run browser tests w/node v4, by [@phillipj]. + +### Docs + + * [#542]: Add API documentation to README, by [@tomekwi]. + * [#546]: Add missing syntax highlighting to README code blocks, by [@pra85]. + * [#569]: Update Ctemplate links in README, by [@mortonfox]. + * [#592]: Change "loadUser" to "loadUser()" in README, by [@Flaque]. + * [#593]: Adding doctype to HTML code example in README, by [@calvinf]. + +### Dependencies + + * eslint -> 2.2.0. Breaking changes fix by [@phillipj]. [#548] + * eslint -> 2.5.1. + * mocha -> 3.0.2. + * zuul -> 3.11.0. + +## [2.2.1] / 13 December 2015 + +### Fixes + + * Improve HTML escaping, by [@phillipj]. + * Fix inconsistency in defining global mustache object, by [@simast]. + * Fix switch-case indent error, by [@norfish]. + * Unpin chai and eslint versions, by [@dasilvacontin]. + * Update README.md with proper grammar, by [@EvanLovely]. + * Update mjackson username in README, by [@mjackson]. + * Remove syntax highlighting in README code sample, by [@imagentleman]. + * Fix typo in README, by [@Xcrucifier]. + * Fix link typo in README, by [@keirog]. + +## [2.2.0] / 15 October 2015 + +### Added + + * Add Partials support to CLI, by [@palkan]. + +### Changed + + * Move install instructions to README's top, by [@mateusortiz] + * Improved devhook install output, by [@ShashankaNataraj]. + * Clarifies and improves language in documentation, by [@jfmercer]. + * Linting CLI tool, by [@phillipj]. + * npm 2.x and node v4 on Travis, by [@phillipj]. + +### Fixes + + * Fix README spelling error to "aforementioned", by [@djchie]. + * Equal error message test in .render() for server and browser, by [@phillipj]. + +### Dependencies + + * chai -> 3.3.0 + * eslint -> 1.6.0 + +## [2.1.3] / 23 July 2015 + +### Added + + * Throw error when providing .render() with invalid template type, by [@phillipj]. + * Documents use of string literals containing double quotes, by [@jfmercer]. + +### Changed + + * Move mustache gif to githubusercontent, by [@Andersos]. + +### Fixed + + * Update UMD Shim to be resilient to HTMLElement global pollution, by [@mikesherov]. + +## [2.1.2] / 17 June 2015 + +### Added + + * Mustache global definition ([#466]) by [@yousefcisco]. + +## [2.1.1] / 11 June 2015 + +### Added + + * State that we use semver on the change log, by [@dasilvacontin]. + * Added version links to change log, by [@dasilvacontin]. + +### Fixed + + * Bugfix for using values from view's context prototype, by [@phillipj]. + * Improve test with undefined/null lookup hit using dot notation, by [@dasilvacontin]. + * Bugfix for null/undefined lookup hit when using dot notation, by [@phillipj]. + * Remove moot `version` property from bower.json, by [@kkirsche]. + * bower.json doesn't require a version bump via hook, by [@dasilvacontin]. + + +## [2.1.0] / 5 June 2015 + + * Added license attribute to package.json, by [@pgilad]. + * Minor changes to make mustache.js compatible with both WSH and ASP, by [@nagaozen]. + * Improve CLI view parsing error, by [@phillipj]. + * Bugfix for view context cache, by [@phillipj]. + +## [2.0.0] / 27 Mar 2015 + + * Fixed lookup not stopping upon finding `undefined` or `null` values, by [@dasilvacontin]. + * Refactored pre-commit hook, by [@dasilvacontin]. + +## [1.2.0] / 24 Mar 2015 + + * Added -v option to CLI, by [@phillipj]. + * Bugfix for rendering Number when it serves as the Context, by [@phillipj]. + * Specified files in package.json for a cleaner install, by [@phillipj]. + +## [1.1.0] / 18 Feb 2015 + + * Refactor Writer.renderTokens() for better readability, by [@phillipj]. + * Cleanup tests section in readme, by [@phillipj]. + * Added JSHint to tests/CI, by [@phillipj]. + * Added node v0.12 on travis, by [@phillipj]. + * Created command line tool, by [@phillipj]. + * Added *falsy* to Inverted Sections description in README, by [@kristijanmatic]. + +## [1.0.0] / 20 Dec 2014 + + * Inline tag compilation, by [@mjackson]. + * Fixed AMD registration, volo package.json entry, by [@jrburke]. + * Added spm support, by [@afc163]. + * Only access properties of objects on Context.lookup, by [@cmbuckley]. + +## [0.8.2] / 17 Mar 2014 + + * Supporting Bower through a bower.json file. + +## [0.8.1] / 3 Jan 2014 + + * Fix usage of partial templates. + +## [0.8.0] / 2 Dec 2013 + + * Remove compile* writer functions, use mustache.parse instead. Smaller API. + * Throw an error when rendering a template that contains higher-order sections and + the original template is not provided. + * Remove low-level Context.make function. + * Better code readability and inline documentation. + * Stop caching templates by name. + +## [0.7.3] / 5 Nov 2013 + + * Don't require the original template to be passed to the rendering function + when using compiled templates. This is still required when using higher-order + functions in order to be able to extract the portion of the template + that was contained by that section. Fixes [#262]. + * Performance improvements. + +## [0.7.2] / 27 Dec 2012 + + * Fixed a rendering bug ([#274]) when using nested higher-order sections. + * Better error reporting on failed parse. + * Converted tests to use mocha instead of vows. + +## [0.7.1] / 6 Dec 2012 + + * Handle empty templates gracefully. Fixes [#265], [#267], and [#270]. + * Cache partials by template, not by name. Fixes [#257]. + * Added Mustache.compileTokens to compile the output of Mustache.parse. Fixes + [#258]. + +## [0.7.0] / 10 Sep 2012 + + * Rename Renderer => Writer. + * Allow partials to be loaded dynamically using a callback (thanks + [@TiddoLangerak] for the suggestion). + * Fixed a bug with higher-order sections that prevented them from being + passed the raw text of the section from the original template. + * More concise token format. Tokens also include start/end indices in the + original template. + * High-level API is consistent with the Writer API. + * Allow partials to be passed to the pre-compiled function (thanks + [@fallenice]). + * Don't use eval (thanks [@cweider]). + +## [0.6.0] / 31 Aug 2012 + + * Use JavaScript's definition of falsy when determining whether to render an + inverted section or not. Issue [#186]. + * Use Mustache.escape to escape values inside {{}}. This function may be + reassigned to alter the default escaping behavior. Issue [#244]. + * Fixed a bug that clashed with QUnit (thanks [@kannix]). + * Added volo support (thanks [@guybedford]). + +[4.1.0]: https://github.com/janl/mustache.js/compare/v4.0.1...v4.1.0 +[4.0.1]: https://github.com/janl/mustache.js/compare/v4.0.0...v4.0.1 +[4.0.0]: https://github.com/janl/mustache.js/compare/v3.2.1...v4.0.0 +[3.2.1]: https://github.com/janl/mustache.js/compare/v3.2.0...v3.2.1 +[3.2.0]: https://github.com/janl/mustache.js/compare/v3.1.0...v3.2.0 +[3.1.0]: https://github.com/janl/mustache.js/compare/v3.0.3...v3.1.0 +[3.0.3]: https://github.com/janl/mustache.js/compare/v3.0.2...v3.0.3 +[3.0.2]: https://github.com/janl/mustache.js/compare/v3.0.1...v3.0.2 +[3.0.1]: https://github.com/janl/mustache.js/compare/v3.0.0...v3.0.1 +[3.0.0]: https://github.com/janl/mustache.js/compare/v2.3.2...v3.0.0 +[2.3.2]: https://github.com/janl/mustache.js/compare/v2.3.1...v2.3.2 +[2.3.1]: https://github.com/janl/mustache.js/compare/v2.3.0...v2.3.1 +[2.3.0]: https://github.com/janl/mustache.js/compare/v2.2.1...v2.3.0 +[2.2.1]: https://github.com/janl/mustache.js/compare/v2.2.0...v2.2.1 +[2.2.0]: https://github.com/janl/mustache.js/compare/v2.1.3...v2.2.0 +[2.1.3]: https://github.com/janl/mustache.js/compare/v2.1.2...v2.1.3 +[2.1.2]: https://github.com/janl/mustache.js/compare/v2.1.1...v2.1.2 +[2.1.1]: https://github.com/janl/mustache.js/compare/v2.1.0...v2.1.1 +[2.1.0]: https://github.com/janl/mustache.js/compare/v2.0.0...v2.1.0 +[2.0.0]: https://github.com/janl/mustache.js/compare/v1.2.0...v2.0.0 +[1.2.0]: https://github.com/janl/mustache.js/compare/v1.1.0...v1.2.0 +[1.1.0]: https://github.com/janl/mustache.js/compare/v1.0.0...v1.1.0 +[1.0.0]: https://github.com/janl/mustache.js/compare/0.8.2...v1.0.0 +[0.8.2]: https://github.com/janl/mustache.js/compare/0.8.1...0.8.2 +[0.8.1]: https://github.com/janl/mustache.js/compare/0.8.0...0.8.1 +[0.8.0]: https://github.com/janl/mustache.js/compare/0.7.3...0.8.0 +[0.7.3]: https://github.com/janl/mustache.js/compare/0.7.2...0.7.3 +[0.7.2]: https://github.com/janl/mustache.js/compare/0.7.1...0.7.2 +[0.7.1]: https://github.com/janl/mustache.js/compare/0.7.0...0.7.1 +[0.7.0]: https://github.com/janl/mustache.js/compare/0.6.0...0.7.0 +[0.6.0]: https://github.com/janl/mustache.js/compare/0.5.2...0.6.0 + +[#186]: https://github.com/janl/mustache.js/issues/186 +[#244]: https://github.com/janl/mustache.js/issues/244 +[#257]: https://github.com/janl/mustache.js/issues/257 +[#258]: https://github.com/janl/mustache.js/issues/258 +[#262]: https://github.com/janl/mustache.js/issues/262 +[#265]: https://github.com/janl/mustache.js/issues/265 +[#267]: https://github.com/janl/mustache.js/issues/267 +[#270]: https://github.com/janl/mustache.js/issues/270 +[#274]: https://github.com/janl/mustache.js/issues/274 +[#466]: https://github.com/janl/mustache.js/issues/466 +[#540]: https://github.com/janl/mustache.js/issues/540 +[#542]: https://github.com/janl/mustache.js/issues/542 +[#546]: https://github.com/janl/mustache.js/issues/546 +[#548]: https://github.com/janl/mustache.js/issues/548 +[#553]: https://github.com/janl/mustache.js/issues/553 +[#560]: https://github.com/janl/mustache.js/issues/560 +[#569]: https://github.com/janl/mustache.js/issues/569 +[#580]: https://github.com/janl/mustache.js/issues/580 +[#592]: https://github.com/janl/mustache.js/issues/592 +[#593]: https://github.com/janl/mustache.js/issues/593 +[#597]: https://github.com/janl/mustache.js/issues/597 +[#610]: https://github.com/janl/mustache.js/issues/610 +[#643]: https://github.com/janl/mustache.js/issues/643 +[#644]: https://github.com/janl/mustache.js/issues/644 +[#657]: https://github.com/janl/mustache.js/issues/657 +[#664]: https://github.com/janl/mustache.js/issues/664 +[#666]: https://github.com/janl/mustache.js/issues/666 +[#667]: https://github.com/janl/mustache.js/issues/667 +[#668]: https://github.com/janl/mustache.js/issues/668 +[#670]: https://github.com/janl/mustache.js/issues/670 +[#618]: https://github.com/janl/mustache.js/issues/618 +[#673]: https://github.com/janl/mustache.js/issues/673 +[#679]: https://github.com/janl/mustache.js/issues/679 +[#701]: https://github.com/janl/mustache.js/issues/701 +[#704]: https://github.com/janl/mustache.js/issues/704 +[#705]: https://github.com/janl/mustache.js/issues/705 +[#713]: https://github.com/janl/mustache.js/issues/713 +[#714]: https://github.com/janl/mustache.js/issues/714 +[#716]: https://github.com/janl/mustache.js/issues/716 +[#717]: https://github.com/janl/mustache.js/issues/717 +[#728]: https://github.com/janl/mustache.js/issues/728 +[#733]: https://github.com/janl/mustache.js/issues/733 +[#731]: https://github.com/janl/mustache.js/issues/731 +[#735]: https://github.com/janl/mustache.js/issues/735 +[#739]: https://github.com/janl/mustache.js/issues/739 +[#764]: https://github.com/janl/mustache.js/issues/764 +[#773]: https://github.com/janl/mustache.js/issues/773 + +[@afc163]: https://github.com/afc163 +[@aielo]: https://github.com/aielo +[@andersk]: https://github.com/andersk +[@Andersos]: https://github.com/Andersos +[@AndrewLeedham]: https://github.com/AndrewLeedham +[@bbrooks]: https://github.com/bbrooks +[@calvinf]: https://github.com/calvinf +[@cmbuckley]: https://github.com/cmbuckley +[@cweider]: https://github.com/cweider +[@dasilvacontin]: https://github.com/dasilvacontin +[@djchie]: https://github.com/djchie +[@eobrain]: https://github.com/eobrain +[@EvanLovely]: https://github.com/EvanLovely +[@fallenice]: https://github.com/fallenice +[@Flaque]: https://github.com/Flaque +[@guybedford]: https://github.com/guybedford +[@imagentleman]: https://github.com/imagentleman +[@JEStaubach]: https://github.com/JEStaubach +[@jfmercer]: https://github.com/jfmercer +[@jrburke]: https://github.com/jrburke +[@kannix]: https://github.com/kannix +[@keirog]: https://github.com/keirog +[@kkirsche]: https://github.com/kkirsche +[@kookookchoozeus]: https://github.com/kookookchoozeus +[@kristijanmatic]: https://github.com/kristijanmatic +[@kevindew]: https://github.com/kevindew +[@manzt]: https://github.com/manzt +[@mateusortiz]: https://github.com/mateusortiz +[@mightyplow]: https://github.com/mightyplow +[@mikesherov]: https://github.com/mikesherov +[@mjackson]: https://github.com/mjackson +[@mortonfox]: https://github.com/mortonfox +[@nagaozen]: https://github.com/nagaozen +[@norfish]: https://github.com/norfish +[@palkan]: https://github.com/palkan +[@paultopia]: https://github.com/paultopia +[@pgilad]: https://github.com/pgilad +[@phillipj]: https://github.com/phillipj +[@pineapplemachine]: https://github.com/pineapplemachine +[@pra85]: https://github.com/pra85 +[@raymond-lam]: https://github.com/raymond-lam +[@seminaoki]: https://github.com/seminaoki +[@ShashankaNataraj]: https://github.com/ShashankaNataraj +[@simast]: https://github.com/simast +[@stackchain]: https://github.com/stackchain +[@TiddoLangerak]: https://github.com/TiddoLangerak +[@tomekwi]: https://github.com/tomekwi +[@wizawu]: https://github.com/wizawu +[@wol-soft]: https://github.com/wol-soft +[@Xcrucifier]: https://github.com/Xcrucifier +[@yotammadem]: https://github.com/yotammadem +[@yousefcisco]: https://github.com/yousefcisco +[@zekth]: https://github.com/zekth diff --git a/node_modules/mustache/LICENSE b/node_modules/mustache/LICENSE new file mode 100644 index 0000000..4df7d1a --- /dev/null +++ b/node_modules/mustache/LICENSE @@ -0,0 +1,11 @@ +The MIT License + +Copyright (c) 2009 Chris Wanstrath (Ruby) +Copyright (c) 2010-2014 Jan Lehnardt (JavaScript) +Copyright (c) 2010-2015 The mustache.js community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mustache/README.md b/node_modules/mustache/README.md new file mode 100644 index 0000000..127dfe1 --- /dev/null +++ b/node_modules/mustache/README.md @@ -0,0 +1,621 @@ +# mustache.js - Logic-less {{mustache}} templates with JavaScript + +> What could be more logical awesome than no logic at all? + +[![Build Status](https://travis-ci.org/janl/mustache.js.svg?branch=master)](https://travis-ci.org/janl/mustache.js) + +[mustache.js](http://github.com/janl/mustache.js) is a zero-dependency implementation of the [mustache](http://mustache.github.com/) template system in JavaScript. + +[Mustache](http://mustache.github.com/) is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. + +We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values. + +For a language-agnostic overview of mustache's template syntax, see the `mustache(5)` [manpage](http://mustache.github.com/mustache.5.html). + +## Where to use mustache.js? + +You can use mustache.js to render mustache templates anywhere you can use JavaScript. This includes web browsers, server-side environments such as [Node.js](http://nodejs.org/), and [CouchDB](http://couchdb.apache.org/) views. + +mustache.js ships with support for the [CommonJS](http://www.commonjs.org/) module API, the [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) API (AMD) and [ECMAScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). + +In addition to being a package to be used programmatically, you can use it as a [command line tool](#command-line-tool). + +And this will be your templates after you use Mustache: + +!['stache](https://cloud.githubusercontent.com/assets/288977/8779228/a3cf700e-2f02-11e5-869a-300312fb7a00.gif) + +## Install + +You can get Mustache via [npm](http://npmjs.com). + +```bash +$ npm install mustache --save +``` + +## Usage + +Below is a quick example how to use mustache.js: + +```js +var view = { + title: "Joe", + calc: function () { + return 2 + 4; + } +}; + +var output = Mustache.render("{{title}} spends {{calc}}", view); +``` + +In this example, the `Mustache.render` function takes two parameters: 1) the [mustache](http://mustache.github.com/) template and 2) a `view` object that contains the data and code needed to render the template. + +## Templates + +A [mustache](http://mustache.github.com/) template is a string that contains any number of mustache tags. Tags are indicated by the double mustaches that surround them. `{{person}}` is a tag, as is `{{#person}}`. In both examples we refer to `person` as the tag's key. There are several types of tags available in mustache.js, described below. + +There are several techniques that can be used to load templates and hand them to mustache.js, here are two of them: + +#### Include Templates + +If you need a template for a dynamic part in a static website, you can consider including the template in the static HTML file to avoid loading templates separately. Here's a small example: + +```js +// file: render.js + +function renderHello() { + var template = document.getElementById('template').innerHTML; + var rendered = Mustache.render(template, { name: 'Luke' }); + document.getElementById('target').innerHTML = rendered; +} +``` + +```html + + +

Loading...
+ + + + + + +``` + +#### Load External Templates + +If your templates reside in individual files, you can load them asynchronously and render them when they arrive. Another example using [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch): + +```js +function renderHello() { + fetch('template.mustache') + .then((response) => response.text()) + .then((template) => { + var rendered = Mustache.render(template, { name: 'Luke' }); + document.getElementById('target').innerHTML = rendered; + }); +} +``` + +### Variables + +The most basic tag type is a simple variable. A `{{name}}` tag renders the value of the `name` key in the current context. If there is no such key, nothing is rendered. + +All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: `{{{name}}}`. You can also use `&` to unescape a variable. + +If you'd like to change HTML-escaping behavior globally (for example, to template non-HTML formats), you can override Mustache's escape function. For example, to disable all escaping: `Mustache.escape = function(text) {return text;};`. + +If you want `{{name}}` _not_ to be interpreted as a mustache tag, but rather to appear exactly as `{{name}}` in the output, you must change and then restore the default delimiter. See the [Custom Delimiters](#custom-delimiters) section for more information. + +View: + +```json +{ + "name": "Chris", + "company": "GitHub" +} +``` + +Template: + +``` +* {{name}} +* {{age}} +* {{company}} +* {{{company}}} +* {{&company}} +{{=<% %>=}} +* {{company}} +<%={{ }}=%> +``` + +Output: + +```html +* Chris +* +* <b>GitHub</b> +* GitHub +* GitHub +* {{company}} +``` + +JavaScript's dot notation may be used to access keys that are properties of objects in a view. + +View: + +```json +{ + "name": { + "first": "Michael", + "last": "Jackson" + }, + "age": "RIP" +} +``` + +Template: + +```html +* {{name.first}} {{name.last}} +* {{age}} +``` + +Output: + +```html +* Michael Jackson +* RIP +``` + +### Sections + +Sections render blocks of text zero or more times, depending on the value of the key in the current context. + +A section begins with a pound and ends with a slash. That is, `{{#person}}` begins a `person` section, while `{{/person}}` ends it. The text between the two tags is referred to as that section's "block". + +The behavior of the section is determined by the value of the key. + +#### False Values or Empty Lists + +If the `person` key does not exist, or exists and has a value of `null`, `undefined`, `false`, `0`, or `NaN`, or is an empty string or an empty list, the block will not be rendered. + +View: + +```json +{ + "person": false +} +``` + +Template: + +```html +Shown. +{{#person}} +Never shown! +{{/person}} +``` + +Output: + +```html +Shown. +``` + +#### Non-Empty Lists + +If the `person` key exists and is not `null`, `undefined`, or `false`, and is not an empty list the block will be rendered one or more times. + +When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way we can loop over collections. + +View: + +```json +{ + "stooges": [ + { "name": "Moe" }, + { "name": "Larry" }, + { "name": "Curly" } + ] +} +``` + +Template: + +```html +{{#stooges}} +{{name}} +{{/stooges}} +``` + +Output: + +```html +Moe +Larry +Curly +``` + +When looping over an array of strings, a `.` can be used to refer to the current item in the list. + +View: + +```json +{ + "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] +} +``` + +Template: + +```html +{{#musketeers}} +* {{.}} +{{/musketeers}} +``` + +Output: + +```html +* Athos +* Aramis +* Porthos +* D'Artagnan +``` + +If the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration. + +View: + +```js +{ + "beatles": [ + { "firstName": "John", "lastName": "Lennon" }, + { "firstName": "Paul", "lastName": "McCartney" }, + { "firstName": "George", "lastName": "Harrison" }, + { "firstName": "Ringo", "lastName": "Starr" } + ], + "name": function () { + return this.firstName + " " + this.lastName; + } +} +``` + +Template: + +```html +{{#beatles}} +* {{name}} +{{/beatles}} +``` + +Output: + +```html +* John Lennon +* Paul McCartney +* George Harrison +* Ringo Starr +``` + +#### Functions + +If the value of a section key is a function, it is called with the section's literal block of text, un-rendered, as its first argument. The second argument is a special rendering function that uses the current view as its view argument. It is called in the context of the current view object. + +View: + +```js +{ + "name": "Tater", + "bold": function () { + return function (text, render) { + return "" + render(text) + ""; + } + } +} +``` + +Template: + +```html +{{#bold}}Hi {{name}}.{{/bold}} +``` + +Output: + +```html +Hi Tater. +``` + +### Inverted Sections + +An inverted section opens with `{{^section}}` instead of `{{#section}}`. The block of an inverted section is rendered only if the value of that section's tag is `null`, `undefined`, `false`, *falsy* or an empty list. + +View: + +```json +{ + "repos": [] +} +``` + +Template: + +```html +{{#repos}}{{name}}{{/repos}} +{{^repos}}No repos :({{/repos}} +``` + +Output: + +```html +No repos :( +``` + +### Comments + +Comments begin with a bang and are ignored. The following template: + +```html +

Today{{! ignore me }}.

+``` + +Will render as follows: + +```html +

Today.

+``` + +Comments may contain newlines. + +### Partials + +Partials begin with a greater than sign, like {{> box}}. + +Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops. + +They also inherit the calling context. Whereas in ERB you may have this: + +```html+erb +<%= partial :next_more, :start => start, :size => size %> +``` + +Mustache requires only this: + +```html +{{> next_more}} +``` + +Why? Because the `next_more.mustache` file will inherit the `size` and `start` variables from the calling context. In this way you may want to think of partials as includes, imports, template expansion, nested templates, or subtemplates, even though those aren't literally the case here. + + +For example, this template and partial: + + base.mustache: +

Names

+ {{#names}} + {{> user}} + {{/names}} + + user.mustache: + {{name}} + +Can be thought of as a single, expanded template: + +```html +

Names

+{{#names}} + {{name}} +{{/names}} +``` + +In mustache.js an object of partials may be passed as the third argument to `Mustache.render`. The object should be keyed by the name of the partial, and its value should be the partial text. + +```js +Mustache.render(template, view, { + user: userTemplate +}); +``` + +### Custom Delimiters + +Custom delimiters can be used in place of `{{` and `}}` by setting the new values in JavaScript or in templates. + +#### Setting in JavaScript + +The `Mustache.tags` property holds an array consisting of the opening and closing tag values. Set custom values by passing a new array of tags to `render()`, which gets honored over the default values, or by overriding the `Mustache.tags` property itself: + +```js +var customTags = [ '<%', '%>' ]; +``` + +##### Pass Value into Render Method +```js +Mustache.render(template, view, {}, customTags); +``` + +##### Override Tags Property +```js +Mustache.tags = customTags; +// Subsequent parse() and render() calls will use customTags +``` + +#### Setting in Templates + +Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings. + +Consider the following contrived example: + +```html+erb +* {{ default_tags }} +{{=<% %>=}} +* <% erb_style_tags %> +<%={{ }}=%> +* {{ default_tags_again }} +``` + +Here we have a list with three items. The first item uses the default tag style, the second uses ERB style as defined by the Set Delimiter tag, and the third returns to the default style after yet another Set Delimiter declaration. + +According to [ctemplates](https://htmlpreview.github.io/?https://raw.githubusercontent.com/OlafvdSpek/ctemplate/master/doc/howto.html), this "is useful for languages like TeX, where double-braces may occur in the text and are awkward to use for markup." + +Custom delimiters may not contain whitespace or the equals sign. + +## Pre-parsing and Caching Templates + +By default, when mustache.js first parses a template it keeps the full parsed token tree in a cache. The next time it sees that same template it skips the parsing step and renders the template much more quickly. If you'd like, you can do this ahead of time using `mustache.parse`. + +```js +Mustache.parse(template); + +// Then, sometime later. +Mustache.render(template, view); +``` + +## Command line tool + +mustache.js is shipped with a Node.js based command line tool. It might be installed as a global tool on your computer to render a mustache template of some kind + +```bash +$ npm install -g mustache + +$ mustache dataView.json myTemplate.mustache > output.html +``` + +also supports stdin. + +```bash +$ cat dataView.json | mustache - myTemplate.mustache > output.html +``` + +or as a package.json `devDependency` in a build process maybe? + +```bash +$ npm install mustache --save-dev +``` + +```json +{ + "scripts": { + "build": "mustache dataView.json myTemplate.mustache > public/output.html" + } +} +``` +```bash +$ npm run build +``` + +The command line tool is basically a wrapper around `Mustache.render` so you get all the features. + +If your templates use partials you should pass paths to partials using `-p` flag: + +```bash +$ mustache -p path/to/partial1.mustache -p path/to/partial2.mustache dataView.json myTemplate.mustache +``` + +## Plugins for JavaScript Libraries + +mustache.js may be built specifically for several different client libraries, including the following: + + - [jQuery](http://jquery.com/) + - [MooTools](http://mootools.net/) + - [Dojo](http://www.dojotoolkit.org/) + - [YUI](http://developer.yahoo.com/yui/) + - [qooxdoo](http://qooxdoo.org/) + +These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands: +```bash +$ rake jquery +$ rake mootools +$ rake dojo +$ rake yui3 +$ rake qooxdoo +``` + +## TypeScript + +Since the source code of this package is written in JavaScript, we follow the [TypeScript publishing docs](https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) preferred approach +by having type definitions available via [@types/mustache](https://www.npmjs.com/package/@types/mustache). + +## Testing + +In order to run the tests you'll need to install [Node.js](http://nodejs.org/). + +You also need to install the sub module containing [Mustache specifications](http://github.com/mustache/spec) in the project root. +```bash +$ git submodule init +$ git submodule update +``` +Install dependencies. +```bash +$ npm install +``` +Then run the tests. +```bash +$ npm test +``` +The test suite consists of both unit and integration tests. If a template isn't rendering correctly for you, you can make a test for it by doing the following: + + 1. Create a template file named `mytest.mustache` in the `test/_files` + directory. Replace `mytest` with the name of your test. + 2. Create a corresponding view file named `mytest.js` in the same directory. + This file should contain a JavaScript object literal enclosed in + parentheses. See any of the other view files for an example. + 3. Create a file with the expected output in `mytest.txt` in the same + directory. + +Then, you can run the test with: +```bash +$ TEST=mytest npm run test-render +``` + +### Browser tests + +Browser tests are not included in `npm test` as they run for too long, although they are ran automatically on Travis when merged into master. Run browser tests locally in any browser: +```bash +$ npm run test-browser-local +``` +then point your browser to `http://localhost:8080/__zuul` + +## Who uses mustache.js? + +An updated list of mustache.js users is kept [on the Github wiki](https://github.com/janl/mustache.js/wiki/Beard-Competition). Add yourself or your company if you use mustache.js! + +## Contributing + +mustache.js is a mature project, but it continues to actively invite maintainers. You can help out a high-profile project that is used in a lot of places on the web. No big commitment required, if all you do is review a single [Pull Request](https://github.com/janl/mustache.js/pulls), you are a maintainer. And a hero. + +### Your First Contribution + +- review a [Pull Request](https://github.com/janl/mustache.js/pulls) +- fix an [Issue](https://github.com/janl/mustache.js/issues) +- update the [documentation](https://github.com/janl/mustache.js#usage) +- make a website +- write a tutorial + +## Thanks + +mustache.js wouldn't kick ass if it weren't for these fine souls: + + * Chris Wanstrath / defunkt + * Alexander Lang / langalex + * Sebastian Cohnen / tisba + * J Chris Anderson / jchris + * Tom Robinson / tlrobinson + * Aaron Quint / quirkey + * Douglas Crockford + * Nikita Vasilyev / NV + * Elise Wood / glytch + * Damien Mathieu / dmathieu + * Jakub Kuźma / qoobaa + * Will Leinweber / will + * dpree + * Jason Smith / jhs + * Aaron Gibralter / agibralter + * Ross Boucher / boucher + * Matt Sanford / mzsanford + * Ben Cherry / bcherry + * Michael Jackson / mjackson + * Phillip Johnsen / phillipj + * David da Silva Contín / dasilvacontin diff --git a/node_modules/mustache/bin/mustache b/node_modules/mustache/bin/mustache new file mode 100755 index 0000000..6db073f --- /dev/null +++ b/node_modules/mustache/bin/mustache @@ -0,0 +1,150 @@ +#!/usr/bin/env node + +var fs = require('fs'), + path = require('path'); + +var Mustache = require('..'); +var pkg = require('../package'); +var partials = {}; + +var partialsPaths = []; +var partialArgIndex = -1; + +while ((partialArgIndex = process.argv.indexOf('-p')) > -1) { + partialsPaths.push(process.argv.splice(partialArgIndex, 2)[1]); +} + +var viewArg = process.argv[2]; +var templateArg = process.argv[3]; +var outputArg = process.argv[4]; + +if (hasVersionArg()) { + return console.log(pkg.version); +} + +if (!templateArg || !viewArg) { + console.error('Syntax: mustache