diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 39539e9..a7d3165 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,9 +11,17 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ubuntu-latest, windows-latest, macos-latest] + os: + - ubuntu-latest + - windows-latest + - macos-latest deno: - [1.x, "1.33.1", canary, ~1.32, b290fd01f3f5d32f9d010fc719ced0240759c049, rc] + - "1.x" + - "1.33.1" + - "canary" + - "~1.32" + - "b290fd01f3f5d32f9d010fc719ced0240759c049" + - "rc" steps: - uses: actions/checkout@v3 @@ -38,14 +46,6 @@ jobs: deno install --allow-net -n deno_curl https://deno.land/std@0.198.0/examples/curl.ts deno_curl https://deno.land/std@0.198.0/examples/curl.ts - - name: Format - if: runner.os == 'Linux' && matrix.deno == 'canary' - run: npm run fmt:check - - - name: Lint - if: runner.os == 'Linux' && matrix.deno == 'canary' - run: npm run lint - test-version-file: runs-on: ubuntu-latest strategy: @@ -66,7 +66,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ ubuntu-latest, windows-latest, macos-latest ] + os: [ubuntu-latest, windows-latest, macos-latest] steps: - uses: actions/checkout@v3 @@ -77,3 +77,22 @@ jobs: - name: Check binary exists run: deno_foo -V + + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Setup Deno + uses: ./ + with: + deno-version: "rc" + + - name: Lint + run: deno lint + + - name: Format + run: deno fmt --check + + - name: Check types + run: deno check main.mjs diff --git a/action.yml b/action.yml index 4793f7f..1ce03fc 100644 --- a/action.yml +++ b/action.yml @@ -22,4 +22,4 @@ outputs: description: "The release channel of the installed version." runs: using: "node20" - main: "main.js" + main: "main.mjs" diff --git a/deno.json b/deno.json new file mode 100644 index 0000000..f2ce6f1 --- /dev/null +++ b/deno.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "checkJs": true, + "allowJs": true + } +} diff --git a/deno.lock b/deno.lock new file mode 100644 index 0000000..4ddfcbd --- /dev/null +++ b/deno.lock @@ -0,0 +1,98 @@ +{ + "version": "4", + "specifiers": { + "npm:@actions/core@^1.10.1": "1.10.1", + "npm:@actions/tool-cache@^2.0.1": "2.0.1", + "npm:@types/node@^20.16.5": "20.16.5", + "npm:@types/semver@^7.5.8": "7.5.8", + "npm:semver@^7.6.3": "7.6.3", + "npm:undici@^6.19.8": "6.19.8" + }, + "npm": { + "@actions/core@1.10.1": { + "integrity": "sha512-3lBR9EDAY+iYIpTnTIXmWcNbX3T2kCkAEQGIQx4NVQ0575nk2k3GRZDTPQG+vVtS2izSLmINlxXf0uLtnrTP+g==", + "dependencies": [ + "@actions/http-client", + "uuid@8.3.2" + ] + }, + "@actions/exec@1.1.1": { + "integrity": "sha512-+sCcHHbVdk93a0XT19ECtO/gIXoxvdsgQLzb2fE2/5sIZmWQuluYyjPQtrtTHdU1YzTZ7bAPN4sITq2xi1679w==", + "dependencies": [ + "@actions/io" + ] + }, + "@actions/http-client@2.2.3": { + "integrity": "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==", + "dependencies": [ + "tunnel", + "undici@5.28.4" + ] + }, + "@actions/io@1.1.3": { + "integrity": "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q==" + }, + "@actions/tool-cache@2.0.1": { + "integrity": "sha512-iPU+mNwrbA8jodY8eyo/0S/QqCKDajiR8OxWTnSk/SnYg0sj8Hp4QcUEVC1YFpHWXtrfbQrE13Jz4k4HXJQKcA==", + "dependencies": [ + "@actions/core", + "@actions/exec", + "@actions/http-client", + "@actions/io", + "semver@6.3.1", + "uuid@3.4.0" + ] + }, + "@fastify/busboy@2.1.1": { + "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==" + }, + "@types/node@20.16.5": { + "integrity": "sha512-VwYCweNo3ERajwy0IUlqqcyZ8/A7Zwa9ZP3MnENWcB11AejO+tLy3pu850goUW2FC/IJMdZUfKpX/yxL1gymCA==", + "dependencies": [ + "undici-types" + ] + }, + "@types/semver@7.5.8": { + "integrity": "sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==" + }, + "semver@6.3.1": { + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==" + }, + "semver@7.6.3": { + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==" + }, + "tunnel@0.0.6": { + "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==" + }, + "undici-types@6.19.8": { + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==" + }, + "undici@5.28.4": { + "integrity": "sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==", + "dependencies": [ + "@fastify/busboy" + ] + }, + "undici@6.19.8": { + "integrity": "sha512-U8uCCl2x9TK3WANvmBavymRzxbfFYG+tAu+fgx3zxQy3qdagQqBLwJVrdyO1TBfUXvfKveMKJZhpvUYoOjM+4g==" + }, + "uuid@3.4.0": { + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==" + }, + "uuid@8.3.2": { + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" + } + }, + "workspace": { + "packageJson": { + "dependencies": [ + "npm:@actions/core@^1.10.1", + "npm:@actions/tool-cache@^2.0.1", + "npm:@types/node@^20.16.5", + "npm:@types/semver@^7.5.8", + "npm:semver@^7.6.3", + "npm:undici@^6.19.8" + ] + } + } +} diff --git a/main.js b/main.mjs similarity index 83% rename from main.js rename to main.mjs index 3ac236e..4810805 100644 --- a/main.js +++ b/main.mjs @@ -1,12 +1,11 @@ -const process = require("process"); -const core = require("@actions/core"); - -const { - parseVersionRange, +import process from "node:process"; +import core from "@actions/core"; +import { getDenoVersionFromFile, + parseVersionRange, resolveVersion, -} = require("./src/version.js"); -const { install } = require("./src/install.js"); +} from "./src/version.mjs"; +import { install } from "./src/install.mjs"; /** * @param {string} message @@ -46,7 +45,7 @@ async function main() { core.info("Installation complete."); } catch (err) { - core.setFailed(err); + core.setFailed((err instanceof Error) ? err : String(err)); process.exit(); } } diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver index 5aaadf4..6d30f2e 120000 --- a/node_modules/.bin/semver +++ b/node_modules/.bin/semver @@ -1 +1 @@ -../semver/bin/semver.js \ No newline at end of file +../.deno/semver@7.6.3/node_modules/semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/.bin/uuid b/node_modules/.bin/uuid index 588f70e..5d1bd39 120000 --- a/node_modules/.bin/uuid +++ b/node_modules/.bin/uuid @@ -1 +1 @@ -../uuid/dist/bin/uuid \ No newline at end of file +../.deno/uuid@8.3.2/node_modules/uuid/dist/bin/uuid \ No newline at end of file diff --git a/node_modules/.deno/.deno.lock b/node_modules/.deno/.deno.lock new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/.deno/.deno.lock.poll b/node_modules/.deno/.deno.lock.poll new file mode 100644 index 0000000..56a6051 --- /dev/null +++ b/node_modules/.deno/.deno.lock.poll @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/node_modules/.deno/.setup-cache.bin b/node_modules/.deno/.setup-cache.bin new file mode 100644 index 0000000..743dd7b Binary files /dev/null and b/node_modules/.deno/.setup-cache.bin differ diff --git a/node_modules/.deno/@actions+core@1.10.1/.initialized b/node_modules/.deno/@actions+core@1.10.1/.initialized new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/@actions/core/LICENSE.md b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/LICENSE.md similarity index 100% rename from node_modules/@actions/core/LICENSE.md rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/LICENSE.md diff --git a/node_modules/@actions/core/README.md b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/README.md similarity index 97% rename from node_modules/@actions/core/README.md rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/README.md index 3c20c8e..8a47143 100644 --- a/node_modules/@actions/core/README.md +++ b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/README.md @@ -121,7 +121,7 @@ const result = await core.group('Do something async', async () => { This library has 3 methods that will produce [annotations](https://docs.github.com/en/rest/reference/checks#create-a-check-run). ```js -core.error('This is a bad error. This will also fail the build.') +core.error('This is a bad error, action may still succeed though.') core.warning('Something went wrong, but it\'s not bad enough to fail the build.') @@ -163,7 +163,7 @@ export interface AnnotationProperties { startColumn?: number /** - * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. + * The end column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. * Defaults to `startColumn` when `startColumn` is provided. */ endColumn?: number diff --git a/node_modules/@actions/core/lib/command.d.ts b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/command.d.ts similarity index 100% rename from node_modules/@actions/core/lib/command.d.ts rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/command.d.ts diff --git a/node_modules/@actions/core/lib/command.js b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/command.js similarity index 100% rename from node_modules/@actions/core/lib/command.js rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/command.js diff --git a/node_modules/@actions/core/lib/command.js.map b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/command.js.map similarity index 100% rename from node_modules/@actions/core/lib/command.js.map rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/command.js.map diff --git a/node_modules/@actions/core/lib/core.d.ts b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/core.d.ts similarity index 96% rename from node_modules/@actions/core/lib/core.d.ts rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/core.d.ts index 1defb57..ceecdd3 100644 --- a/node_modules/@actions/core/lib/core.d.ts +++ b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/core.d.ts @@ -21,7 +21,7 @@ export declare enum ExitCode { Failure = 1 } /** - * Optional properties that can be sent with annotatation commands (notice, error, and warning) + * Optional properties that can be sent with annotation commands (notice, error, and warning) * See: https://docs.github.com/en/rest/reference/checks#create-a-check-run for more information about annotations. */ export interface AnnotationProperties { @@ -46,7 +46,7 @@ export interface AnnotationProperties { */ startColumn?: number; /** - * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. + * The end column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. * Defaults to `startColumn` when `startColumn` is provided. */ endColumn?: number; diff --git a/node_modules/@actions/core/lib/core.js b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/core.js similarity index 100% rename from node_modules/@actions/core/lib/core.js rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/core.js diff --git a/node_modules/@actions/core/lib/core.js.map b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/core.js.map similarity index 100% rename from node_modules/@actions/core/lib/core.js.map rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/core.js.map diff --git a/node_modules/@actions/core/lib/file-command.d.ts b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/file-command.d.ts similarity index 100% rename from node_modules/@actions/core/lib/file-command.d.ts rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/file-command.d.ts diff --git a/node_modules/@actions/core/lib/file-command.js b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/file-command.js similarity index 100% rename from node_modules/@actions/core/lib/file-command.js rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/file-command.js diff --git a/node_modules/@actions/core/lib/file-command.js.map b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/file-command.js.map similarity index 100% rename from node_modules/@actions/core/lib/file-command.js.map rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/file-command.js.map diff --git a/node_modules/@actions/core/lib/oidc-utils.d.ts b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/oidc-utils.d.ts similarity index 100% rename from node_modules/@actions/core/lib/oidc-utils.d.ts rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/oidc-utils.d.ts diff --git a/node_modules/@actions/core/lib/oidc-utils.js b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/oidc-utils.js similarity index 98% rename from node_modules/@actions/core/lib/oidc-utils.js rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/oidc-utils.js index f701277..092e93d 100644 --- a/node_modules/@actions/core/lib/oidc-utils.js +++ b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/oidc-utils.js @@ -44,7 +44,7 @@ class OidcClient { .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n - Error Message: ${error.result.message}`); + Error Message: ${error.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { diff --git a/node_modules/@actions/core/lib/oidc-utils.js.map b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/oidc-utils.js.map similarity index 58% rename from node_modules/@actions/core/lib/oidc-utils.js.map rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/oidc-utils.js.map index 284fa1d..22506b8 100644 --- a/node_modules/@actions/core/lib/oidc-utils.js.map +++ b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/oidc-utils.js.map @@ -1 +1 @@ -{"version":3,"file":"oidc-utils.js","sourceRoot":"","sources":["../src/oidc-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,sDAA+C;AAC/C,wDAAqE;AACrE,iCAAuC;AAKvC,MAAa,UAAU;IACb,MAAM,CAAC,gBAAgB,CAC7B,UAAU,GAAG,IAAI,EACjB,QAAQ,GAAG,EAAE;QAEb,MAAM,cAAc,GAAmB;YACrC,YAAY,EAAE,UAAU;YACxB,UAAU,EAAE,QAAQ;SACrB,CAAA;QAED,OAAO,IAAI,wBAAU,CACnB,qBAAqB,EACrB,CAAC,IAAI,8BAAuB,CAAC,UAAU,CAAC,eAAe,EAAE,CAAC,CAAC,EAC3D,cAAc,CACf,CAAA;IACH,CAAC;IAEO,MAAM,CAAC,eAAe;QAC5B,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAA;QAC3D,IAAI,CAAC,KAAK,EAAE;YACV,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAA;SACF;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAEO,MAAM,CAAC,aAAa;QAC1B,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAA;QAC9D,IAAI,CAAC,UAAU,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;SAC3E;QACD,OAAO,UAAU,CAAA;IACnB,CAAC;IAEO,MAAM,CAAO,OAAO,CAAC,YAAoB;;;YAC/C,MAAM,UAAU,GAAG,UAAU,CAAC,gBAAgB,EAAE,CAAA;YAEhD,MAAM,GAAG,GAAG,MAAM,UAAU;iBACzB,OAAO,CAAgB,YAAY,CAAC;iBACpC,KAAK,CAAC,KAAK,CAAC,EAAE;gBACb,MAAM,IAAI,KAAK,CACb;uBACa,KAAK,CAAC,UAAU;yBACd,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CACtC,CAAA;YACH,CAAC,CAAC,CAAA;YAEJ,MAAM,QAAQ,SAAG,GAAG,CAAC,MAAM,0CAAE,KAAK,CAAA;YAClC,IAAI,CAAC,QAAQ,EAAE;gBACb,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAA;aACjE;YACD,OAAO,QAAQ,CAAA;;KAChB;IAED,MAAM,CAAO,UAAU,CAAC,QAAiB;;YACvC,IAAI;gBACF,gDAAgD;gBAChD,IAAI,YAAY,GAAW,UAAU,CAAC,aAAa,EAAE,CAAA;gBACrD,IAAI,QAAQ,EAAE;oBACZ,MAAM,eAAe,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAA;oBACpD,YAAY,GAAG,GAAG,YAAY,aAAa,eAAe,EAAE,CAAA;iBAC7D;gBAED,YAAK,CAAC,mBAAmB,YAAY,EAAE,CAAC,CAAA;gBAExC,MAAM,QAAQ,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;gBACvD,gBAAS,CAAC,QAAQ,CAAC,CAAA;gBACnB,OAAO,QAAQ,CAAA;aAChB;YAAC,OAAO,KAAK,EAAE;gBACd,MAAM,IAAI,KAAK,CAAC,kBAAkB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;aACnD;QACH,CAAC;KAAA;CACF;AAzED,gCAyEC"} \ No newline at end of file +{"version":3,"file":"oidc-utils.js","sourceRoot":"","sources":["../src/oidc-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,sDAA+C;AAC/C,wDAAqE;AACrE,iCAAuC;AAKvC,MAAa,UAAU;IACb,MAAM,CAAC,gBAAgB,CAC7B,UAAU,GAAG,IAAI,EACjB,QAAQ,GAAG,EAAE;QAEb,MAAM,cAAc,GAAmB;YACrC,YAAY,EAAE,UAAU;YACxB,UAAU,EAAE,QAAQ;SACrB,CAAA;QAED,OAAO,IAAI,wBAAU,CACnB,qBAAqB,EACrB,CAAC,IAAI,8BAAuB,CAAC,UAAU,CAAC,eAAe,EAAE,CAAC,CAAC,EAC3D,cAAc,CACf,CAAA;IACH,CAAC;IAEO,MAAM,CAAC,eAAe;QAC5B,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAA;QAC3D,IAAI,CAAC,KAAK,EAAE;YACV,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAA;SACF;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAEO,MAAM,CAAC,aAAa;QAC1B,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAA;QAC9D,IAAI,CAAC,UAAU,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;SAC3E;QACD,OAAO,UAAU,CAAA;IACnB,CAAC;IAEO,MAAM,CAAO,OAAO,CAAC,YAAoB;;;YAC/C,MAAM,UAAU,GAAG,UAAU,CAAC,gBAAgB,EAAE,CAAA;YAEhD,MAAM,GAAG,GAAG,MAAM,UAAU;iBACzB,OAAO,CAAgB,YAAY,CAAC;iBACpC,KAAK,CAAC,KAAK,CAAC,EAAE;gBACb,MAAM,IAAI,KAAK,CACb;uBACa,KAAK,CAAC,UAAU;yBACd,KAAK,CAAC,OAAO,EAAE,CAC/B,CAAA;YACH,CAAC,CAAC,CAAA;YAEJ,MAAM,QAAQ,SAAG,GAAG,CAAC,MAAM,0CAAE,KAAK,CAAA;YAClC,IAAI,CAAC,QAAQ,EAAE;gBACb,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAA;aACjE;YACD,OAAO,QAAQ,CAAA;;KAChB;IAED,MAAM,CAAO,UAAU,CAAC,QAAiB;;YACvC,IAAI;gBACF,gDAAgD;gBAChD,IAAI,YAAY,GAAW,UAAU,CAAC,aAAa,EAAE,CAAA;gBACrD,IAAI,QAAQ,EAAE;oBACZ,MAAM,eAAe,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAA;oBACpD,YAAY,GAAG,GAAG,YAAY,aAAa,eAAe,EAAE,CAAA;iBAC7D;gBAED,YAAK,CAAC,mBAAmB,YAAY,EAAE,CAAC,CAAA;gBAExC,MAAM,QAAQ,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;gBACvD,gBAAS,CAAC,QAAQ,CAAC,CAAA;gBACnB,OAAO,QAAQ,CAAA;aAChB;YAAC,OAAO,KAAK,EAAE;gBACd,MAAM,IAAI,KAAK,CAAC,kBAAkB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;aACnD;QACH,CAAC;KAAA;CACF;AAzED,gCAyEC"} \ No newline at end of file diff --git a/node_modules/@actions/core/lib/path-utils.d.ts b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/path-utils.d.ts similarity index 100% rename from node_modules/@actions/core/lib/path-utils.d.ts rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/path-utils.d.ts diff --git a/node_modules/@actions/core/lib/path-utils.js b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/path-utils.js similarity index 100% rename from node_modules/@actions/core/lib/path-utils.js rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/path-utils.js diff --git a/node_modules/@actions/core/lib/path-utils.js.map b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/path-utils.js.map similarity index 100% rename from node_modules/@actions/core/lib/path-utils.js.map rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/path-utils.js.map diff --git a/node_modules/@actions/core/lib/summary.d.ts b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/summary.d.ts similarity index 100% rename from node_modules/@actions/core/lib/summary.d.ts rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/summary.d.ts diff --git a/node_modules/@actions/core/lib/summary.js b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/summary.js similarity index 100% rename from node_modules/@actions/core/lib/summary.js rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/summary.js diff --git a/node_modules/@actions/core/lib/summary.js.map b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/summary.js.map similarity index 100% rename from node_modules/@actions/core/lib/summary.js.map rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/summary.js.map diff --git a/node_modules/@actions/core/lib/utils.d.ts b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/utils.d.ts similarity index 100% rename from node_modules/@actions/core/lib/utils.d.ts rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/utils.d.ts diff --git a/node_modules/@actions/core/lib/utils.js b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/utils.js similarity index 100% rename from node_modules/@actions/core/lib/utils.js rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/utils.js diff --git a/node_modules/@actions/core/lib/utils.js.map b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/utils.js.map similarity index 100% rename from node_modules/@actions/core/lib/utils.js.map rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/lib/utils.js.map diff --git a/node_modules/@actions/core/package.json b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/package.json similarity index 94% rename from node_modules/@actions/core/package.json rename to node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/package.json index 1f3824d..1558268 100644 --- a/node_modules/@actions/core/package.json +++ b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/core/package.json @@ -1,6 +1,6 @@ { "name": "@actions/core", - "version": "1.10.0", + "version": "1.10.1", "description": "Actions core lib", "keywords": [ "github", @@ -30,7 +30,7 @@ "scripts": { "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", "test": "echo \"Error: run tests from root\" && exit 1", - "tsc": "tsc" + "tsc": "tsc -p tsconfig.json" }, "bugs": { "url": "https://github.com/actions/toolkit/issues" @@ -43,4 +43,4 @@ "@types/node": "^12.0.2", "@types/uuid": "^8.3.4" } -} +} \ No newline at end of file diff --git a/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/http-client b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/http-client new file mode 120000 index 0000000..ccfba50 --- /dev/null +++ b/node_modules/.deno/@actions+core@1.10.1/node_modules/@actions/http-client @@ -0,0 +1 @@ +../../../@actions+http-client@2.2.3/node_modules/@actions/http-client \ No newline at end of file diff --git a/node_modules/.deno/@actions+core@1.10.1/node_modules/uuid b/node_modules/.deno/@actions+core@1.10.1/node_modules/uuid new file mode 120000 index 0000000..42f2008 --- /dev/null +++ b/node_modules/.deno/@actions+core@1.10.1/node_modules/uuid @@ -0,0 +1 @@ +../../uuid@8.3.2/node_modules/uuid \ No newline at end of file diff --git a/node_modules/.deno/@actions+exec@1.1.1/.initialized b/node_modules/.deno/@actions+exec@1.1.1/.initialized new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/@actions/exec/LICENSE.md b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/LICENSE.md similarity index 100% rename from node_modules/@actions/exec/LICENSE.md rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/LICENSE.md diff --git a/node_modules/@actions/exec/README.md b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/README.md similarity index 100% rename from node_modules/@actions/exec/README.md rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/README.md diff --git a/node_modules/@actions/exec/lib/exec.d.ts b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/exec.d.ts similarity index 100% rename from node_modules/@actions/exec/lib/exec.d.ts rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/exec.d.ts diff --git a/node_modules/@actions/exec/lib/exec.js b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/exec.js similarity index 100% rename from node_modules/@actions/exec/lib/exec.js rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/exec.js diff --git a/node_modules/@actions/exec/lib/exec.js.map b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/exec.js.map similarity index 100% rename from node_modules/@actions/exec/lib/exec.js.map rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/exec.js.map diff --git a/node_modules/@actions/exec/lib/interfaces.d.ts b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/interfaces.d.ts similarity index 100% rename from node_modules/@actions/exec/lib/interfaces.d.ts rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/interfaces.d.ts diff --git a/node_modules/@actions/exec/lib/interfaces.js b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/interfaces.js similarity index 100% rename from node_modules/@actions/exec/lib/interfaces.js rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/interfaces.js diff --git a/node_modules/@actions/exec/lib/interfaces.js.map b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/interfaces.js.map similarity index 100% rename from node_modules/@actions/exec/lib/interfaces.js.map rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/interfaces.js.map diff --git a/node_modules/@actions/exec/lib/toolrunner.d.ts b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/toolrunner.d.ts similarity index 100% rename from node_modules/@actions/exec/lib/toolrunner.d.ts rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/toolrunner.d.ts diff --git a/node_modules/@actions/exec/lib/toolrunner.js b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/toolrunner.js similarity index 100% rename from node_modules/@actions/exec/lib/toolrunner.js rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/toolrunner.js diff --git a/node_modules/@actions/exec/lib/toolrunner.js.map b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/toolrunner.js.map similarity index 100% rename from node_modules/@actions/exec/lib/toolrunner.js.map rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/lib/toolrunner.js.map diff --git a/node_modules/@actions/exec/package.json b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/package.json similarity index 100% rename from node_modules/@actions/exec/package.json rename to node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/exec/package.json diff --git a/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/io b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/io new file mode 120000 index 0000000..aa80d32 --- /dev/null +++ b/node_modules/.deno/@actions+exec@1.1.1/node_modules/@actions/io @@ -0,0 +1 @@ +../../../@actions+io@1.1.3/node_modules/@actions/io \ No newline at end of file diff --git a/node_modules/.deno/@actions+http-client@2.2.3/.initialized b/node_modules/.deno/@actions+http-client@2.2.3/.initialized new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/@actions/http-client/LICENSE b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/LICENSE similarity index 100% rename from node_modules/@actions/http-client/LICENSE rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/LICENSE diff --git a/node_modules/@actions/http-client/README.md b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/README.md similarity index 100% rename from node_modules/@actions/http-client/README.md rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/README.md diff --git a/node_modules/@actions/http-client/lib/auth.d.ts b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/auth.d.ts similarity index 100% rename from node_modules/@actions/http-client/lib/auth.d.ts rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/auth.d.ts diff --git a/node_modules/@actions/http-client/lib/auth.js b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/auth.js similarity index 100% rename from node_modules/@actions/http-client/lib/auth.js rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/auth.js diff --git a/node_modules/@actions/http-client/lib/auth.js.map b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/auth.js.map similarity index 93% rename from node_modules/@actions/http-client/lib/auth.js.map rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/auth.js.map index 7d3a18a..62cc16b 100644 --- a/node_modules/@actions/http-client/lib/auth.js.map +++ b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/auth.js.map @@ -1 +1 @@ -{"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,MAAa,sBAAsB;IAIjC,YAAY,QAAgB,EAAE,QAAgB;QAC5C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;IAC1B,CAAC;IAED,cAAc,CAAC,OAA4B;QACzC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACpB,MAAM,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC1C;QACD,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CACrD,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,EAAE,CACpC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAA;IACxB,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AA1BD,wDA0BC;AAED,MAAa,uBAAuB;IAGlC,YAAY,KAAa;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IAED,yCAAyC;IACzC,sDAAsD;IACtD,cAAc,CAAC,OAA4B;QACzC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACpB,MAAM,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC1C;QACD,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,IAAI,CAAC,KAAK,EAAE,CAAA;IAC3D,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AAxBD,0DAwBC;AAED,MAAa,oCAAoC;IAI/C,YAAY,KAAa;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IAED,yCAAyC;IACzC,sDAAsD;IACtD,cAAc,CAAC,OAA4B;QACzC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACpB,MAAM,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC1C;QACD,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CACrD,OAAO,IAAI,CAAC,KAAK,EAAE,CACpB,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAA;IACxB,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AA3BD,oFA2BC"} \ No newline at end of file +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,MAAa,sBAAsB;IAIjC,YAAY,QAAgB,EAAE,QAAgB;QAC5C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;IAC1B,CAAC;IAED,cAAc,CAAC,OAA4B;QACzC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACpB,MAAM,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC1C;QACD,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CACrD,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,EAAE,CACpC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAA;IACxB,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AA1BD,wDA0BC;AAED,MAAa,uBAAuB;IAGlC,YAAY,KAAa;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IAED,yCAAyC;IACzC,sDAAsD;IACtD,cAAc,CAAC,OAA4B;QACzC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACpB,MAAM,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC1C;QACD,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,IAAI,CAAC,KAAK,EAAE,CAAA;IAC3D,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AAxBD,0DAwBC;AAED,MAAa,oCAAoC;IAK/C,YAAY,KAAa;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IAED,yCAAyC;IACzC,sDAAsD;IACtD,cAAc,CAAC,OAA4B;QACzC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACpB,MAAM,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC1C;QACD,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CACrD,OAAO,IAAI,CAAC,KAAK,EAAE,CACpB,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAA;IACxB,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AA5BD,oFA4BC"} \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/index.d.ts b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/index.d.ts similarity index 94% rename from node_modules/@actions/http-client/lib/index.d.ts rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/index.d.ts index fe733d1..38db700 100644 --- a/node_modules/@actions/http-client/lib/index.d.ts +++ b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/index.d.ts @@ -1,6 +1,9 @@ /// +/// +/// import * as http from 'http'; import * as ifm from './interfaces'; +import { ProxyAgent } from 'undici'; export declare enum HttpCodes { OK = 200, MultipleChoices = 300, @@ -51,6 +54,7 @@ export declare class HttpClientResponse { constructor(message: http.IncomingMessage); message: http.IncomingMessage; readBody(): Promise; + readBodyBuffer?(): Promise; } export declare function isHttps(requestUrl: string): boolean; export declare class HttpClient { @@ -66,6 +70,7 @@ export declare class HttpClient { private _maxRetries; private _agent; private _proxyAgent; + private _proxyAgentDispatcher; private _keepAlive; private _disposed; constructor(userAgent?: string, handlers?: ifm.RequestHandler[], requestOptions?: ifm.RequestOptions); @@ -114,10 +119,12 @@ export declare class HttpClient { * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl: string): http.Agent; + getAgentDispatcher(serverUrl: string): ProxyAgent | undefined; private _prepareRequest; private _mergeHeaders; private _getExistingOrDefaultHeader; private _getAgent; + private _getProxyAgentDispatcher; private _performExponentialBackoff; private _processResponse; } diff --git a/node_modules/@actions/http-client/lib/index.js b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/index.js similarity index 90% rename from node_modules/@actions/http-client/lib/index.js rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/index.js index a1b7d03..c337ca6 100644 --- a/node_modules/@actions/http-client/lib/index.js +++ b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/index.js @@ -2,7 +2,11 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -15,7 +19,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -34,6 +38,7 @@ const http = __importStar(require("http")); const https = __importStar(require("https")); const pm = __importStar(require("./proxy")); const tunnel = __importStar(require("tunnel")); +const undici_1 = require("undici"); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -63,16 +68,16 @@ var HttpCodes; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); +})(Headers || (exports.Headers = Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com @@ -123,6 +128,19 @@ class HttpClientResponse { })); }); } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { @@ -428,6 +446,15 @@ class HttpClient { const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; @@ -475,7 +502,7 @@ class HttpClient { if (this._keepAlive && useProxy) { agent = this._proxyAgent; } - if (this._keepAlive && !useProxy) { + if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. @@ -507,16 +534,12 @@ class HttpClient { agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { + // if tunneling agent isn't assigned create a new agent + if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options @@ -527,6 +550,30 @@ class HttpClient { } return agent; } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + // if agent is already assigned use that agent. + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` + }))); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); diff --git a/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/index.js.map b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/index.js.map new file mode 100644 index 0000000..2a0d1a8 --- /dev/null +++ b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,uDAAuD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEvD,2CAA4B;AAC5B,6CAA8B;AAG9B,4CAA6B;AAC7B,+CAAgC;AAChC,mCAAiC;AAEjC,IAAY,SA4BX;AA5BD,WAAY,SAAS;IACnB,uCAAQ,CAAA;IACR,iEAAqB,CAAA;IACrB,mEAAsB,CAAA;IACtB,6DAAmB,CAAA;IACnB,mDAAc,CAAA;IACd,yDAAiB,CAAA;IACjB,mDAAc,CAAA;IACd,yDAAiB,CAAA;IACjB,qEAAuB,CAAA;IACvB,qEAAuB,CAAA;IACvB,uDAAgB,CAAA;IAChB,2DAAkB,CAAA;IAClB,iEAAqB,CAAA;IACrB,qDAAe,CAAA;IACf,mDAAc,CAAA;IACd,mEAAsB,CAAA;IACtB,6DAAmB,CAAA;IACnB,yFAAiC,CAAA;IACjC,+DAAoB,CAAA;IACpB,mDAAc,CAAA;IACd,2CAAU,CAAA;IACV,iEAAqB,CAAA;IACrB,yEAAyB,CAAA;IACzB,+DAAoB,CAAA;IACpB,uDAAgB,CAAA;IAChB,uEAAwB,CAAA;IACxB,+DAAoB,CAAA;AACtB,CAAC,EA5BW,SAAS,yBAAT,SAAS,QA4BpB;AAED,IAAY,OAGX;AAHD,WAAY,OAAO;IACjB,4BAAiB,CAAA;IACjB,uCAA4B,CAAA;AAC9B,CAAC,EAHW,OAAO,uBAAP,OAAO,QAGlB;AAED,IAAY,UAEX;AAFD,WAAY,UAAU;IACpB,kDAAoC,CAAA;AACtC,CAAC,EAFW,UAAU,0BAAV,UAAU,QAErB;AAED;;;GAGG;AACH,SAAgB,WAAW,CAAC,SAAiB;IAC3C,MAAM,QAAQ,GAAG,EAAE,CAAC,WAAW,CAAC,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC,CAAA;IACnD,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAA;AACtC,CAAC;AAHD,kCAGC;AAED,MAAM,iBAAiB,GAAa;IAClC,SAAS,CAAC,gBAAgB;IAC1B,SAAS,CAAC,aAAa;IACvB,SAAS,CAAC,QAAQ;IAClB,SAAS,CAAC,iBAAiB;IAC3B,SAAS,CAAC,iBAAiB;CAC5B,CAAA;AACD,MAAM,sBAAsB,GAAa;IACvC,SAAS,CAAC,UAAU;IACpB,SAAS,CAAC,kBAAkB;IAC5B,SAAS,CAAC,cAAc;CACzB,CAAA;AACD,MAAM,kBAAkB,GAAa,CAAC,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;AACzE,MAAM,yBAAyB,GAAG,EAAE,CAAA;AACpC,MAAM,2BAA2B,GAAG,CAAC,CAAA;AAErC,MAAa,eAAgB,SAAQ,KAAK;IACxC,YAAY,OAAe,EAAE,UAAkB;QAC7C,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAA;QAC7B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,eAAe,CAAC,SAAS,CAAC,CAAA;IACxD,CAAC;CAIF;AAVD,0CAUC;AAED,MAAa,kBAAkB;IAC7B,YAAY,OAA6B;QACvC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAGK,QAAQ;;YACZ,OAAO,IAAI,OAAO,CAAS,CAAM,OAAO,EAAC,EAAE;gBACzC,IAAI,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;gBAE5B,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAa,EAAE,EAAE;oBACxC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAA;gBACzC,CAAC,CAAC,CAAA;gBAEF,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;oBAC1B,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAA;gBAC5B,CAAC,CAAC,CAAA;YACJ,CAAC,CAAA,CAAC,CAAA;QACJ,CAAC;KAAA;IAEK,cAAc;;YAClB,OAAO,IAAI,OAAO,CAAS,CAAM,OAAO,EAAC,EAAE;gBACzC,MAAM,MAAM,GAAa,EAAE,CAAA;gBAE3B,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAa,EAAE,EAAE;oBACxC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;gBACpB,CAAC,CAAC,CAAA;gBAEF,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;oBAC1B,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAA;gBAChC,CAAC,CAAC,CAAA;YACJ,CAAC,CAAA,CAAC,CAAA;QACJ,CAAC;KAAA;CACF;AAjCD,gDAiCC;AAED,SAAgB,OAAO,CAAC,UAAkB;IACxC,MAAM,SAAS,GAAQ,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;IAC1C,OAAO,SAAS,CAAC,QAAQ,KAAK,QAAQ,CAAA;AACxC,CAAC;AAHD,0BAGC;AAED,MAAa,UAAU;IAkBrB,YACE,SAAkB,EAClB,QAA+B,EAC/B,cAAmC;QAhB7B,oBAAe,GAAG,KAAK,CAAA;QAEvB,oBAAe,GAAG,IAAI,CAAA;QACtB,4BAAuB,GAAG,KAAK,CAAA;QAC/B,kBAAa,GAAG,EAAE,CAAA;QAClB,kBAAa,GAAG,KAAK,CAAA;QACrB,gBAAW,GAAG,CAAC,CAAA;QAIf,eAAU,GAAG,KAAK,CAAA;QAClB,cAAS,GAAG,KAAK,CAAA;QAOvB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;QAC1B,IAAI,CAAC,QAAQ,GAAG,QAAQ,IAAI,EAAE,CAAA;QAC9B,IAAI,CAAC,cAAc,GAAG,cAAc,CAAA;QACpC,IAAI,cAAc,EAAE;YAClB,IAAI,cAAc,CAAC,cAAc,IAAI,IAAI,EAAE;gBACzC,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC,cAAc,CAAA;aACrD;YAED,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC,aAAa,CAAA;YAElD,IAAI,cAAc,CAAC,cAAc,IAAI,IAAI,EAAE;gBACzC,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC,cAAc,CAAA;aACrD;YAED,IAAI,cAAc,CAAC,sBAAsB,IAAI,IAAI,EAAE;gBACjD,IAAI,CAAC,uBAAuB,GAAG,cAAc,CAAC,sBAAsB,CAAA;aACrE;YAED,IAAI,cAAc,CAAC,YAAY,IAAI,IAAI,EAAE;gBACvC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC,YAAY,EAAE,CAAC,CAAC,CAAA;aAC9D;YAED,IAAI,cAAc,CAAC,SAAS,IAAI,IAAI,EAAE;gBACpC,IAAI,CAAC,UAAU,GAAG,cAAc,CAAC,SAAS,CAAA;aAC3C;YAED,IAAI,cAAc,CAAC,YAAY,IAAI,IAAI,EAAE;gBACvC,IAAI,CAAC,aAAa,GAAG,cAAc,CAAC,YAAY,CAAA;aACjD;YAED,IAAI,cAAc,CAAC,UAAU,IAAI,IAAI,EAAE;gBACrC,IAAI,CAAC,WAAW,GAAG,cAAc,CAAC,UAAU,CAAA;aAC7C;SACF;IACH,CAAC;IAEK,OAAO,CACX,UAAkB,EAClB,iBAA4C;;YAE5C,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,UAAU,EAAE,IAAI,EAAE,iBAAiB,IAAI,EAAE,CAAC,CAAA;QAC3E,CAAC;KAAA;IAEK,GAAG,CACP,UAAkB,EAClB,iBAA4C;;YAE5C,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,iBAAiB,IAAI,EAAE,CAAC,CAAA;QACvE,CAAC;KAAA;IAEK,GAAG,CACP,UAAkB,EAClB,iBAA4C;;YAE5C,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,EAAE,IAAI,EAAE,iBAAiB,IAAI,EAAE,CAAC,CAAA;QAC1E,CAAC;KAAA;IAEK,IAAI,CACR,UAAkB,EAClB,IAAY,EACZ,iBAA4C;;YAE5C,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,iBAAiB,IAAI,EAAE,CAAC,CAAA;QACxE,CAAC;KAAA;IAEK,KAAK,CACT,UAAkB,EAClB,IAAY,EACZ,iBAA4C;;YAE5C,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,iBAAiB,IAAI,EAAE,CAAC,CAAA;QACzE,CAAC;KAAA;IAEK,GAAG,CACP,UAAkB,EAClB,IAAY,EACZ,iBAA4C;;YAE5C,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,iBAAiB,IAAI,EAAE,CAAC,CAAA;QACvE,CAAC;KAAA;IAEK,IAAI,CACR,UAAkB,EAClB,iBAA4C;;YAE5C,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,iBAAiB,IAAI,EAAE,CAAC,CAAA;QACxE,CAAC;KAAA;IAEK,UAAU,CACd,IAAY,EACZ,UAAkB,EAClB,MAA6B,EAC7B,iBAA4C;;YAE5C,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,iBAAiB,CAAC,CAAA;QAClE,CAAC;KAAA;IAED;;;OAGG;IACG,OAAO,CACX,UAAkB,EAClB,oBAA8C,EAAE;;YAEhD,iBAAiB,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,2BAA2B,CAClE,iBAAiB,EACjB,OAAO,CAAC,MAAM,EACd,UAAU,CAAC,eAAe,CAC3B,CAAA;YACD,MAAM,GAAG,GAAuB,MAAM,IAAI,CAAC,GAAG,CAC5C,UAAU,EACV,iBAAiB,CAClB,CAAA;YACD,OAAO,IAAI,CAAC,gBAAgB,CAAI,GAAG,EAAE,IAAI,CAAC,cAAc,CAAC,CAAA;QAC3D,CAAC;KAAA;IAEK,QAAQ,CACZ,UAAkB,EAClB,GAAQ,EACR,oBAA8C,EAAE;;YAEhD,MAAM,IAAI,GAAW,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;YACjD,iBAAiB,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,2BAA2B,CAClE,iBAAiB,EACjB,OAAO,CAAC,MAAM,EACd,UAAU,CAAC,eAAe,CAC3B,CAAA;YACD,iBAAiB,CAAC,OAAO,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC,2BAA2B,CACvE,iBAAiB,EACjB,OAAO,CAAC,WAAW,EACnB,UAAU,CAAC,eAAe,CAC3B,CAAA;YACD,MAAM,GAAG,GAAuB,MAAM,IAAI,CAAC,IAAI,CAC7C,UAAU,EACV,IAAI,EACJ,iBAAiB,CAClB,CAAA;YACD,OAAO,IAAI,CAAC,gBAAgB,CAAI,GAAG,EAAE,IAAI,CAAC,cAAc,CAAC,CAAA;QAC3D,CAAC;KAAA;IAEK,OAAO,CACX,UAAkB,EAClB,GAAQ,EACR,oBAA8C,EAAE;;YAEhD,MAAM,IAAI,GAAW,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;YACjD,iBAAiB,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,2BAA2B,CAClE,iBAAiB,EACjB,OAAO,CAAC,MAAM,EACd,UAAU,CAAC,eAAe,CAC3B,CAAA;YACD,iBAAiB,CAAC,OAAO,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC,2BAA2B,CACvE,iBAAiB,EACjB,OAAO,CAAC,WAAW,EACnB,UAAU,CAAC,eAAe,CAC3B,CAAA;YACD,MAAM,GAAG,GAAuB,MAAM,IAAI,CAAC,GAAG,CAC5C,UAAU,EACV,IAAI,EACJ,iBAAiB,CAClB,CAAA;YACD,OAAO,IAAI,CAAC,gBAAgB,CAAI,GAAG,EAAE,IAAI,CAAC,cAAc,CAAC,CAAA;QAC3D,CAAC;KAAA;IAEK,SAAS,CACb,UAAkB,EAClB,GAAQ,EACR,oBAA8C,EAAE;;YAEhD,MAAM,IAAI,GAAW,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;YACjD,iBAAiB,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,2BAA2B,CAClE,iBAAiB,EACjB,OAAO,CAAC,MAAM,EACd,UAAU,CAAC,eAAe,CAC3B,CAAA;YACD,iBAAiB,CAAC,OAAO,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC,2BAA2B,CACvE,iBAAiB,EACjB,OAAO,CAAC,WAAW,EACnB,UAAU,CAAC,eAAe,CAC3B,CAAA;YACD,MAAM,GAAG,GAAuB,MAAM,IAAI,CAAC,KAAK,CAC9C,UAAU,EACV,IAAI,EACJ,iBAAiB,CAClB,CAAA;YACD,OAAO,IAAI,CAAC,gBAAgB,CAAI,GAAG,EAAE,IAAI,CAAC,cAAc,CAAC,CAAA;QAC3D,CAAC;KAAA;IAED;;;;OAIG;IACG,OAAO,CACX,IAAY,EACZ,UAAkB,EAClB,IAA2C,EAC3C,OAAkC;;YAElC,IAAI,IAAI,CAAC,SAAS,EAAE;gBAClB,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAA;aACrD;YAED,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;YACrC,IAAI,IAAI,GAAoB,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,CAAA;YAE1E,oEAAoE;YACpE,MAAM,QAAQ,GACZ,IAAI,CAAC,aAAa,IAAI,kBAAkB,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACrD,CAAC,CAAC,IAAI,CAAC,WAAW,GAAG,CAAC;gBACtB,CAAC,CAAC,CAAC,CAAA;YACP,IAAI,QAAQ,GAAG,CAAC,CAAA;YAEhB,IAAI,QAAwC,CAAA;YAC5C,GAAG;gBACD,QAAQ,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;gBAE5C,4CAA4C;gBAC5C,IACE,QAAQ;oBACR,QAAQ,CAAC,OAAO;oBAChB,QAAQ,CAAC,OAAO,CAAC,UAAU,KAAK,SAAS,CAAC,YAAY,EACtD;oBACA,IAAI,qBAAqD,CAAA;oBAEzD,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,QAAQ,EAAE;wBACnC,IAAI,OAAO,CAAC,uBAAuB,CAAC,QAAQ,CAAC,EAAE;4BAC7C,qBAAqB,GAAG,OAAO,CAAA;4BAC/B,MAAK;yBACN;qBACF;oBAED,IAAI,qBAAqB,EAAE;wBACzB,OAAO,qBAAqB,CAAC,oBAAoB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;qBACpE;yBAAM;wBACL,+EAA+E;wBAC/E,yCAAyC;wBACzC,OAAO,QAAQ,CAAA;qBAChB;iBACF;gBAED,IAAI,kBAAkB,GAAW,IAAI,CAAC,aAAa,CAAA;gBACnD,OACE,QAAQ,CAAC,OAAO,CAAC,UAAU;oBAC3B,iBAAiB,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC;oBACvD,IAAI,CAAC,eAAe;oBACpB,kBAAkB,GAAG,CAAC,EACtB;oBACA,MAAM,WAAW,GACf,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,CAAA;oBACtC,IAAI,CAAC,WAAW,EAAE;wBAChB,kDAAkD;wBAClD,MAAK;qBACN;oBACD,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAA;oBAC9C,IACE,SAAS,CAAC,QAAQ,KAAK,QAAQ;wBAC/B,SAAS,CAAC,QAAQ,KAAK,iBAAiB,CAAC,QAAQ;wBACjD,CAAC,IAAI,CAAC,uBAAuB,EAC7B;wBACA,MAAM,IAAI,KAAK,CACb,8KAA8K,CAC/K,CAAA;qBACF;oBAED,qEAAqE;oBACrE,mCAAmC;oBACnC,MAAM,QAAQ,CAAC,QAAQ,EAAE,CAAA;oBAEzB,mEAAmE;oBACnE,IAAI,iBAAiB,CAAC,QAAQ,KAAK,SAAS,CAAC,QAAQ,EAAE;wBACrD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;4BAC5B,oCAAoC;4BACpC,IAAI,MAAM,CAAC,WAAW,EAAE,KAAK,eAAe,EAAE;gCAC5C,OAAO,OAAO,CAAC,MAAM,CAAC,CAAA;6BACvB;yBACF;qBACF;oBAED,kDAAkD;oBAClD,IAAI,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,iBAAiB,EAAE,OAAO,CAAC,CAAA;oBAC7D,QAAQ,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;oBAC5C,kBAAkB,EAAE,CAAA;iBACrB;gBAED,IACE,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAU;oBAC5B,CAAC,sBAAsB,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,EAC7D;oBACA,8DAA8D;oBAC9D,OAAO,QAAQ,CAAA;iBAChB;gBAED,QAAQ,IAAI,CAAC,CAAA;gBAEb,IAAI,QAAQ,GAAG,QAAQ,EAAE;oBACvB,MAAM,QAAQ,CAAC,QAAQ,EAAE,CAAA;oBACzB,MAAM,IAAI,CAAC,0BAA0B,CAAC,QAAQ,CAAC,CAAA;iBAChD;aACF,QAAQ,QAAQ,GAAG,QAAQ,EAAC;YAE7B,OAAO,QAAQ,CAAA;QACjB,CAAC;KAAA;IAED;;OAEG;IACH,OAAO;QACL,IAAI,IAAI,CAAC,MAAM,EAAE;YACf,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAA;SACtB;QAED,IAAI,CAAC,SAAS,GAAG,IAAI,CAAA;IACvB,CAAC;IAED;;;;OAIG;IACG,UAAU,CACd,IAAqB,EACrB,IAA2C;;YAE3C,OAAO,IAAI,OAAO,CAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBACzD,SAAS,iBAAiB,CAAC,GAAW,EAAE,GAAwB;oBAC9D,IAAI,GAAG,EAAE;wBACP,MAAM,CAAC,GAAG,CAAC,CAAA;qBACZ;yBAAM,IAAI,CAAC,GAAG,EAAE;wBACf,qDAAqD;wBACrD,MAAM,CAAC,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC,CAAA;qBACnC;yBAAM;wBACL,OAAO,CAAC,GAAG,CAAC,CAAA;qBACb;gBACH,CAAC;gBAED,IAAI,CAAC,sBAAsB,CAAC,IAAI,EAAE,IAAI,EAAE,iBAAiB,CAAC,CAAA;YAC5D,CAAC,CAAC,CAAA;QACJ,CAAC;KAAA;IAED;;;;;OAKG;IACH,sBAAsB,CACpB,IAAqB,EACrB,IAA2C,EAC3C,QAAyD;QAEzD,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;YAC5B,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;gBACzB,IAAI,CAAC,OAAO,CAAC,OAAO,GAAG,EAAE,CAAA;aAC1B;YACD,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,gBAAgB,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;SACzE;QAED,IAAI,cAAc,GAAG,KAAK,CAAA;QAC1B,SAAS,YAAY,CAAC,GAAW,EAAE,GAAwB;YACzD,IAAI,CAAC,cAAc,EAAE;gBACnB,cAAc,GAAG,IAAI,CAAA;gBACrB,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;aACnB;QACH,CAAC;QAED,MAAM,GAAG,GAAuB,IAAI,CAAC,UAAU,CAAC,OAAO,CACrD,IAAI,CAAC,OAAO,EACZ,CAAC,GAAyB,EAAE,EAAE;YAC5B,MAAM,GAAG,GAAuB,IAAI,kBAAkB,CAAC,GAAG,CAAC,CAAA;YAC3D,YAAY,CAAC,SAAS,EAAE,GAAG,CAAC,CAAA;QAC9B,CAAC,CACF,CAAA;QAED,IAAI,MAAkB,CAAA;QACtB,GAAG,CAAC,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE;YACtB,MAAM,GAAG,IAAI,CAAA;QACf,CAAC,CAAC,CAAA;QAEF,wEAAwE;QACxE,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,cAAc,IAAI,CAAC,GAAG,KAAK,EAAE,GAAG,EAAE;YACpD,IAAI,MAAM,EAAE;gBACV,MAAM,CAAC,GAAG,EAAE,CAAA;aACb;YACD,YAAY,CAAC,IAAI,KAAK,CAAC,oBAAoB,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;QAClE,CAAC,CAAC,CAAA;QAEF,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,GAAG;YAC3B,8BAA8B;YAC9B,0BAA0B;YAC1B,YAAY,CAAC,GAAG,CAAC,CAAA;QACnB,CAAC,CAAC,CAAA;QAEF,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;YACpC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;SACxB;QAED,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;YACpC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE;gBACf,GAAG,CAAC,GAAG,EAAE,CAAA;YACX,CAAC,CAAC,CAAA;YAEF,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;SACf;aAAM;YACL,GAAG,CAAC,GAAG,EAAE,CAAA;SACV;IACH,CAAC;IAED;;;;OAIG;IACH,QAAQ,CAAC,SAAiB;QACxB,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAA;QACpC,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAA;IAClC,CAAC;IAED,kBAAkB,CAAC,SAAiB;QAClC,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAA;QACpC,MAAM,QAAQ,GAAG,EAAE,CAAC,WAAW,CAAC,SAAS,CAAC,CAAA;QAC1C,MAAM,QAAQ,GAAG,QAAQ,IAAI,QAAQ,CAAC,QAAQ,CAAA;QAC9C,IAAI,CAAC,QAAQ,EAAE;YACb,OAAM;SACP;QAED,OAAO,IAAI,CAAC,wBAAwB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAA;IAC3D,CAAC;IAEO,eAAe,CACrB,MAAc,EACd,UAAe,EACf,OAAkC;QAElC,MAAM,IAAI,GAAqC,EAAE,CAAA;QAEjD,IAAI,CAAC,SAAS,GAAG,UAAU,CAAA;QAC3B,MAAM,QAAQ,GAAY,IAAI,CAAC,SAAS,CAAC,QAAQ,KAAK,QAAQ,CAAA;QAC9D,IAAI,CAAC,UAAU,GAAG,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAA;QACzC,MAAM,WAAW,GAAW,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAA;QAE/C,IAAI,CAAC,OAAO,GAAwB,EAAE,CAAA;QACtC,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAA;QAC3C,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI;YACrC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;YAC/B,CAAC,CAAC,WAAW,CAAA;QACf,IAAI,CAAC,OAAO,CAAC,IAAI;YACf,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,IAAI,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,IAAI,EAAE,CAAC,CAAA;QACjE,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,MAAM,CAAA;QAC5B,IAAI,CAAC,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAA;QAClD,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,EAAE;YAC1B,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,SAAS,CAAA;SACpD;QAED,IAAI,CAAC,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;QAEnD,+CAA+C;QAC/C,IAAI,IAAI,CAAC,QAAQ,EAAE;YACjB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,QAAQ,EAAE;gBACnC,OAAO,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;aACrC;SACF;QAED,OAAO,IAAI,CAAA;IACb,CAAC;IAEO,aAAa,CACnB,OAAkC;QAElC,IAAI,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;YACtD,OAAO,MAAM,CAAC,MAAM,CAClB,EAAE,EACF,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,EAC1C,aAAa,CAAC,OAAO,IAAI,EAAE,CAAC,CAC7B,CAAA;SACF;QAED,OAAO,aAAa,CAAC,OAAO,IAAI,EAAE,CAAC,CAAA;IACrC,CAAC;IAEO,2BAA2B,CACjC,iBAA2C,EAC3C,MAAc,EACd,QAAgB;QAEhB,IAAI,YAAgC,CAAA;QACpC,IAAI,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;YACtD,YAAY,GAAG,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAA;SAClE;QACD,OAAO,iBAAiB,CAAC,MAAM,CAAC,IAAI,YAAY,IAAI,QAAQ,CAAA;IAC9D,CAAC;IAEO,SAAS,CAAC,SAAc;QAC9B,IAAI,KAAK,CAAA;QACT,MAAM,QAAQ,GAAG,EAAE,CAAC,WAAW,CAAC,SAAS,CAAC,CAAA;QAC1C,MAAM,QAAQ,GAAG,QAAQ,IAAI,QAAQ,CAAC,QAAQ,CAAA;QAE9C,IAAI,IAAI,CAAC,UAAU,IAAI,QAAQ,EAAE;YAC/B,KAAK,GAAG,IAAI,CAAC,WAAW,CAAA;SACzB;QAED,IAAI,CAAC,QAAQ,EAAE;YACb,KAAK,GAAG,IAAI,CAAC,MAAM,CAAA;SACpB;QAED,+CAA+C;QAC/C,IAAI,KAAK,EAAE;YACT,OAAO,KAAK,CAAA;SACb;QAED,MAAM,QAAQ,GAAG,SAAS,CAAC,QAAQ,KAAK,QAAQ,CAAA;QAChD,IAAI,UAAU,GAAG,GAAG,CAAA;QACpB,IAAI,IAAI,CAAC,cAAc,EAAE;YACvB,UAAU,GAAG,IAAI,CAAC,cAAc,CAAC,UAAU,IAAI,IAAI,CAAC,WAAW,CAAC,UAAU,CAAA;SAC3E;QAED,sGAAsG;QACtG,IAAI,QAAQ,IAAI,QAAQ,CAAC,QAAQ,EAAE;YACjC,MAAM,YAAY,GAAG;gBACnB,UAAU;gBACV,SAAS,EAAE,IAAI,CAAC,UAAU;gBAC1B,KAAK,kCACA,CAAC,CAAC,QAAQ,CAAC,QAAQ,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI;oBAC9C,SAAS,EAAE,GAAG,QAAQ,CAAC,QAAQ,IAAI,QAAQ,CAAC,QAAQ,EAAE;iBACvD,CAAC,KACF,IAAI,EAAE,QAAQ,CAAC,QAAQ,EACvB,IAAI,EAAE,QAAQ,CAAC,IAAI,GACpB;aACF,CAAA;YAED,IAAI,WAAqB,CAAA;YACzB,MAAM,SAAS,GAAG,QAAQ,CAAC,QAAQ,KAAK,QAAQ,CAAA;YAChD,IAAI,QAAQ,EAAE;gBACZ,WAAW,GAAG,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAA;aACvE;iBAAM;gBACL,WAAW,GAAG,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC,YAAY,CAAA;aACrE;YAED,KAAK,GAAG,WAAW,CAAC,YAAY,CAAC,CAAA;YACjC,IAAI,CAAC,WAAW,GAAG,KAAK,CAAA;SACzB;QAED,uDAAuD;QACvD,IAAI,CAAC,KAAK,EAAE;YACV,MAAM,OAAO,GAAG,EAAC,SAAS,EAAE,IAAI,CAAC,UAAU,EAAE,UAAU,EAAC,CAAA;YACxD,KAAK,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;YACrE,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;SACpB;QAED,IAAI,QAAQ,IAAI,IAAI,CAAC,eAAe,EAAE;YACpC,wGAAwG;YACxG,kFAAkF;YAClF,mDAAmD;YACnD,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,IAAI,EAAE,EAAE;gBACjD,kBAAkB,EAAE,KAAK;aAC1B,CAAC,CAAA;SACH;QAED,OAAO,KAAK,CAAA;IACd,CAAC;IAEO,wBAAwB,CAAC,SAAc,EAAE,QAAa;QAC5D,IAAI,UAAU,CAAA;QAEd,IAAI,IAAI,CAAC,UAAU,EAAE;YACnB,UAAU,GAAG,IAAI,CAAC,qBAAqB,CAAA;SACxC;QAED,+CAA+C;QAC/C,IAAI,UAAU,EAAE;YACd,OAAO,UAAU,CAAA;SAClB;QAED,MAAM,QAAQ,GAAG,SAAS,CAAC,QAAQ,KAAK,QAAQ,CAAA;QAChD,UAAU,GAAG,IAAI,mBAAU,iBACzB,GAAG,EAAE,QAAQ,CAAC,IAAI,EAClB,UAAU,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IACjC,CAAC,CAAC,QAAQ,CAAC,QAAQ,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI;YAC9C,KAAK,EAAE,SAAS,MAAM,CAAC,IAAI,CACzB,GAAG,QAAQ,CAAC,QAAQ,IAAI,QAAQ,CAAC,QAAQ,EAAE,CAC5C,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;SACvB,CAAC,EACF,CAAA;QACF,IAAI,CAAC,qBAAqB,GAAG,UAAU,CAAA;QAEvC,IAAI,QAAQ,IAAI,IAAI,CAAC,eAAe,EAAE;YACpC,wGAAwG;YACxG,kFAAkF;YAClF,mDAAmD;YACnD,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,UAAU,IAAI,EAAE,EAAE;gBACtE,kBAAkB,EAAE,KAAK;aAC1B,CAAC,CAAA;SACH;QAED,OAAO,UAAU,CAAA;IACnB,CAAC;IAEa,0BAA0B,CAAC,WAAmB;;YAC1D,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,yBAAyB,EAAE,WAAW,CAAC,CAAA;YAC9D,MAAM,EAAE,GAAW,2BAA2B,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,WAAW,CAAC,CAAA;YACzE,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC,CAAA;QAChE,CAAC;KAAA;IAEa,gBAAgB,CAC5B,GAAuB,EACvB,OAA4B;;YAE5B,OAAO,IAAI,OAAO,CAAuB,CAAO,OAAO,EAAE,MAAM,EAAE,EAAE;gBACjE,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,IAAI,CAAC,CAAA;gBAE9C,MAAM,QAAQ,GAAyB;oBACrC,UAAU;oBACV,MAAM,EAAE,IAAI;oBACZ,OAAO,EAAE,EAAE;iBACZ,CAAA;gBAED,uCAAuC;gBACvC,IAAI,UAAU,KAAK,SAAS,CAAC,QAAQ,EAAE;oBACrC,OAAO,CAAC,QAAQ,CAAC,CAAA;iBAClB;gBAED,+BAA+B;gBAE/B,SAAS,oBAAoB,CAAC,GAAQ,EAAE,KAAU;oBAChD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;wBAC7B,MAAM,CAAC,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAA;wBACzB,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,EAAE;4BACvB,OAAO,CAAC,CAAA;yBACT;qBACF;oBAED,OAAO,KAAK,CAAA;gBACd,CAAC;gBAED,IAAI,GAAQ,CAAA;gBACZ,IAAI,QAA4B,CAAA;gBAEhC,IAAI;oBACF,QAAQ,GAAG,MAAM,GAAG,CAAC,QAAQ,EAAE,CAAA;oBAC/B,IAAI,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;wBACnC,IAAI,OAAO,IAAI,OAAO,CAAC,gBAAgB,EAAE;4BACvC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,oBAAoB,CAAC,CAAA;yBACjD;6BAAM;4BACL,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;yBAC3B;wBAED,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAA;qBACtB;oBAED,QAAQ,CAAC,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC,OAAO,CAAA;iBACvC;gBAAC,OAAO,GAAG,EAAE;oBACZ,iEAAiE;iBAClE;gBAED,yDAAyD;gBACzD,IAAI,UAAU,GAAG,GAAG,EAAE;oBACpB,IAAI,GAAW,CAAA;oBAEf,0DAA0D;oBAC1D,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,EAAE;wBACtB,GAAG,GAAG,GAAG,CAAC,OAAO,CAAA;qBAClB;yBAAM,IAAI,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;wBAC1C,yEAAyE;wBACzE,GAAG,GAAG,QAAQ,CAAA;qBACf;yBAAM;wBACL,GAAG,GAAG,oBAAoB,UAAU,GAAG,CAAA;qBACxC;oBAED,MAAM,GAAG,GAAG,IAAI,eAAe,CAAC,GAAG,EAAE,UAAU,CAAC,CAAA;oBAChD,GAAG,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAA;oBAE5B,MAAM,CAAC,GAAG,CAAC,CAAA;iBACZ;qBAAM;oBACL,OAAO,CAAC,QAAQ,CAAC,CAAA;iBAClB;YACH,CAAC,CAAA,CAAC,CAAA;QACJ,CAAC;KAAA;CACF;AA7rBD,gCA6rBC;AAED,MAAM,aAAa,GAAG,CAAC,GAA2B,EAAO,EAAE,CACzD,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAM,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/interfaces.d.ts b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/interfaces.d.ts similarity index 97% rename from node_modules/@actions/http-client/lib/interfaces.d.ts rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/interfaces.d.ts index 54fd4a8..775ced9 100644 --- a/node_modules/@actions/http-client/lib/interfaces.d.ts +++ b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/interfaces.d.ts @@ -1,4 +1,6 @@ /// +/// +/// import * as http from 'http'; import * as https from 'https'; import { HttpClientResponse } from './index'; diff --git a/node_modules/@actions/http-client/lib/interfaces.js b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/interfaces.js similarity index 100% rename from node_modules/@actions/http-client/lib/interfaces.js rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/interfaces.js diff --git a/node_modules/@actions/http-client/lib/interfaces.js.map b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/interfaces.js.map similarity index 100% rename from node_modules/@actions/http-client/lib/interfaces.js.map rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/interfaces.js.map diff --git a/node_modules/@actions/http-client/lib/proxy.d.ts b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/proxy.d.ts similarity index 100% rename from node_modules/@actions/http-client/lib/proxy.d.ts rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/proxy.d.ts diff --git a/node_modules/@actions/http-client/lib/proxy.js b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/proxy.js similarity index 57% rename from node_modules/@actions/http-client/lib/proxy.js rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/proxy.js index 528ffe4..fac1cfc 100644 --- a/node_modules/@actions/http-client/lib/proxy.js +++ b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/proxy.js @@ -15,7 +15,13 @@ function getProxyUrl(reqUrl) { } })(); if (proxyVar) { - return new URL(proxyVar); + try { + return new DecodedURL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new DecodedURL(`http://${proxyVar}`); + } } else { return undefined; @@ -26,6 +32,10 @@ function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; @@ -51,11 +61,35 @@ function checkBypass(reqUrl) { .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } exports.checkBypass = checkBypass; +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); +} +class DecodedURL extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } +} //# sourceMappingURL=proxy.js.map \ No newline at end of file diff --git a/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/proxy.js.map b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/proxy.js.map new file mode 100644 index 0000000..0d7f8cc --- /dev/null +++ b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/lib/proxy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":";;;AAAA,SAAgB,WAAW,CAAC,MAAW;IACrC,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAA;IAE7C,IAAI,WAAW,CAAC,MAAM,CAAC,EAAE;QACvB,OAAO,SAAS,CAAA;KACjB;IAED,MAAM,QAAQ,GAAG,CAAC,GAAG,EAAE;QACrB,IAAI,QAAQ,EAAE;YACZ,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAA;SAChE;aAAM;YACL,OAAO,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAA;SAC9D;IACH,CAAC,CAAC,EAAE,CAAA;IAEJ,IAAI,QAAQ,EAAE;QACZ,IAAI;YACF,OAAO,IAAI,UAAU,CAAC,QAAQ,CAAC,CAAA;SAChC;QAAC,WAAM;YACN,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,UAAU,CAAC;gBACrE,OAAO,IAAI,UAAU,CAAC,UAAU,QAAQ,EAAE,CAAC,CAAA;SAC9C;KACF;SAAM;QACL,OAAO,SAAS,CAAA;KACjB;AACH,CAAC;AAzBD,kCAyBC;AAED,SAAgB,WAAW,CAAC,MAAW;IACrC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE;QACpB,OAAO,KAAK,CAAA;KACb;IAED,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAA;IAC/B,IAAI,iBAAiB,CAAC,OAAO,CAAC,EAAE;QAC9B,OAAO,IAAI,CAAA;KACZ;IAED,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,CAAA;IACxE,IAAI,CAAC,OAAO,EAAE;QACZ,OAAO,KAAK,CAAA;KACb;IAED,6BAA6B;IAC7B,IAAI,OAA2B,CAAA;IAC/B,IAAI,MAAM,CAAC,IAAI,EAAE;QACf,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;KAC9B;SAAM,IAAI,MAAM,CAAC,QAAQ,KAAK,OAAO,EAAE;QACtC,OAAO,GAAG,EAAE,CAAA;KACb;SAAM,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,EAAE;QACvC,OAAO,GAAG,GAAG,CAAA;KACd;IAED,qDAAqD;IACrD,MAAM,aAAa,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAA;IACrD,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,aAAa,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,IAAI,OAAO,EAAE,CAAC,CAAA;KACrD;IAED,uCAAuC;IACvC,KAAK,MAAM,gBAAgB,IAAI,OAAO;SACnC,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;SAChC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE;QACjB,IACE,gBAAgB,KAAK,GAAG;YACxB,aAAa,CAAC,IAAI,CAChB,CAAC,CAAC,EAAE,CACF,CAAC,KAAK,gBAAgB;gBACtB,CAAC,CAAC,QAAQ,CAAC,IAAI,gBAAgB,EAAE,CAAC;gBAClC,CAAC,gBAAgB,CAAC,UAAU,CAAC,GAAG,CAAC;oBAC/B,CAAC,CAAC,QAAQ,CAAC,GAAG,gBAAgB,EAAE,CAAC,CAAC,CACvC,EACD;YACA,OAAO,IAAI,CAAA;SACZ;KACF;IAED,OAAO,KAAK,CAAA;AACd,CAAC;AAnDD,kCAmDC;AAED,SAAS,iBAAiB,CAAC,IAAY;IACrC,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,EAAE,CAAA;IACpC,OAAO,CACL,SAAS,KAAK,WAAW;QACzB,SAAS,CAAC,UAAU,CAAC,MAAM,CAAC;QAC5B,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC;QAC7B,SAAS,CAAC,UAAU,CAAC,mBAAmB,CAAC,CAC1C,CAAA;AACH,CAAC;AAED,MAAM,UAAW,SAAQ,GAAG;IAI1B,YAAY,GAAiB,EAAE,IAAmB;QAChD,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;QAChB,IAAI,CAAC,gBAAgB,GAAG,kBAAkB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC1D,IAAI,CAAC,gBAAgB,GAAG,kBAAkB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;IAC5D,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,gBAAgB,CAAA;IAC9B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,gBAAgB,CAAA;IAC9B,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@actions/http-client/package.json b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/package.json similarity index 87% rename from node_modules/@actions/http-client/package.json rename to node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/package.json index c1de221..3960a83 100644 --- a/node_modules/@actions/http-client/package.json +++ b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/@actions/http-client/package.json @@ -1,6 +1,6 @@ { "name": "@actions/http-client", - "version": "2.0.1", + "version": "2.2.3", "description": "Actions Http Client", "keywords": [ "github", @@ -39,10 +39,13 @@ "url": "https://github.com/actions/toolkit/issues" }, "devDependencies": { + "@types/node": "20.7.1", "@types/tunnel": "0.0.3", - "proxy": "^1.0.1" + "proxy": "^2.1.1", + "@types/proxy": "^1.0.1" }, "dependencies": { - "tunnel": "^0.0.6" + "tunnel": "^0.0.6", + "undici": "^5.25.4" } -} +} \ No newline at end of file diff --git a/node_modules/.deno/@actions+http-client@2.2.3/node_modules/tunnel b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/tunnel new file mode 120000 index 0000000..bddefb3 --- /dev/null +++ b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/tunnel @@ -0,0 +1 @@ +../../tunnel@0.0.6/node_modules/tunnel \ No newline at end of file diff --git a/node_modules/.deno/@actions+http-client@2.2.3/node_modules/undici b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/undici new file mode 120000 index 0000000..eb58f2e --- /dev/null +++ b/node_modules/.deno/@actions+http-client@2.2.3/node_modules/undici @@ -0,0 +1 @@ +../../undici@5.28.4/node_modules/undici \ No newline at end of file diff --git a/node_modules/.deno/@actions+io@1.1.3/.initialized b/node_modules/.deno/@actions+io@1.1.3/.initialized new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/@actions/io/LICENSE.md b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/LICENSE.md similarity index 100% rename from node_modules/@actions/io/LICENSE.md rename to node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/LICENSE.md diff --git a/node_modules/@actions/io/README.md b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/README.md similarity index 100% rename from node_modules/@actions/io/README.md rename to node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/README.md diff --git a/node_modules/@actions/io/lib/io-util.d.ts b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.d.ts similarity index 71% rename from node_modules/@actions/io/lib/io-util.d.ts rename to node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.d.ts index 0cddd31..0241e72 100644 --- a/node_modules/@actions/io/lib/io-util.d.ts +++ b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.d.ts @@ -1,7 +1,9 @@ /// import * as fs from 'fs'; -export declare const chmod: typeof fs.promises.chmod, copyFile: typeof fs.promises.copyFile, lstat: typeof fs.promises.lstat, mkdir: typeof fs.promises.mkdir, readdir: typeof fs.promises.readdir, readlink: typeof fs.promises.readlink, rename: typeof fs.promises.rename, rmdir: typeof fs.promises.rmdir, stat: typeof fs.promises.stat, symlink: typeof fs.promises.symlink, unlink: typeof fs.promises.unlink; +export declare const chmod: typeof fs.promises.chmod, copyFile: typeof fs.promises.copyFile, lstat: typeof fs.promises.lstat, mkdir: typeof fs.promises.mkdir, open: typeof fs.promises.open, readdir: typeof fs.promises.readdir, readlink: typeof fs.promises.readlink, rename: typeof fs.promises.rename, rm: typeof fs.promises.rm, rmdir: typeof fs.promises.rmdir, stat: typeof fs.promises.stat, symlink: typeof fs.promises.symlink, unlink: typeof fs.promises.unlink; export declare const IS_WINDOWS: boolean; +export declare const UV_FS_O_EXLOCK = 268435456; +export declare const READONLY: number; export declare function exists(fsPath: string): Promise; export declare function isDirectory(fsPath: string, useStat?: boolean): Promise; /** diff --git a/node_modules/@actions/io/lib/io-util.js b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.js similarity index 87% rename from node_modules/@actions/io/lib/io-util.js rename to node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.js index aae903c..f12e5b0 100644 --- a/node_modules/@actions/io/lib/io-util.js +++ b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.js @@ -29,11 +29,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; var _a; Object.defineProperty(exports, "__esModule", { value: true }); -exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rename = exports.readlink = exports.readdir = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; +exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; const fs = __importStar(require("fs")); const path = __importStar(require("path")); -_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; +_a = fs.promises +// export const {open} = 'fs' +, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; +// export const {open} = 'fs' exports.IS_WINDOWS = process.platform === 'win32'; +// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 +exports.UV_FS_O_EXLOCK = 0x10000000; +exports.READONLY = fs.constants.O_RDONLY; function exists(fsPath) { return __awaiter(this, void 0, void 0, function* () { try { diff --git a/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.js.map b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.js.map new file mode 100644 index 0000000..9a587b3 --- /dev/null +++ b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"io-util.js","sourceRoot":"","sources":["../src/io-util.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAwB;AACxB,2CAA4B;AAEf,KAcT,EAAE,CAAC,QAAQ;AACf,6BAA6B;EAd3B,aAAK,aACL,gBAAQ,gBACR,aAAK,aACL,aAAK,aACL,YAAI,YACJ,eAAO,eACP,gBAAQ,gBACR,cAAM,cACN,UAAE,UACF,aAAK,aACL,YAAI,YACJ,eAAO,eACP,cAAM,aACO;AACf,6BAA6B;AAChB,QAAA,UAAU,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAA;AACtD,iHAAiH;AACpG,QAAA,cAAc,GAAG,UAAU,CAAA;AAC3B,QAAA,QAAQ,GAAG,EAAE,CAAC,SAAS,CAAC,QAAQ,CAAA;AAE7C,SAAsB,MAAM,CAAC,MAAc;;QACzC,IAAI;YACF,MAAM,YAAI,CAAC,MAAM,CAAC,CAAA;SACnB;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACzB,OAAO,KAAK,CAAA;aACb;YAED,MAAM,GAAG,CAAA;SACV;QAED,OAAO,IAAI,CAAA;IACb,CAAC;CAAA;AAZD,wBAYC;AAED,SAAsB,WAAW,CAC/B,MAAc,EACd,OAAO,GAAG,KAAK;;QAEf,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,YAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,aAAK,CAAC,MAAM,CAAC,CAAA;QAChE,OAAO,KAAK,CAAC,WAAW,EAAE,CAAA;IAC5B,CAAC;CAAA;AAND,kCAMC;AAED;;;GAGG;AACH,SAAgB,QAAQ,CAAC,CAAS;IAChC,CAAC,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAA;IAC1B,IAAI,CAAC,CAAC,EAAE;QACN,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;KAC5D;IAED,IAAI,kBAAU,EAAE;QACd,OAAO,CACL,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,8BAA8B;SACxE,CAAA,CAAC,sBAAsB;KACzB;IAED,OAAO,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;AAC1B,CAAC;AAbD,4BAaC;AAED;;;;;GAKG;AACH,SAAsB,oBAAoB,CACxC,QAAgB,EAChB,UAAoB;;QAEpB,IAAI,KAAK,GAAyB,SAAS,CAAA;QAC3C,IAAI;YACF,mBAAmB;YACnB,KAAK,GAAG,MAAM,YAAI,CAAC,QAAQ,CAAC,CAAA;SAC7B;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACzB,sCAAsC;gBACtC,OAAO,CAAC,GAAG,CACT,uEAAuE,QAAQ,MAAM,GAAG,EAAE,CAC3F,CAAA;aACF;SACF;QACD,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE;YAC3B,IAAI,kBAAU,EAAE;gBACd,uCAAuC;gBACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAA;gBACrD,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,WAAW,EAAE,KAAK,QAAQ,CAAC,EAAE;oBACpE,OAAO,QAAQ,CAAA;iBAChB;aACF;iBAAM;gBACL,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;oBAC3B,OAAO,QAAQ,CAAA;iBAChB;aACF;SACF;QAED,qBAAqB;QACrB,MAAM,gBAAgB,GAAG,QAAQ,CAAA;QACjC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE;YAClC,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CAAA;YAEvC,KAAK,GAAG,SAAS,CAAA;YACjB,IAAI;gBACF,KAAK,GAAG,MAAM,YAAI,CAAC,QAAQ,CAAC,CAAA;aAC7B;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;oBACzB,sCAAsC;oBACtC,OAAO,CAAC,GAAG,CACT,uEAAuE,QAAQ,MAAM,GAAG,EAAE,CAC3F,CAAA;iBACF;aACF;YAED,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE;gBAC3B,IAAI,kBAAU,EAAE;oBACd,yEAAyE;oBACzE,IAAI;wBACF,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;wBACxC,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAA;wBACvD,KAAK,MAAM,UAAU,IAAI,MAAM,eAAO,CAAC,SAAS,CAAC,EAAE;4BACjD,IAAI,SAAS,KAAK,UAAU,CAAC,WAAW,EAAE,EAAE;gCAC1C,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAAA;gCAC3C,MAAK;6BACN;yBACF;qBACF;oBAAC,OAAO,GAAG,EAAE;wBACZ,sCAAsC;wBACtC,OAAO,CAAC,GAAG,CACT,yEAAyE,QAAQ,MAAM,GAAG,EAAE,CAC7F,CAAA;qBACF;oBAED,OAAO,QAAQ,CAAA;iBAChB;qBAAM;oBACL,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;wBAC3B,OAAO,QAAQ,CAAA;qBAChB;iBACF;aACF;SACF;QAED,OAAO,EAAE,CAAA;IACX,CAAC;CAAA;AA5ED,oDA4EC;AAED,SAAS,mBAAmB,CAAC,CAAS;IACpC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAA;IACX,IAAI,kBAAU,EAAE;QACd,6BAA6B;QAC7B,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QAE1B,2BAA2B;QAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;KACjC;IAED,2BAA2B;IAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjC,CAAC;AAED,qCAAqC;AACrC,6BAA6B;AAC7B,6BAA6B;AAC7B,SAAS,gBAAgB,CAAC,KAAe;IACvC,OAAO,CACL,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC;QACpB,CAAC,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC;QACxD,CAAC,CAAC,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAC1D,CAAA;AACH,CAAC;AAED,qCAAqC;AACrC,SAAgB,UAAU;;IACxB,aAAO,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,mCAAI,SAAS,CAAA;AAC5C,CAAC;AAFD,gCAEC"} \ No newline at end of file diff --git a/node_modules/@actions/io/lib/io.d.ts b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io.d.ts similarity index 100% rename from node_modules/@actions/io/lib/io.d.ts rename to node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io.d.ts diff --git a/node_modules/@actions/io/lib/io.js b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io.js similarity index 83% rename from node_modules/@actions/io/lib/io.js rename to node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io.js index 4dc1fc3..15f7d7c 100644 --- a/node_modules/@actions/io/lib/io.js +++ b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io.js @@ -30,12 +30,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge Object.defineProperty(exports, "__esModule", { value: true }); exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; const assert_1 = require("assert"); -const childProcess = __importStar(require("child_process")); const path = __importStar(require("path")); -const util_1 = require("util"); const ioUtil = __importStar(require("./io-util")); -const exec = util_1.promisify(childProcess.exec); -const execFile = util_1.promisify(childProcess.execFile); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js @@ -116,61 +112,23 @@ exports.mv = mv; function rmRF(inputPath) { return __awaiter(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { - // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another - // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del. // Check for invalid characters // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file if (/[*"<>|]/.test(inputPath)) { throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); } - try { - const cmdPath = ioUtil.getCmdPath(); - if (yield ioUtil.isDirectory(inputPath, true)) { - yield exec(`${cmdPath} /s /c "rd /s /q "%inputPath%""`, { - env: { inputPath } - }); - } - else { - yield exec(`${cmdPath} /s /c "del /f /a "%inputPath%""`, { - env: { inputPath } - }); - } - } - catch (err) { - // if you try to delete a file that doesn't exist, desired result is achieved - // other errors are valid - if (err.code !== 'ENOENT') - throw err; - } - // Shelling out fails to remove a symlink folder with missing source, this unlink catches that - try { - yield ioUtil.unlink(inputPath); - } - catch (err) { - // if you try to delete a file that doesn't exist, desired result is achieved - // other errors are valid - if (err.code !== 'ENOENT') - throw err; - } } - else { - let isDir = false; - try { - isDir = yield ioUtil.isDirectory(inputPath); - } - catch (err) { - // if you try to delete a file that doesn't exist, desired result is achieved - // other errors are valid - if (err.code !== 'ENOENT') - throw err; - return; - } - if (isDir) { - yield execFile(`rm`, [`-rf`, `${inputPath}`]); - } - else { - yield ioUtil.unlink(inputPath); - } + try { + // note if path does not exist, error is silent + yield ioUtil.rm(inputPath, { + force: true, + maxRetries: 3, + recursive: true, + retryDelay: 300 + }); + } + catch (err) { + throw new Error(`File was unable to be removed ${err}`); } }); } diff --git a/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io.js.map b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io.js.map new file mode 100644 index 0000000..4021d28 --- /dev/null +++ b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/lib/io.js.map @@ -0,0 +1 @@ +{"version":3,"file":"io.js","sourceRoot":"","sources":["../src/io.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mCAAyB;AACzB,2CAA4B;AAC5B,kDAAmC;AAsBnC;;;;;;;GAOG;AACH,SAAsB,EAAE,CACtB,MAAc,EACd,IAAY,EACZ,UAAuB,EAAE;;QAEzB,MAAM,EAAC,KAAK,EAAE,SAAS,EAAE,mBAAmB,EAAC,GAAG,eAAe,CAAC,OAAO,CAAC,CAAA;QAExE,MAAM,QAAQ,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;QAC7E,4CAA4C;QAC5C,IAAI,QAAQ,IAAI,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE;YAC3C,OAAM;SACP;QAED,wDAAwD;QACxD,MAAM,OAAO,GACX,QAAQ,IAAI,QAAQ,CAAC,WAAW,EAAE,IAAI,mBAAmB;YACvD,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;YACxC,CAAC,CAAC,IAAI,CAAA;QAEV,IAAI,CAAC,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE;YAClC,MAAM,IAAI,KAAK,CAAC,8BAA8B,MAAM,EAAE,CAAC,CAAA;SACxD;QACD,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;QAE5C,IAAI,UAAU,CAAC,WAAW,EAAE,EAAE;YAC5B,IAAI,CAAC,SAAS,EAAE;gBACd,MAAM,IAAI,KAAK,CACb,mBAAmB,MAAM,4DAA4D,CACtF,CAAA;aACF;iBAAM;gBACL,MAAM,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,CAAC,CAAA;aAChD;SACF;aAAM;YACL,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,EAAE,EAAE;gBACzC,oCAAoC;gBACpC,MAAM,IAAI,KAAK,CAAC,IAAI,OAAO,UAAU,MAAM,qBAAqB,CAAC,CAAA;aAClE;YAED,MAAM,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAA;SACvC;IACH,CAAC;CAAA;AAxCD,gBAwCC;AAED;;;;;;GAMG;AACH,SAAsB,EAAE,CACtB,MAAc,EACd,IAAY,EACZ,UAAuB,EAAE;;QAEzB,IAAI,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;YAC7B,IAAI,UAAU,GAAG,IAAI,CAAA;YACrB,IAAI,MAAM,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE;gBAClC,0CAA0C;gBAC1C,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAA;gBAC7C,UAAU,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;aACvC;YAED,IAAI,UAAU,EAAE;gBACd,IAAI,OAAO,CAAC,KAAK,IAAI,IAAI,IAAI,OAAO,CAAC,KAAK,EAAE;oBAC1C,MAAM,IAAI,CAAC,IAAI,CAAC,CAAA;iBACjB;qBAAM;oBACL,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAA;iBAC9C;aACF;SACF;QACD,MAAM,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAA;QAChC,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;CAAA;AAvBD,gBAuBC;AAED;;;;GAIG;AACH,SAAsB,IAAI,CAAC,SAAiB;;QAC1C,IAAI,MAAM,CAAC,UAAU,EAAE;YACrB,+BAA+B;YAC/B,sEAAsE;YACtE,IAAI,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE;gBAC7B,MAAM,IAAI,KAAK,CACb,iEAAiE,CAClE,CAAA;aACF;SACF;QACD,IAAI;YACF,+CAA+C;YAC/C,MAAM,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE;gBACzB,KAAK,EAAE,IAAI;gBACX,UAAU,EAAE,CAAC;gBACb,SAAS,EAAE,IAAI;gBACf,UAAU,EAAE,GAAG;aAChB,CAAC,CAAA;SACH;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,iCAAiC,GAAG,EAAE,CAAC,CAAA;SACxD;IACH,CAAC;CAAA;AArBD,oBAqBC;AAED;;;;;;GAMG;AACH,SAAsB,MAAM,CAAC,MAAc;;QACzC,WAAE,CAAC,MAAM,EAAE,kCAAkC,CAAC,CAAA;QAC9C,MAAM,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,EAAC,SAAS,EAAE,IAAI,EAAC,CAAC,CAAA;IAC/C,CAAC;CAAA;AAHD,wBAGC;AAED;;;;;;;GAOG;AACH,SAAsB,KAAK,CAAC,IAAY,EAAE,KAAe;;QACvD,IAAI,CAAC,IAAI,EAAE;YACT,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAA;SAChD;QAED,4BAA4B;QAC5B,IAAI,KAAK,EAAE;YACT,MAAM,MAAM,GAAW,MAAM,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;YAE/C,IAAI,CAAC,MAAM,EAAE;gBACX,IAAI,MAAM,CAAC,UAAU,EAAE;oBACrB,MAAM,IAAI,KAAK,CACb,qCAAqC,IAAI,wMAAwM,CAClP,CAAA;iBACF;qBAAM;oBACL,MAAM,IAAI,KAAK,CACb,qCAAqC,IAAI,gMAAgM,CAC1O,CAAA;iBACF;aACF;YAED,OAAO,MAAM,CAAA;SACd;QAED,MAAM,OAAO,GAAa,MAAM,UAAU,CAAC,IAAI,CAAC,CAAA;QAEhD,IAAI,OAAO,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;YACjC,OAAO,OAAO,CAAC,CAAC,CAAC,CAAA;SAClB;QAED,OAAO,EAAE,CAAA;IACX,CAAC;CAAA;AA/BD,sBA+BC;AAED;;;;GAIG;AACH,SAAsB,UAAU,CAAC,IAAY;;QAC3C,IAAI,CAAC,IAAI,EAAE;YACT,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAA;SAChD;QAED,sCAAsC;QACtC,MAAM,UAAU,GAAa,EAAE,CAAA;QAC/B,IAAI,MAAM,CAAC,UAAU,IAAI,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;YAC/C,KAAK,MAAM,SAAS,IAAI,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE;gBACpE,IAAI,SAAS,EAAE;oBACb,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;iBAC3B;aACF;SACF;QAED,+DAA+D;QAC/D,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;YACzB,MAAM,QAAQ,GAAW,MAAM,MAAM,CAAC,oBAAoB,CAAC,IAAI,EAAE,UAAU,CAAC,CAAA;YAE5E,IAAI,QAAQ,EAAE;gBACZ,OAAO,CAAC,QAAQ,CAAC,CAAA;aAClB;YAED,OAAO,EAAE,CAAA;SACV;QAED,uCAAuC;QACvC,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;YAC3B,OAAO,EAAE,CAAA;SACV;QAED,gCAAgC;QAChC,EAAE;QACF,iGAAiG;QACjG,+FAA+F;QAC/F,iGAAiG;QACjG,oBAAoB;QACpB,MAAM,WAAW,GAAa,EAAE,CAAA;QAEhC,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE;YACpB,KAAK,MAAM,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE;gBACtD,IAAI,CAAC,EAAE;oBACL,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;iBACpB;aACF;SACF;QAED,mBAAmB;QACnB,MAAM,OAAO,GAAa,EAAE,CAAA;QAE5B,KAAK,MAAM,SAAS,IAAI,WAAW,EAAE;YACnC,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,oBAAoB,CAChD,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,EAC1B,UAAU,CACX,CAAA;YACD,IAAI,QAAQ,EAAE;gBACZ,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;aACvB;SACF;QAED,OAAO,OAAO,CAAA;IAChB,CAAC;CAAA;AA7DD,gCA6DC;AAED,SAAS,eAAe,CAAC,OAAoB;IAC3C,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAA;IAC1D,MAAM,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;IAC5C,MAAM,mBAAmB,GACvB,OAAO,CAAC,mBAAmB,IAAI,IAAI;QACjC,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAA;IAC1C,OAAO,EAAC,KAAK,EAAE,SAAS,EAAE,mBAAmB,EAAC,CAAA;AAChD,CAAC;AAED,SAAe,cAAc,CAC3B,SAAiB,EACjB,OAAe,EACf,YAAoB,EACpB,KAAc;;QAEd,gDAAgD;QAChD,IAAI,YAAY,IAAI,GAAG;YAAE,OAAM;QAC/B,YAAY,EAAE,CAAA;QAEd,MAAM,MAAM,CAAC,OAAO,CAAC,CAAA;QAErB,MAAM,KAAK,GAAa,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;QAEvD,KAAK,MAAM,QAAQ,IAAI,KAAK,EAAE;YAC5B,MAAM,OAAO,GAAG,GAAG,SAAS,IAAI,QAAQ,EAAE,CAAA;YAC1C,MAAM,QAAQ,GAAG,GAAG,OAAO,IAAI,QAAQ,EAAE,CAAA;YACzC,MAAM,WAAW,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;YAE/C,IAAI,WAAW,CAAC,WAAW,EAAE,EAAE;gBAC7B,UAAU;gBACV,MAAM,cAAc,CAAC,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,KAAK,CAAC,CAAA;aAC7D;iBAAM;gBACL,MAAM,QAAQ,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;aACzC;SACF;QAED,kDAAkD;QAClD,MAAM,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;IAClE,CAAC;CAAA;AAED,qBAAqB;AACrB,SAAe,QAAQ,CACrB,OAAe,EACf,QAAgB,EAChB,KAAc;;QAEd,IAAI,CAAC,MAAM,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,cAAc,EAAE,EAAE;YAClD,oBAAoB;YACpB,IAAI;gBACF,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;gBAC5B,MAAM,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;aAC9B;YAAC,OAAO,CAAC,EAAE;gBACV,kCAAkC;gBAClC,IAAI,CAAC,CAAC,IAAI,KAAK,OAAO,EAAE;oBACtB,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA;oBACpC,MAAM,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;iBAC9B;gBACD,iDAAiD;aAClD;YAED,oBAAoB;YACpB,MAAM,WAAW,GAAW,MAAM,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAA;YAC1D,MAAM,MAAM,CAAC,OAAO,CAClB,WAAW,EACX,QAAQ,EACR,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CACtC,CAAA;SACF;aAAM,IAAI,CAAC,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,KAAK,EAAE;YACpD,MAAM,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAA;SACzC;IACH,CAAC;CAAA"} \ No newline at end of file diff --git a/node_modules/@actions/io/package.json b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/package.json similarity index 97% rename from node_modules/@actions/io/package.json rename to node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/package.json index 5ebc63a..e8c8d8f 100644 --- a/node_modules/@actions/io/package.json +++ b/node_modules/.deno/@actions+io@1.1.3/node_modules/@actions/io/package.json @@ -1,6 +1,6 @@ { "name": "@actions/io", - "version": "1.1.2", + "version": "1.1.3", "description": "Actions io lib", "keywords": [ "github", diff --git a/node_modules/.deno/@actions+tool-cache@2.0.1/.initialized b/node_modules/.deno/@actions+tool-cache@2.0.1/.initialized new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/core b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/core new file mode 120000 index 0000000..9961111 --- /dev/null +++ b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/core @@ -0,0 +1 @@ +../../../@actions+core@1.10.1/node_modules/@actions/core \ No newline at end of file diff --git a/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/exec b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/exec new file mode 120000 index 0000000..aa75ad2 --- /dev/null +++ b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/exec @@ -0,0 +1 @@ +../../../@actions+exec@1.1.1/node_modules/@actions/exec \ No newline at end of file diff --git a/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/http-client b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/http-client new file mode 120000 index 0000000..ccfba50 --- /dev/null +++ b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/http-client @@ -0,0 +1 @@ +../../../@actions+http-client@2.2.3/node_modules/@actions/http-client \ No newline at end of file diff --git a/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/io b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/io new file mode 120000 index 0000000..aa80d32 --- /dev/null +++ b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/io @@ -0,0 +1 @@ +../../../@actions+io@1.1.3/node_modules/@actions/io \ No newline at end of file diff --git a/node_modules/@actions/tool-cache/LICENSE.md b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/LICENSE.md similarity index 100% rename from node_modules/@actions/tool-cache/LICENSE.md rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/LICENSE.md diff --git a/node_modules/@actions/tool-cache/README.md b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/README.md similarity index 100% rename from node_modules/@actions/tool-cache/README.md rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/README.md diff --git a/node_modules/@actions/tool-cache/lib/manifest.d.ts b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/manifest.d.ts similarity index 100% rename from node_modules/@actions/tool-cache/lib/manifest.d.ts rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/manifest.d.ts diff --git a/node_modules/@actions/tool-cache/lib/manifest.js b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/manifest.js similarity index 100% rename from node_modules/@actions/tool-cache/lib/manifest.js rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/manifest.js diff --git a/node_modules/@actions/tool-cache/lib/manifest.js.map b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/manifest.js.map similarity index 100% rename from node_modules/@actions/tool-cache/lib/manifest.js.map rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/manifest.js.map diff --git a/node_modules/@actions/tool-cache/lib/retry-helper.d.ts b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/retry-helper.d.ts similarity index 100% rename from node_modules/@actions/tool-cache/lib/retry-helper.d.ts rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/retry-helper.d.ts diff --git a/node_modules/@actions/tool-cache/lib/retry-helper.js b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/retry-helper.js similarity index 100% rename from node_modules/@actions/tool-cache/lib/retry-helper.js rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/retry-helper.js diff --git a/node_modules/@actions/tool-cache/lib/retry-helper.js.map b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/retry-helper.js.map similarity index 100% rename from node_modules/@actions/tool-cache/lib/retry-helper.js.map rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/retry-helper.js.map diff --git a/node_modules/@actions/tool-cache/lib/tool-cache.d.ts b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/tool-cache.d.ts similarity index 100% rename from node_modules/@actions/tool-cache/lib/tool-cache.d.ts rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/tool-cache.d.ts diff --git a/node_modules/@actions/tool-cache/lib/tool-cache.js b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/tool-cache.js similarity index 100% rename from node_modules/@actions/tool-cache/lib/tool-cache.js rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/tool-cache.js diff --git a/node_modules/@actions/tool-cache/lib/tool-cache.js.map b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/tool-cache.js.map similarity index 100% rename from node_modules/@actions/tool-cache/lib/tool-cache.js.map rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/lib/tool-cache.js.map diff --git a/node_modules/@actions/tool-cache/package.json b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/package.json similarity index 100% rename from node_modules/@actions/tool-cache/package.json rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/package.json diff --git a/node_modules/@actions/tool-cache/scripts/Invoke-7zdec.ps1 b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/scripts/Invoke-7zdec.ps1 similarity index 100% rename from node_modules/@actions/tool-cache/scripts/Invoke-7zdec.ps1 rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/scripts/Invoke-7zdec.ps1 diff --git a/node_modules/@actions/tool-cache/scripts/externals/7zdec.exe b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/scripts/externals/7zdec.exe similarity index 100% rename from node_modules/@actions/tool-cache/scripts/externals/7zdec.exe rename to node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/@actions/tool-cache/scripts/externals/7zdec.exe diff --git a/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/semver b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/semver new file mode 120000 index 0000000..582bffa --- /dev/null +++ b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/semver @@ -0,0 +1 @@ +../../semver@6.3.1/node_modules/semver \ No newline at end of file diff --git a/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/uuid b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/uuid new file mode 120000 index 0000000..7a67bfb --- /dev/null +++ b/node_modules/.deno/@actions+tool-cache@2.0.1/node_modules/uuid @@ -0,0 +1 @@ +../../uuid@3.4.0/node_modules/uuid \ No newline at end of file diff --git a/node_modules/.deno/@fastify+busboy@2.1.1/.initialized b/node_modules/.deno/@fastify+busboy@2.1.1/.initialized new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/busboy/LICENSE b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/LICENSE similarity index 100% rename from node_modules/busboy/LICENSE rename to node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/LICENSE diff --git a/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/README.md b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/README.md new file mode 100644 index 0000000..ece3cc8 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/README.md @@ -0,0 +1,271 @@ +# busboy + +
+ +[![Build Status](https://github.com/fastify/busboy/actions/workflows/ci.yml/badge.svg)](https://github.com/fastify/busboy/actions) +[![Coverage Status](https://coveralls.io/repos/fastify/busboy/badge.svg?branch=master)](https://coveralls.io/r/fastify/busboy?branch=master) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/) +[![Security Responsible Disclosure](https://img.shields.io/badge/Security-Responsible%20Disclosure-yellow.svg)](https://github.com/fastify/.github/blob/main/SECURITY.md) + +
+ +
+ +[![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/streamsearch/LICENSE b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/LICENSE similarity index 98% rename from node_modules/streamsearch/LICENSE rename to node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/LICENSE index 9ea90e0..290762e 100644 --- a/node_modules/streamsearch/LICENSE +++ b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/LICENSE @@ -1,19 +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 +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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js new file mode 100644 index 0000000..3c8c081 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js new file mode 100644 index 0000000..65f667b --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js new file mode 100644 index 0000000..c91da1c --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts new file mode 100644 index 0000000..3c5b896 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js new file mode 100644 index 0000000..b90c0e8 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/main.d.ts b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/main.d.ts new file mode 100644 index 0000000..91b6448 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/main.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/main.js new file mode 100644 index 0000000..8794beb --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/types/multipart.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/types/multipart.js new file mode 100644 index 0000000..d691eca --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/types/urlencoded.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/types/urlencoded.js new file mode 100644 index 0000000..6f5f784 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/Decoder.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/Decoder.js new file mode 100644 index 0000000..7917678 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/basename.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/basename.js new file mode 100644 index 0000000..db58819 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/decodeText.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/decodeText.js new file mode 100644 index 0000000..eac7d35 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/getLimit.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/getLimit.js new file mode 100644 index 0000000..cb64fd6 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/parseParams.js b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/parseParams.js new file mode 100644 index 0000000..1698e62 --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/package.json b/node_modules/.deno/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/package.json new file mode 100644 index 0000000..83693ac --- /dev/null +++ b/node_modules/.deno/@fastify+busboy@2.1.1/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/.deno/@types+node@20.16.5/.initialized b/node_modules/.deno/@types+node@20.16.5/.initialized new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/@types/node/LICENSE b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/LICENSE old mode 100755 new mode 100644 similarity index 100% rename from node_modules/@types/node/LICENSE rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/LICENSE diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/README.md b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/README.md new file mode 100644 index 0000000..e2e090a --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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/v20. + +### Additional Details + * Last updated: Wed, 04 Sep 2024 21:35:57 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/ts4.8/assert.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/assert.d.ts old mode 100755 new mode 100644 similarity index 68% rename from node_modules/@types/node/ts4.8/assert.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/assert.d.ts index 9f916c1..4e465c5 --- a/node_modules/@types/node/ts4.8/assert.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/assert.d.ts @@ -1,9 +1,9 @@ /** - * The `assert` module provides a set of assertion functions for verifying + * The `node:assert` module provides a set of assertion functions for verifying * invariants. - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/assert.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/assert.js) */ -declare module 'assert' { +declare module "assert" { /** * An alias of {@link ok}. * @since v0.5.9 @@ -12,15 +12,29 @@ declare module 'assert' { function assert(value: unknown, message?: string | Error): asserts value; namespace assert { /** - * Indicates the failure of an assertion. All errors thrown by the `assert` module - * will be instances of the `AssertionError` class. + * 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; - code: 'ERR_ASSERTION'; + /** + * 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; @@ -31,14 +45,15 @@ declare module 'assert' { /** The `operator` property on the error instance. */ operator?: string | undefined; /** If provided, the generated stack trace omits frames before this function. */ - // tslint:disable-next-line:ban-types + // eslint-disable-next-line @typescript-eslint/ban-types stackStartFn?: Function | undefined; }); } /** - * This feature is currently experimental and behavior might still change. + * 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 - * @experimental + * @deprecated Deprecated */ class CallTracker { /** @@ -47,7 +62,7 @@ declare module 'assert' { * error. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * // Creates call tracker. * const tracker = new assert.CallTracker(); @@ -61,30 +76,47 @@ declare module 'assert' { * @since v14.2.0, v12.19.0 * @param [fn='A no-op function'] * @param [exact=1] - * @return that wraps `fn`. + * @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 'assert'; + * import assert from 'node:assert'; * * // Creates call tracker. * const tracker = new assert.CallTracker(); * * function func() {} * - * function foo() {} - * * // Returns a function that wraps func() that must be called exact times * // before tracker.verify(). * const callsfunc = tracker.calls(func, 2); * * // Returns an array containing information on callsfunc() - * tracker.report(); + * console.log(tracker.report()); * // [ * // { * // message: 'Expected the func function to be executed 2 time(s) but was @@ -97,15 +129,38 @@ declare module 'assert' { * // ] * ``` * @since v14.2.0, v12.19.0 - * @return of objects containing information about the wrapper functions returned by `calls`. + * @return An array of objects containing information about the wrapper functions returned by {@link tracker.calls()}. */ report(): CallTrackerReportInformation[]; /** - * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * 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 'assert'; + * import assert from 'node:assert'; * * // Creates call tracker. * const tracker = new assert.CallTracker(); @@ -125,6 +180,10 @@ declare module 'assert' { */ verify(): void; } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } interface CallTrackerReportInformation { message: string; /** The actual number of times the function was called. */ @@ -136,14 +195,14 @@ declare module 'assert' { /** A stack trace of the function. */ stack: object; } - type AssertPredicate = RegExp | (new () => object) | ((thrown: unknown) => boolean) | object | Error; + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; /** * Throws an `AssertionError` with the provided error message or a default * error message. If the `message` parameter is an instance of an `Error` then * it will be thrown instead of the `AssertionError`. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.fail(); * // AssertionError [ERR_ASSERTION]: Failed @@ -167,21 +226,21 @@ declare module 'assert' { expected: unknown, message?: string | Error, operator?: string, - // tslint:disable-next-line:ban-types - stackStartFn?: Function + // 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)`. + * 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 `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. * * Be aware that in the `repl` the error message will be different to the one * thrown in a file! See below for further details. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.ok(true); * // OK @@ -216,7 +275,7 @@ declare module 'assert' { * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * // Using `assert()` works the same: * assert(0); @@ -237,11 +296,11 @@ declare module 'assert' { * > Stability: 3 - Legacy: Use {@link strictEqual} instead. * * Tests shallow, coercive equality between the `actual` and `expected` parameters - * using the [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison) ( `==` ). `NaN` is special handled - * and treated as being identical in case both sides are `NaN`. + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * assert.equal(1, 1); * // OK, 1 == 1 @@ -256,8 +315,8 @@ declare module 'assert' { * // 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`. + * 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; @@ -270,12 +329,11 @@ declare module 'assert' { * * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. * - * Tests shallow, coercive inequality with the [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison)(`!=` ). `NaN` is special handled and treated as - * being identical in case both - * sides are `NaN`. + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * assert.notEqual(1, 2); * // OK @@ -287,8 +345,8 @@ declare module 'assert' { * // 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`. + * 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; @@ -322,24 +380,24 @@ declare module 'assert' { * Tests for any deep inequality. Opposite of {@link deepEqual}. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * const obj1 = { * a: { - * b: 1 - * } + * b: 1, + * }, * }; * const obj2 = { * a: { - * b: 2 - * } + * b: 2, + * }, * }; * const obj3 = { * a: { - * b: 1 - * } + * b: 1, + * }, * }; - * const obj4 = Object.create(obj1); + * const obj4 = { __proto__: obj1 }; * * assert.notDeepEqual(obj1, obj1); * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } @@ -354,18 +412,18 @@ declare module 'assert' { * // 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 + * 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 the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.strictEqual(1, 2); * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: @@ -392,18 +450,18 @@ declare module 'assert' { * // 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 + * 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 the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.notStrictEqual(1, 2); * // OK @@ -417,8 +475,8 @@ declare module 'assert' { * // 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 + * 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 */ @@ -434,7 +492,7 @@ declare module 'assert' { * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); * // OK @@ -459,20 +517,20 @@ declare module 'assert' { * 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 + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation * fails. * * Custom validation object/error instance: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * const err = new TypeError('Wrong value'); * err.code = 404; * err.foo = 'bar'; * err.info = { * nested: true, - * baz: 'text' + * baz: 'text', * }; * err.reg = /abc/i; * @@ -485,16 +543,16 @@ declare module 'assert' { * message: 'Wrong value', * info: { * nested: true, - * baz: 'text' - * } + * baz: 'text', + * }, * // Only properties on the validation object will be tested for. * // Using nested objects requires all properties to be present. Otherwise * // the validation is going to fail. - * } + * }, * ); * * // Using regular expressions to validate error properties: - * throws( + * assert.throws( * () => { * throw err; * }, @@ -508,17 +566,17 @@ declare module 'assert' { * info: { * nested: true, * // It is not possible to use regular expressions for nested properties! - * baz: 'text' + * 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 - * } + * reg: /abc/i, + * }, * ); * * // Fails due to the different `message` and `name` properties: - * throws( + * assert.throws( * () => { * const otherErr = new Error('Not found'); * // Copy all enumerable properties from `err` to `otherErr`. @@ -529,20 +587,20 @@ declare module 'assert' { * }, * // The error's `message` and `name` properties will also be checked when using * // an error as validation object. - * err + * err, * ); * ``` * * Validate instanceof using constructor: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.throws( * () => { * throw new Error('Wrong value'); * }, - * Error + * Error, * ); * ``` * @@ -552,13 +610,13 @@ declare module 'assert' { * therefore also include the error name. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.throws( * () => { * throw new Error('Wrong value'); * }, - * /^Error: Wrong value$/ + * /^Error: Wrong value$/, * ); * ``` * @@ -568,7 +626,7 @@ declare module 'assert' { * It will otherwise fail with an `AssertionError`. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.throws( * () => { @@ -584,17 +642,17 @@ declare module 'assert' { * // possible. * return true; * }, - * 'unexpected error' + * '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 + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using * a string as the second argument gets considered: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * function throwingFirst() { * throw new Error('First'); @@ -643,27 +701,27 @@ declare module 'assert' { * 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. + * 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 + * 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 + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation * function. See {@link throws} for more details. * * The following, for instance, will throw the `TypeError` because there is no * matching error type in the assertion: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, - * SyntaxError + * SyntaxError, * ); * ``` * @@ -671,27 +729,27 @@ declare module 'assert' { * 'Got unwanted exception...': * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, - * TypeError + * 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: + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, * /Wrong value/, - * 'Whoops' + * 'Whoops', * ); * // Throws: AssertionError: Got unwanted exception: Whoops * ``` @@ -702,10 +760,10 @@ declare module 'assert' { /** * 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. + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.ifError(null); * // OK @@ -737,21 +795,21 @@ declare module 'assert' { * calls the function and awaits the returned promise to complete. It will then * check that the promise is rejected. * - * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the - * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error - * handler is skipped. + * 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. + * each property will be tested for including the non-enumerable `message` and `name` properties. * - * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * await assert.rejects( * async () => { @@ -759,13 +817,13 @@ declare module 'assert' { * }, * { * name: 'TypeError', - * message: 'Wrong value' - * } + * message: 'Wrong value', + * }, * ); * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * await assert.rejects( * async () => { @@ -775,37 +833,40 @@ declare module 'assert' { * assert.strictEqual(err.name, 'TypeError'); * assert.strictEqual(err.message, 'Wrong value'); * return true; - * } + * }, * ); * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.rejects( * Promise.reject(new Error('Wrong value')), - * Error + * 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. + * `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; + 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 + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If * the function does not return a promise, `assert.doesNotReject()` will return a - * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * 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 @@ -814,24 +875,24 @@ declare module 'assert' { * 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 + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation * function. See {@link throws} for more details. * * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * await assert.doesNotReject( * async () => { * throw new TypeError('Wrong value'); * }, - * SyntaxError + * SyntaxError, * ); * ``` * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) * .then(() => { @@ -840,13 +901,20 @@ declare module 'assert' { * ``` * @since v10.0.0 */ - function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; - function doesNotReject(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; /** * Expects the `string` input to match the regular expression. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.match('I will fail', /pass/); * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... @@ -858,10 +926,10 @@ declare module 'assert' { * // OK * ``` * - * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * 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` then it will be thrown instead of the `AssertionError`. + * 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; @@ -869,7 +937,7 @@ declare module 'assert' { * Expects the `string` input not to match the regular expression. * * ```js - * import assert from 'assert/strict'; + * import assert from 'node:assert/strict'; * * assert.doesNotMatch('I will fail', /fail/); * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... @@ -881,32 +949,92 @@ declare module 'assert' { * // OK * ``` * - * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * 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` then it will be thrown instead of the `AssertionError`. + * 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; - const strict: Omit & { - (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; - }; + /** + * 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'); +declare module "node:assert" { + import assert = require("assert"); export = assert; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/assert/strict.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..f333913 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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/.deno/@types+node@20.16.5/node_modules/@types/node/async_hooks.d.ts old mode 100755 new mode 100644 similarity index 78% rename from node_modules/@types/node/async_hooks.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/async_hooks.d.ts index ed294eb..f5432e2 --- a/node_modules/@types/node/async_hooks.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/async_hooks.d.ts @@ -1,19 +1,27 @@ /** - * The `async_hooks` module provides an API to track asynchronous resources. It - * can be accessed using: + * 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 'async_hooks'; + * import async_hooks from 'node:async_hooks'; * ``` * @experimental - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/async_hooks.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/async_hooks.js) */ -declare module 'async_hooks' { +declare module "async_hooks" { /** * ```js - * import { executionAsyncId } from 'async_hooks'; + * 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() * }); @@ -36,7 +44,7 @@ declare module 'async_hooks' { * ``` * * Promise contexts may not get precise `executionAsyncIds` by default. - * See the section on `promise execution tracking`. + * 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. */ @@ -51,8 +59,8 @@ declare module 'async_hooks' { * but having an object representing the top-level can be helpful. * * ```js - * import { open } from 'fs'; - * import { executionAsyncId, executionAsyncResource } from 'async_hooks'; + * 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) => { @@ -64,11 +72,11 @@ declare module 'async_hooks' { * use of a tracking `Map` to store the metadata: * * ```js - * import { createServer } from 'http'; + * import { createServer } from 'node:http'; * import { * executionAsyncId, * executionAsyncResource, - * createHook + * createHook, * } from 'async_hooks'; * const sym = Symbol('state'); // Private symbol to avoid pollution * @@ -78,7 +86,7 @@ declare module 'async_hooks' { * if (cr) { * resource[sym] = cr[sym]; * } - * } + * }, * }).enable(); * * const server = createServer((req, res) => { @@ -109,17 +117,17 @@ declare module 'async_hooks' { * ``` * * Promise contexts may not get valid `triggerAsyncId`s by default. See - * the section on `promise execution tracking`. + * 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 + * @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; /** @@ -129,7 +137,9 @@ declare module 'async_hooks' { */ before?(asyncId: number): void; /** - * Called immediately after the callback specified in before is completed. + * 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; @@ -167,11 +177,11 @@ declare module 'async_hooks' { * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. * * ```js - * import { createHook } from 'async_hooks'; + * import { createHook } from 'node:async_hooks'; * * const asyncHook = createHook({ * init(asyncId, type, triggerAsyncId, resource) { }, - * destroy(asyncId) { } + * destroy(asyncId) { }, * }); * ``` * @@ -223,13 +233,13 @@ declare module 'async_hooks' { * The following is an overview of the `AsyncResource` API. * * ```js - * import { AsyncResource, executionAsyncId } from 'async_hooks'; + * 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 } + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, * ); * * // Run a function in the execution context of the resource. This will @@ -263,9 +273,6 @@ declare module 'async_hooks' { constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); /** * Binds the given function to the current execution context. - * - * The returned function will have an `asyncResource` property referencing - * the `AsyncResource` to which the function is bound. * @since v14.8.0, v12.19.0 * @param fn The function to bind to the current execution context. * @param type An optional name to associate with the underlying `AsyncResource`. @@ -273,23 +280,14 @@ declare module 'async_hooks' { static bind any, ThisArg>( fn: Func, type?: string, - thisArg?: ThisArg - ): Func & { - asyncResource: AsyncResource; - }; + thisArg?: ThisArg, + ): Func; /** * Binds the given function to execute to this `AsyncResource`'s scope. - * - * The returned function will have an `asyncResource` property referencing - * the `AsyncResource` to which the function is bound. * @since v14.8.0, v12.19.0 * @param fn The function to bind to the current `AsyncResource`. */ - bind any>( - fn: Func - ): Func & { - asyncResource: AsyncResource; - }; + 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 @@ -300,7 +298,11 @@ declare module 'async_hooks' { * @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; + 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 @@ -314,7 +316,6 @@ declare module 'async_hooks' { */ asyncId(): number; /** - * * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. */ triggerAsyncId(): number; @@ -322,17 +323,17 @@ declare module 'async_hooks' { /** * This class creates stores that stay coherent through asynchronous operations. * - * While you can create your own implementation on top of the `async_hooks` module,`AsyncLocalStorage` should be preferred as it is a performant and memory safe - * implementation that involves significant optimizations that are non-obvious to - * implement. + * 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 'http'; - * import { AsyncLocalStorage } from 'async_hooks'; + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; * * const asyncLocalStorage = new AsyncLocalStorage(); * @@ -364,18 +365,56 @@ declare module 'async_hooks' { * * Each instance of `AsyncLocalStorage` maintains an independent storage context. * Multiple instances can safely exist simultaneously without risk of interfering - * with each other data. + * 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. + * 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 + * 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. * @@ -395,8 +434,9 @@ declare module 'async_hooks' { 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 or - * the asynchronous operations created within the callback. + * 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. * @@ -410,6 +450,9 @@ declare module 'async_hooks' { * try { * asyncLocalStorage.run(store, () => { * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); * throw new Error(); * }); * } catch (e) { @@ -419,11 +462,12 @@ declare module 'async_hooks' { * ``` * @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 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. * @@ -469,7 +513,7 @@ declare module 'async_hooks' { * 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 + * 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 @@ -492,6 +536,6 @@ declare module 'async_hooks' { enterWith(store: T): void; } } -declare module 'node:async_hooks' { - export * from 'async_hooks'; +declare module "node:async_hooks" { + export * from "async_hooks"; } diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/buffer.d.ts old mode 100755 new mode 100644 similarity index 85% rename from node_modules/@types/node/buffer.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/buffer.d.ts index 1d9dd98..772db72 --- a/node_modules/@types/node/buffer.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/buffer.d.ts @@ -1,3 +1,8 @@ +// If lib.dom.d.ts or lib.webworker.d.ts is loaded, then use the global types. +// Otherwise, use the types from node. +type _Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : import("buffer").Blob; +type _File = typeof globalThis extends { onmessage: any; File: any } ? {} : import("buffer").File; + /** * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many * Node.js APIs support `Buffer`s. @@ -10,7 +15,7 @@ * recommended to explicitly reference it via an import or require statement. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Creates a zero-filled Buffer of length 10. * const buf1 = Buffer.alloc(10); @@ -41,11 +46,29 @@ * // 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/v16.9.0/lib/buffer.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/buffer.js) */ -declare module 'buffer' { - import { BinaryLike } from 'node:crypto'; - import { ReadableStream as WebReadableStream } from 'node:stream/web'; +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; @@ -53,7 +76,16 @@ declare module 'buffer' { MAX_LENGTH: number; MAX_STRING_LENGTH: number; }; - export type TranscodeEncoding = 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'latin1' | 'binary'; + 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. @@ -61,13 +93,13 @@ declare module 'buffer' { * 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'`. + * 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 'buffer'; + * import { Buffer, transcode } from 'node:buffer'; * * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); * console.log(newBuf.toString('ascii')); @@ -84,7 +116,7 @@ declare module 'buffer' { 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; + new(size: number): Buffer; prototype: Buffer; }; /** @@ -101,9 +133,10 @@ declare module 'buffer' { */ export interface BlobOptions { /** - * @default 'utf8' + * 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`. */ - encoding?: BufferEncoding | undefined; + 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 @@ -114,18 +147,17 @@ declare module 'buffer' { /** * 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 - * @experimental + * @since v15.7.0, v14.18.0 */ export class Blob { /** * The total size of the `Blob` in bytes. - * @since v15.7.0 + * @since v15.7.0, v14.18.0 */ readonly size: number; /** * The content-type of the `Blob`. - * @since v15.7.0 + * @since v15.7.0, v14.18.0 */ readonly type: string; /** @@ -136,17 +168,29 @@ declare module 'buffer' { * * String sources are also copied into the `Blob`. */ - constructor(sources: Array, options?: BlobOptions); + 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 + * @since v15.7.0, v14.18.0 */ arrayBuffer(): Promise; + /** + * The `blob.bytes()` method returns the byte of the `Blob` object as a `Promise`. + * + * ```js + * const blob = new Blob(['hello']); + * blob.bytes().then((bytes) => { + * console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ] + * }); + * ``` + * @since v20.16.0 + */ + bytes(): 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 + * @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` @@ -155,25 +199,69 @@ declare module 'buffer' { /** * Returns a promise that fulfills with the contents of the `Blob` decoded as a * UTF-8 string. - * @since v15.7.0 + * @since v15.7.0, v14.18.0 */ text(): Promise; /** - * Returns a new (WHATWG) `ReadableStream` that allows the content of the `Blob` to be read. + * 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; + global { + namespace NodeJS { + export { BufferEncoding }; + } // Buffer class - type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; type WithImplicitCoercion = | T | { - valueOf(): 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. @@ -187,68 +275,75 @@ declare module '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; + 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; + 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; + 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; + 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: ReadonlyArray): Buffer; + 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; + 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 'buffer'; + * 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. + * `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; + 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 | ReadonlyArray): Buffer; - from(data: WithImplicitCoercion | string>): 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. @@ -258,9 +353,9 @@ declare module 'buffer' { str: | WithImplicitCoercion | { - [Symbol.toPrimitive](hint: 'string'): string; - }, - encoding?: BufferEncoding + [Symbol.toPrimitive](hint: "string"): string; + }, + encoding?: BufferEncoding, ): Buffer; /** * Creates a new Buffer using the passed {data} @@ -271,7 +366,7 @@ declare module 'buffer' { * Returns `true` if `obj` is a `Buffer`, `false` otherwise. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * Buffer.isBuffer(Buffer.alloc(10)); // true * Buffer.isBuffer(Buffer.from('foo')); // true @@ -287,7 +382,7 @@ declare module 'buffer' { * or `false` otherwise. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * console.log(Buffer.isEncoding('utf8')); * // Prints: true @@ -316,7 +411,7 @@ declare module 'buffer' { * string. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const str = '\u00bd + \u00bc = \u00be'; * @@ -334,11 +429,14 @@ declare module 'buffer' { * @param [encoding='utf8'] If `string` is a string, this is its encoding. * @return The number of bytes contained within `string`. */ - byteLength(string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; + 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. + * 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 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. @@ -348,7 +446,7 @@ declare module 'buffer' { * truncated to `totalLength`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create a single `Buffer` from a list of three `Buffer` instances. * @@ -373,12 +471,29 @@ declare module 'buffer' { * @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: ReadonlyArray, totalLength?: number): Buffer; + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; /** - * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * Copies the underlying memory of `view` into a new `Buffer`. * * ```js - * import { Buffer } from 'buffer'; + * 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'); @@ -391,12 +506,12 @@ declare module 'buffer' { * @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): number; + 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(5); * @@ -404,12 +519,12 @@ declare module 'buffer' { * // Prints: * ``` * - * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(5, 'a'); * @@ -421,7 +536,7 @@ declare module 'buffer' { * initialized by calling `buf.fill(fill, encoding)`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); * @@ -439,15 +554,15 @@ declare module '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 | Buffer | number, encoding?: BufferEncoding): Buffer; + 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_INVALID_ARG_VALUE` is thrown. + * 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. + * _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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(10); * @@ -463,9 +578,8 @@ declare module 'buffer' { * 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)`, `Buffer.concat()`, and the - * deprecated`new Buffer(size)` constructor only when `size` is less than or equal - * to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * 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)`. @@ -478,15 +592,15 @@ declare module '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_INVALID_ARG_VALUE` is thrown. A zero-length `Buffer` is created - * if `size` is 0. + * 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 + * _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 KB are sliced from a single pre-allocated `Buffer`. This + * 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 @@ -498,7 +612,7 @@ declare module 'buffer' { * then copying out the relevant bits. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Need to keep around a few small chunks of memory. * const store = []; @@ -536,7 +650,7 @@ declare module 'buffer' { * written. However, partially encoded characters will not be written. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(256); * @@ -572,7 +686,7 @@ declare module 'buffer' { * as {@link constants.MAX_STRING_LENGTH}. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.allocUnsafe(26); * @@ -609,7 +723,7 @@ declare module 'buffer' { * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); * const json = JSON.stringify(buf); @@ -629,14 +743,14 @@ declare module 'buffer' { * @since v0.9.2 */ toJSON(): { - type: 'Buffer'; + 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('ABC'); * const buf2 = Buffer.from('414243', 'hex'); @@ -660,7 +774,7 @@ declare module 'buffer' { * * `-1` is returned if `target` should come _after_`buf` when sorted. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('ABC'); * const buf2 = Buffer.from('BCD'); @@ -681,10 +795,10 @@ declare module 'buffer' { * // (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. + * 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 'buffer'; + * 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]); @@ -697,7 +811,7 @@ declare module 'buffer' { * // Prints: 1 * ``` * - * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * `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. @@ -705,7 +819,13 @@ declare module 'buffer' { * @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): number; + 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`. * @@ -714,7 +834,7 @@ declare module 'buffer' { * different function arguments. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create two `Buffer` instances. * const buf1 = Buffer.allocUnsafe(26); @@ -735,7 +855,7 @@ declare module 'buffer' { * ``` * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create a `Buffer` and copy data from one region to an overlapping region * // within the same `Buffer`. @@ -764,13 +884,11 @@ declare module 'buffer' { * Returns a new `Buffer` that references the same memory as the original, but * offset and cropped by the `start` and `end` indices. * - * This is the same behavior as `buf.subarray()`. - * * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('buffer'); * @@ -781,8 +899,17 @@ declare module 'buffer' { * * 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). */ @@ -799,7 +926,7 @@ declare module 'buffer' { * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte * // from the original `Buffer`. @@ -826,7 +953,7 @@ declare module 'buffer' { * end of `buf` rather than the beginning. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('buffer'); * @@ -853,7 +980,7 @@ declare module 'buffer' { * `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -874,7 +1001,7 @@ declare module 'buffer' { * `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -895,7 +1022,7 @@ declare module 'buffer' { * This function is also available under the `writeBigUint64BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -919,7 +1046,7 @@ declare module 'buffer' { * Writes `value` to `buf` at the specified `offset` as little-endian * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -948,7 +1075,7 @@ declare module 'buffer' { * This function is also available under the `writeUintLE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -976,7 +1103,7 @@ declare module 'buffer' { * This function is also available under the `writeUintBE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -1002,7 +1129,7 @@ declare module 'buffer' { * when `value` is anything other than a signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -1023,7 +1150,7 @@ declare module 'buffer' { * signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(6); * @@ -1045,7 +1172,7 @@ declare module 'buffer' { * This function is also available under the `readBigUint64BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); * @@ -1067,7 +1194,7 @@ declare module 'buffer' { * This function is also available under the `readBigUint64LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); * @@ -1102,13 +1229,13 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1126,13 +1253,13 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1152,11 +1279,11 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1169,11 +1296,11 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); * @@ -1195,7 +1322,7 @@ declare module 'buffer' { * This function is also available under the `readUint8` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, -2]); * @@ -1216,12 +1343,12 @@ declare module 'buffer' { */ readUint8(offset?: number): number; /** - * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56]); * @@ -1247,7 +1374,7 @@ declare module 'buffer' { * This function is also available under the `readUint16BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56]); * @@ -1271,7 +1398,7 @@ declare module 'buffer' { * This function is also available under the `readUint32LE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); * @@ -1295,7 +1422,7 @@ declare module 'buffer' { * This function is also available under the `readUint32BE` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); * @@ -1317,7 +1444,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([-1, 5]); * @@ -1338,7 +1465,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 5]); * @@ -1357,7 +1484,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 5]); * @@ -1374,7 +1501,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 0, 0, 5]); * @@ -1393,7 +1520,7 @@ declare module 'buffer' { * Integers read from a `Buffer` are interpreted as two's complement signed values. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([0, 0, 0, 5]); * @@ -1408,7 +1535,7 @@ declare module 'buffer' { * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4]); * @@ -1425,7 +1552,7 @@ declare module 'buffer' { * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4]); * @@ -1440,7 +1567,7 @@ declare module 'buffer' { * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); * @@ -1457,7 +1584,7 @@ declare module 'buffer' { * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); * @@ -1474,7 +1601,7 @@ declare module 'buffer' { * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); * @@ -1496,7 +1623,7 @@ declare module 'buffer' { * between UTF-16 little-endian and UTF-16 big-endian: * * ```js - * import { Buffer } from 'buffer'; + * 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. @@ -1510,7 +1637,7 @@ declare module 'buffer' { * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); * @@ -1536,7 +1663,7 @@ declare module 'buffer' { * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); * @@ -1565,7 +1692,7 @@ declare module 'buffer' { * This function is also available under the `writeUint8` alias. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1589,13 +1716,13 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1617,13 +1744,13 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1645,13 +1772,13 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1672,13 +1799,13 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1706,7 +1833,7 @@ declare module 'buffer' { * `value` is interpreted and written as a two's complement signed integer. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(2); * @@ -1723,13 +1850,13 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(2); * @@ -1745,13 +1872,13 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(2); * @@ -1767,13 +1894,13 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1789,13 +1916,13 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1815,7 +1942,7 @@ declare module 'buffer' { * undefined when `value` is anything other than a JavaScript number. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1835,7 +1962,7 @@ declare module 'buffer' { * undefined when `value` is anything other than a JavaScript number. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(4); * @@ -1851,11 +1978,11 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -1871,11 +1998,11 @@ declare module 'buffer' { */ 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 + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(8); * @@ -1895,7 +2022,7 @@ declare module 'buffer' { * the entire `buf` will be filled: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Fill a `Buffer` with the ASCII character 'h'. * @@ -1903,6 +2030,12 @@ declare module 'buffer' { * * 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 @@ -1913,7 +2046,7 @@ declare module 'buffer' { * then only the bytes of that character that fit into `buf` are written: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * // Fill a `Buffer` with character that takes up two bytes in UTF-8. * @@ -1925,7 +2058,7 @@ declare module 'buffer' { * fill data remains, an exception is thrown: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(5); * @@ -1937,7 +2070,7 @@ declare module 'buffer' { * // Throws an exception. * ``` * @since v0.5.0 - * @param value The value with which to fill `buf`. + * @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. @@ -1947,14 +2080,14 @@ declare module 'buffer' { /** * If `value` is: * - * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * 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.slice()`. + * 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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('this is a buffer'); * @@ -1979,7 +2112,7 @@ declare module 'buffer' { * // 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, + * 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 @@ -1987,7 +2120,7 @@ declare module 'buffer' { * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const b = Buffer.from('abcdef'); * @@ -2018,7 +2151,7 @@ declare module 'buffer' { * rather than the first occurrence. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('this buffer is a buffer'); * @@ -2045,7 +2178,7 @@ declare module 'buffer' { * // 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, + * 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 @@ -2053,7 +2186,7 @@ declare module '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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const b = Buffer.from('abcdef'); * @@ -2081,36 +2214,11 @@ declare module 'buffer' { * @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 '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 'buffer'; + * import { Buffer } from 'node:buffer'; * * const buf = Buffer.from('this is a buffer'); * @@ -2136,62 +2244,6 @@ declare module 'buffer' { * @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 '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 '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; /** @@ -2204,9 +2256,9 @@ declare module 'buffer' { * **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 - * @deprecated Use `Buffer.from(data, 'base64')` instead. + * **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; @@ -2220,14 +2272,30 @@ declare module 'buffer' { * **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 - * @deprecated Use `buf.toString('base64')` instead. + * **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 import("buffer").Blob; + interface File extends _File {} + /** + * `File` class is a global reference for `require('node:buffer').File` + * https://nodejs.org/api/buffer.html#class-file + * @since v20.0.0 + */ + var File: typeof globalThis extends { onmessage: any; File: infer T } ? T + : typeof import("buffer").File; } } -declare module 'node:buffer' { - export * from 'buffer'; +declare module "node:buffer" { + export * from "buffer"; } diff --git a/node_modules/@types/node/ts4.8/child_process.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/child_process.d.ts old mode 100755 new mode 100644 similarity index 70% rename from node_modules/@types/node/ts4.8/child_process.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/child_process.d.ts index d383145..b642adc --- a/node_modules/@types/node/ts4.8/child_process.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/child_process.d.ts @@ -1,10 +1,10 @@ /** - * The `child_process` module provides the ability to spawn subprocesses in + * 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('child_process'); + * const { spawn } = require('node:child_process'); * const ls = spawn('ls', ['-lh', '/usr']); * * ls.stdout.on('data', (data) => { @@ -25,24 +25,27 @@ * 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. + * 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 it is in the `options` object. Otherwise, `process.env.PATH` is - * used. + * 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`. + * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. * * The {@link spawn} method spawns the child process asynchronously, * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks * the event loop until the spawned process either exits or is terminated. * - * For convenience, the `child_process` module provides a handful of synchronous - * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * 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 @@ -60,16 +63,17 @@ * 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/v16.9.0/lib/child_process.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/child_process.js) */ -declare module 'child_process' { - import { ObjectEncodingOptions } from 'node:fs'; - import { EventEmitter, Abortable } from 'node:events'; - import * as net from 'node:net'; - import { Writable, Readable, Stream, Pipe } from 'node:stream'; - import { URL } from 'node:url'; +declare module "child_process" { + import { ObjectEncodingOptions } from "node:fs"; + import { Abortable, EventEmitter } from "node:events"; + import * as dgram from "node:dgram"; + 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; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; /** * Instances of the `ChildProcess` represent spawned child processes. * @@ -91,8 +95,7 @@ declare module 'child_process' { * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will * refer to the same value. * - * The `subprocess.stdin` property can be `undefined` if the child process could - * not be successfully spawned. + * 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; @@ -106,7 +109,7 @@ declare module 'child_process' { * refer to the same value. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn('ls'); * @@ -115,8 +118,7 @@ declare module 'child_process' { * }); * ``` * - * The `subprocess.stdout` property can be `null` if the child process could - * not be successfully spawned. + * 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; @@ -129,21 +131,20 @@ declare module 'child_process' { * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will * refer to the same value. * - * The `subprocess.stderr` property can be `null` if the child process could - * not be successfully spawned. + * 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 currently exists, this property is `undefined`. + * 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`, + * 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 @@ -151,16 +152,16 @@ declare module 'child_process' { * in the array are `null`. * * ```js - * const assert = require('assert'); - * const fs = require('fs'); - * const child_process = require('child_process'); + * 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); @@ -186,7 +187,7 @@ declare module 'child_process' { // stderr Readable | Writable | null | undefined, // extra - Readable | Writable | null | undefined // extra + Readable | Writable | null | undefined, // extra ]; /** * The `subprocess.killed` property indicates whether the child process @@ -201,7 +202,7 @@ declare module 'child_process' { * emitted. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const grep = spawn('grep', ['ssh']); * * console.log(`Spawned child pid: ${grep.pid}`); @@ -212,7 +213,7 @@ declare module 'child_process' { 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. + * 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; @@ -248,7 +249,7 @@ declare module 'child_process' { * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const grep = spawn('grep', ['ssh']); * * grep.on('close', (code, signal) => { @@ -272,7 +273,7 @@ declare module 'child_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'`). + * 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 @@ -281,7 +282,7 @@ declare module 'child_process' { * * ```js * 'use strict'; - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn( * 'sh', @@ -291,8 +292,8 @@ declare module 'child_process' { * console.log(process.pid, 'is alive') * }, 500);"`, * ], { - * stdio: ['inherit', 'inherit', 'inherit'] - * } + * stdio: ['inherit', 'inherit', 'inherit'], + * }, * ); * * setTimeout(() => { @@ -302,6 +303,11 @@ declare module 'child_process' { * @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 @@ -314,7 +320,7 @@ declare module 'child_process' { * For example, in the parent script: * * ```js - * const cp = require('child_process'); + * const cp = require('node:child_process'); * const n = cp.fork(`${__dirname}/sub.js`); * * n.on('message', (m) => { @@ -341,20 +347,20 @@ declare module 'child_process' { * * 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. + * 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. + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. * * 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 + * 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 @@ -368,10 +374,10 @@ declare module 'child_process' { * a TCP server object to the child process as illustrated in the example below: * * ```js - * const subprocess = require('child_process').fork('subprocess.js'); + * const subprocess = require('node:child_process').fork('subprocess.js'); * * // Open up the server object and send the handle. - * const server = require('net').createServer(); + * const server = require('node:net').createServer(); * server.on('connection', (socket) => { * socket.end('handled by parent'); * }); @@ -395,10 +401,9 @@ declare module 'child_process' { * Once the server is now shared between the parent and child, some connections * can be handled by the parent and some by the child. * - * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on - * a `'message'` event instead of `'connection'` and using `server.bind()` instead - * of `server.listen()`. This is, however, currently only supported on Unix - * platforms. + * 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 * @@ -407,13 +412,13 @@ declare module 'child_process' { * handle connections with "normal" or "special" priority: * * ```js - * const { fork } = require('child_process'); + * 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('net').createServer({ pauseOnConnect: true }); + * const server = require('node:net').createServer({ pauseOnConnect: true }); * server.on('connection', (socket) => { * * // If this is special priority... @@ -450,11 +455,17 @@ declare module 'child_process' { * as the connection may have been closed during the time it takes to send the * connection to the child. * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v20.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v20.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v20.x/api/dgram.html#class-dgramsocket) object. * @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; + 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 @@ -473,17 +484,17 @@ declare module 'child_process' { 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 + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not * include the child in its reference count, allowing the parent to exit * independently of the child, unless there is an established IPC channel between * the child and the parent. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn(process.argv[0], ['child_program.js'], { * detached: true, - * stdio: 'ignore' + * stdio: 'ignore', * }); * * subprocess.unref(); @@ -497,11 +508,11 @@ declare module 'child_process' { * to wait for the child to exit before exiting itself. * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * * const subprocess = spawn(process.argv[0], ['child_program.js'], { * detached: true, - * stdio: 'ignore' + * stdio: 'ignore', * }); * * subprocess.unref(); @@ -520,47 +531,53 @@ declare module 'child_process' { * 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; + 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; + 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; + 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; + 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; + 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; + 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 { @@ -574,11 +591,13 @@ declare module 'child_process' { // stderr Readable | Writable | null | undefined, // extra, no modification - 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 { + interface ChildProcessByStdio + extends ChildProcess + { stdin: I; stdout: O; stderr: E; @@ -588,15 +607,15 @@ declare module 'child_process' { E, Readable | Writable | null | undefined, // extra, no modification - 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'; + 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. @@ -621,7 +640,7 @@ declare module 'child_process' { } interface CommonOptions extends ProcessEnvOptions { /** - * @default true + * @default false */ windowsHide?: boolean | undefined; /** @@ -631,6 +650,15 @@ declare module 'child_process' { } 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; @@ -641,14 +669,18 @@ declare module 'child_process' { interface SpawnOptionsWithoutStdio extends SpawnOptions { stdio?: StdioPipeNamed | StdioPipe[] | undefined; } - type StdioNull = 'inherit' | 'ignore' | Stream; - type StdioPipeNamed = 'pipe' | 'overlapped'; + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; type StdioPipe = undefined | null | StdioPipeNamed; - interface SpawnOptionsWithStdioTuple extends SpawnOptions { + 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 + * 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** @@ -660,7 +692,7 @@ declare module 'child_process' { * ```js * const defaults = { * cwd: undefined, - * env: process.env + * env: process.env, * }; * ``` * @@ -679,7 +711,7 @@ declare module 'child_process' { * exit code: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const ls = spawn('ls', ['-lh', '/usr']); * * ls.stdout.on('data', (data) => { @@ -698,7 +730,7 @@ declare module 'child_process' { * Example: A very elaborate way to run `ps ax | grep ssh` * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const ps = spawn('ps', ['ax']); * const grep = spawn('grep', ['ssh']); * @@ -735,7 +767,7 @@ declare module 'child_process' { * Example of checking for failed `spawn`: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const subprocess = spawn('bad_command'); * * subprocess.on('error', (err) => { @@ -746,14 +778,14 @@ declare module 'child_process' { * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process * title while others (Windows, SunOS) will use `command`. * - * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, - * retrieve it with the`process.argv0` property instead. + * 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 + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js - * const { spawn } = require('child_process'); + * const { spawn } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const grep = spawn('grep', ['ssh'], { signal }); @@ -767,26 +799,86 @@ declare module 'child_process' { * @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: 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?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; - function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; - function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; - function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; - function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; - function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; - function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; - function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; - function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; - function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; + 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; @@ -804,6 +896,8 @@ declare module 'child_process' { 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 @@ -812,7 +906,7 @@ declare module 'child_process' { * need to be dealt with accordingly: * * ```js - * const { exec } = require('child_process'); + * 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 @@ -825,9 +919,9 @@ declare module 'child_process' { * **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 + * 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 + * 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 @@ -838,7 +932,7 @@ declare module 'child_process' { * encoding, `Buffer` objects will be passed to the callback instead. * * ```js - * const { exec } = require('child_process'); + * const { exec } = require('node:child_process'); * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { * if (error) { * console.error(`exec error: ${error}`); @@ -857,14 +951,14 @@ declare module 'child_process' { * 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 + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In * case of an error (including any error resulting in an exit code other than 0), a * rejected promise is returned, with the same `error` object given in the * callback, but with two additional properties `stdout` and `stderr`. * * ```js - * const util = require('util'); - * const exec = util.promisify(require('child_process').exec); + * const util = require('node:util'); + * const exec = util.promisify(require('node:child_process').exec); * * async function lsExample() { * const { stdout, stderr } = await exec('ls'); @@ -874,15 +968,15 @@ declare module 'child_process' { * lsExample(); * ``` * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js - * const { exec } = require('child_process'); + * const { exec } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = exec('grep ssh', { signal }, (error) => { - * console.log(error); // an AbortError + * console.error(error); // an AbortError * }); * controller.abort(); * ``` @@ -890,14 +984,17 @@ declare module 'child_process' { * @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; + 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; + encoding: "buffer" | null; } & ExecOptions, - callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, ): ChildProcess; // `options` with well known `encoding` means stdout/stderr are definitely `string`. function exec( @@ -905,7 +1002,7 @@ declare module 'child_process' { options: { encoding: BufferEncoding; } & ExecOptions, - callback?: (error: ExecException | null, stdout: string, stderr: string) => void + 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`. @@ -914,15 +1011,19 @@ declare module 'child_process' { options: { encoding: BufferEncoding; } & ExecOptions, - callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + 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; + 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 + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, ): ChildProcess; interface PromiseWithChild extends Promise { child: ChildProcess; @@ -935,8 +1036,8 @@ declare module 'child_process' { function __promisify__( command: string, options: { - encoding: 'buffer' | null; - } & ExecOptions + encoding: "buffer" | null; + } & ExecOptions, ): PromiseWithChild<{ stdout: Buffer; stderr: Buffer; @@ -945,21 +1046,21 @@ declare module 'child_process' { command: string, options: { encoding: BufferEncoding; - } & ExecOptions + } & ExecOptions, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( command: string, - options: ExecOptions + options: ExecOptions, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( command: string, - options?: (ObjectEncodingOptions & ExecOptions) | null + options?: (ObjectEncodingOptions & ExecOptions) | null, ): PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer; @@ -976,12 +1077,15 @@ declare module 'child_process' { encoding: BufferEncoding; } interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: 'buffer' | null; + encoding: "buffer" | null; } interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { encoding: BufferEncoding; } - type ExecFileException = ExecException & NodeJS.ErrnoException; + 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 @@ -992,7 +1096,7 @@ declare module 'child_process' { * supported. * * ```js - * const { execFile } = require('child_process'); + * const { execFile } = require('node:child_process'); * const child = execFile('node', ['--version'], (error, stdout, stderr) => { * if (error) { * throw error; @@ -1009,14 +1113,14 @@ declare module 'child_process' { * 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 + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In * case of an error (including any error resulting in an exit code other than 0), a * rejected promise is returned, with the same `error` object given in the * callback, but with two additional properties `stdout` and `stderr`. * * ```js - * const util = require('util'); - * const execFile = util.promisify(require('child_process').execFile); + * 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); @@ -1028,15 +1132,15 @@ declare module 'child_process' { * **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 + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js - * const { execFile } = require('child_process'); + * const { execFile } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = execFile('node', ['--version'], { signal }, (error) => { - * console.log(error); // an AbortError + * console.error(error); // an AbortError * }); * controller.abort(); * ``` @@ -1046,56 +1150,92 @@ declare module 'child_process' { * @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?: ReadonlyArray | null): ChildProcess; - function execFile(file: string, args: ReadonlyArray | 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: ReadonlyArray | 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: ReadonlyArray | undefined | null, + 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 + 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: ReadonlyArray | undefined | null, options: ExecFileOptionsWithStringEncoding, - callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + 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: ReadonlyArray | undefined | null, options: ExecFileOptionsWithOtherEncoding, - callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void + 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: ReadonlyArray | undefined | null, options: ExecFileOptions, - callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + 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 + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, ): ChildProcess; function execFile( file: string, - args: ReadonlyArray | undefined | null, + args: readonly string[] | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, - callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, ): ChildProcess; namespace execFile { function __promisify__(file: string): PromiseWithChild<{ @@ -1104,82 +1244,82 @@ declare module 'child_process' { }>; function __promisify__( file: string, - args: ReadonlyArray | undefined | null + args: readonly string[] | undefined | null, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, - options: ExecFileOptionsWithBufferEncoding + options: ExecFileOptionsWithBufferEncoding, ): PromiseWithChild<{ stdout: Buffer; stderr: Buffer; }>; function __promisify__( file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithBufferEncoding + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, ): PromiseWithChild<{ stdout: Buffer; stderr: Buffer; }>; function __promisify__( file: string, - options: ExecFileOptionsWithStringEncoding + options: ExecFileOptionsWithStringEncoding, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithStringEncoding + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, - options: ExecFileOptionsWithOtherEncoding + options: ExecFileOptionsWithOtherEncoding, ): PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer; }>; function __promisify__( file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithOtherEncoding + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, ): PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer; }>; function __promisify__( file: string, - options: ExecFileOptions + options: ExecFileOptions, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptions + args: readonly string[] | undefined | null, + options: ExecFileOptions, ): PromiseWithChild<{ stdout: string; stderr: string; }>; function __promisify__( file: string, - options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, ): PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer; }>; function __promisify__( file: string, - args: ReadonlyArray | undefined | null, - options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, ): PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer; @@ -1189,6 +1329,15 @@ declare module 'child_process' { 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; @@ -1207,7 +1356,7 @@ declare module 'child_process' { * 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 + * 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 @@ -1217,9 +1366,9 @@ declare module '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. + * 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 + * 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 @@ -1228,7 +1377,7 @@ declare module 'child_process' { * console.log(`Hello from ${process.argv[2]}!`); * }, 1_000); * } else { - * const { fork } = require('child_process'); + * const { fork } = require('node:child_process'); * const controller = new AbortController(); * const { signal } = controller; * const child = fork(__filename, ['child'], { signal }); @@ -1242,18 +1391,18 @@ declare module 'child_process' { * @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?: ReadonlyArray, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess; interface SpawnSyncOptions extends CommonSpawnOptions { input?: string | NodeJS.ArrayBufferView | undefined; maxBuffer?: number | undefined; - encoding?: BufferEncoding | 'buffer' | null | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; } interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { encoding: BufferEncoding; } interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding?: 'buffer' | null | undefined; + encoding?: "buffer" | null | undefined; } interface SpawnSyncReturns { pid: number; @@ -1283,16 +1432,37 @@ declare module 'child_process' { 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: ReadonlyArray): SpawnSyncReturns; - function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - function spawnSync(command: string, args?: ReadonlyArray, 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; + encoding?: BufferEncoding | "buffer" | null | undefined; } interface ExecSyncOptions extends CommonExecOptions { shell?: string | undefined; @@ -1301,13 +1471,13 @@ declare module 'child_process' { encoding: BufferEncoding; } interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { - encoding?: 'buffer' | null | undefined; + 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 + * 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. @@ -1330,7 +1500,7 @@ declare module 'child_process' { encoding: BufferEncoding; } interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding?: 'buffer' | null; // specify `null`. + encoding?: "buffer" | null; // specify `null`. } /** * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not @@ -1356,11 +1526,19 @@ declare module 'child_process' { 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: ReadonlyArray): Buffer; - function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithStringEncoding): string; - function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; - function execFileSync(file: string, args?: ReadonlyArray, 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'; +declare module "node:child_process" { + export * from "child_process"; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/cluster.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..7711927 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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.13.1/lib/cluster.js) + */ +declare module "cluster" { + import * as child from "node:child_process"; + import EventEmitter = require("node:events"); + import * as net from "node:net"; + type SerializationType = "json" | "advanced"; + export interface ClusterSettings { + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ + exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ + args?: string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ + silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-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/.deno/@types+node@20.16.5/node_modules/@types/node/console.d.ts old mode 100755 new mode 100644 similarity index 71% rename from node_modules/@types/node/console.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/console.d.ts index ede7a53..3d1a6c2 --- a/node_modules/@types/node/console.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/console.d.ts @@ -1,15 +1,16 @@ /** - * The `console` module provides a simple debugging console that is similar to the - * JavaScript console mechanism provided by web browsers. + * 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` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * * 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` for + * 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`: @@ -53,14 +54,14 @@ * myConsole.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to err * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/console.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/console.js) */ -declare module 'console' { - import console = require('node:console'); +declare module "console" { + import console = require("node:console"); export = console; } -declare module 'node:console' { - import { InspectOptions } from 'node:util'; +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 { @@ -68,7 +69,8 @@ declare module 'node:console' { /** * `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()`. + * 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. * @@ -91,7 +93,7 @@ declare module 'node:console' { * 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 + * 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 @@ -123,7 +125,7 @@ declare module 'node:console' { * > * ``` * @since v8.3.0 - * @param label The display label for the counter. + * @param [label='default'] The display label for the counter. */ count(label?: string): void; /** @@ -141,7 +143,7 @@ declare module 'node:console' { * > * ``` * @since v8.3.0 - * @param label The display label for the counter. + * @param [label='default'] The display label for the counter. */ countReset(label?: string): void; /** @@ -150,7 +152,7 @@ declare module 'node:console' { */ debug(message?: any, ...optionalParams: any[]): void; /** - * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. + * 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 */ @@ -164,7 +166,8 @@ declare module 'node:console' { /** * 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()`). + * 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; @@ -174,13 +177,15 @@ declare module 'node:console' { * // Prints: error 5, to stderr * ``` * - * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string - * values are concatenated. See `util.format()` for more information. + * 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. + * 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. @@ -193,7 +198,7 @@ declare module 'node:console' { */ groupCollapsed(...label: any[]): void; /** - * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. + * Decreases indentation of subsequent lines by spaces for `groupIndentation` length. * @since v8.5.0 */ groupEnd(): void; @@ -205,7 +210,8 @@ declare module 'node:console' { /** * 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()`). + * 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; @@ -215,13 +221,13 @@ declare module 'node:console' { * // Prints: count: 5, to stdout * ``` * - * See `util.format()` for more information. + * 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. + * 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 @@ -250,13 +256,14 @@ declare module 'node:console' { * @since v10.0.0 * @param properties Alternate properties for constructing the table. */ - table(tabularData: any, properties?: ReadonlyArray): void; + 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; /** @@ -264,12 +271,13 @@ declare module 'node:console' { * prints the result to `stdout`: * * ```js - * console.time('100-elements'); - * for (let i = 0; i < 100; i++) {} - * console.timeEnd('100-elements'); - * // prints 100-elements: 225.438ms + * 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; /** @@ -285,10 +293,12 @@ declare module 'node:console' { * 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()` formatted message and stack trace to the current position in the code. + * 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'); @@ -315,18 +325,32 @@ declare module 'node:console' { warn(message?: any, ...optionalParams: any[]): void; // --- Inspector mode only --- /** - * This method does not display anything unless used in the inspector. - * Starts a JavaScript CPU profile with an optional label. + * 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. + * 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. - * Adds an event with the label `label` to the Timeline panel of the inspector. + * 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; } @@ -336,12 +360,13 @@ declare module 'node:console' { * * 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` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * * 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` for + * 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`: @@ -385,25 +410,40 @@ declare module 'node:console' { * myConsole.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to err * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) + * @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; - colorMode?: boolean | 'auto' | 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 + * 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; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; } } var console: Console; diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/constants.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..c3ac2b8 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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/.deno/@types+node@20.16.5/node_modules/@types/node/crypto.d.ts old mode 100755 new mode 100644 similarity index 70% rename from node_modules/@types/node/crypto.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/crypto.d.ts index 4f6dc9f..10683ed --- a/node_modules/@types/node/crypto.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/crypto.d.ts @@ -1,9 +1,10 @@ /** - * The `crypto` module provides cryptographic functionality that includes a set of - * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * 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('crypto'); + * const { createHmac } = await import('node:crypto'); * * const secret = 'abcdefg'; * const hash = createHmac('sha256', secret) @@ -13,12 +14,64 @@ * // Prints: * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/crypto.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/crypto.js) */ -declare module 'crypto' { - import * as stream from 'node:stream'; - import { PeerCertificate } from 'node:tls'; - interface Certificate { +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 @@ -42,41 +95,18 @@ declare module 'crypto' { */ verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; } - const Certificate: Certificate & { - /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ - new (): Certificate; - /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ - (): Certificate; - /** - * @param spkac - * @returns The challenge component of the `spkac` data structure, - * which includes a public key and a challenge. - */ - exportChallenge(spkac: BinaryLike): Buffer; - /** - * @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; - /** - * @param spkac - * @returns `true` if the given `spkac` data structure is valid, - * `false` otherwise. - */ - verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; - }; namespace constants { - // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + // 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 "speshul" version of DTLS_BAD_VER. */ + /** 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; @@ -84,39 +114,33 @@ declare module 'crypto' { const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ - const SSL_OP_EPHEMERAL_RSA: number; /** Allows initial connection to servers that do not support RI. */ const SSL_OP_LEGACY_SERVER_CONNECT: number; - const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - const SSL_OP_MICROSOFT_SESS_ID_BUG: number; - /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ - const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - const SSL_OP_NETSCAPE_CA_DN_BUG: number; - const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; /** Instructs OpenSSL to disable support for SSL/TLS compression. */ const SSL_OP_NO_COMPRESSION: number; + /** 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; - const SSL_OP_PKCS1_CHECK_1: number; - const SSL_OP_PKCS1_CHECK_2: number; - /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ - const SSL_OP_SINGLE_DH_USE: number; - /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ - const SSL_OP_SINGLE_ECDH_USE: number; - const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - const SSL_OP_TLS_BLOCK_PADDING_BUG: number; - const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to 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; @@ -134,7 +158,6 @@ declare module 'crypto' { const DH_CHECK_P_NOT_PRIME: number; const DH_UNABLE_TO_CHECK_GENERATOR: number; const DH_NOT_SUITABLE_GENERATOR: number; - const ALPN_ENABLED: number; const RSA_PKCS1_PADDING: number; const RSA_SSLV23_PADDING: number; const RSA_NO_PADDING: number; @@ -172,19 +195,19 @@ declare module 'crypto' { * * 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`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will * display the available digest algorithms. * * Example: generating the sha256 sum of a file * * ```js * import { - * createReadStream - * } from 'fs'; - * import { argv } from 'process'; + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const filename = argv[2]; * @@ -212,22 +235,24 @@ declare module 'crypto' { * * 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`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * 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`. + * 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 'fs'; - * import { argv } from 'process'; + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const filename = argv[2]; * @@ -250,11 +275,11 @@ declare module 'crypto' { */ 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'; - type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1'; - type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2'; + 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'; + 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: @@ -270,8 +295,8 @@ declare module 'crypto' { * * ```js * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -293,9 +318,9 @@ declare module 'crypto' { * Example: Using `Hash` and piped streams: * * ```js - * import { createReadStream } from 'fs'; - * import { stdout } from 'process'; - * const { createHash } = await import('crypto'); + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -307,8 +332,8 @@ declare module 'crypto' { * * ```js * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -335,8 +360,8 @@ declare module 'crypto' { * ```js * // Calculate a rolling hash. * const { - * createHash - * } = await import('crypto'); + * createHash, + * } = await import('node:crypto'); * * const hash = createHash('sha256'); * @@ -354,7 +379,7 @@ declare module 'crypto' { * @since v13.1.0 * @param options `stream.transform` options */ - copy(options?: stream.TransformOptions): Hash; + copy(options?: HashOptions): Hash; /** * Updates the hash content with the given `data`, the encoding of which * is given in `inputEncoding`. @@ -395,8 +420,8 @@ declare module 'crypto' { * * ```js * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const hmac = createHmac('sha256', 'a secret'); * @@ -418,11 +443,11 @@ declare module 'crypto' { * Example: Using `Hmac` and piped streams: * * ```js - * import { createReadStream } from 'fs'; - * import { stdout } from 'process'; + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const hmac = createHmac('sha256', 'a secret'); * @@ -434,8 +459,8 @@ declare module 'crypto' { * * ```js * const { - * createHmac - * } = await import('crypto'); + * createHmac, + * } = await import('node:crypto'); * * const hmac = createHmac('sha256', 'a secret'); * @@ -445,6 +470,7 @@ declare module 'crypto' { * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e * ``` * @since v0.1.94 + * @deprecated Since v20.13.0 Calling `Hmac` class directly with `Hmac()` or `new Hmac()` is deprecated due to being internals, not intended for public use. Please use the {@link createHmac} method to create Hmac instances. */ class Hmac extends stream.Transform { private constructor(); @@ -473,15 +499,15 @@ declare module 'crypto' { digest(): Buffer; digest(encoding: BinaryToTextEncoding): string; } - type KeyObjectType = 'secret' | 'public' | 'private'; + type KeyObjectType = "secret" | "public" | "private"; interface KeyExportOptions { - type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; format: T; cipher?: string | undefined; passphrase?: string | Buffer | undefined; } interface JwkKeyExportOptions { - format: 'jwk'; + format: "jwk"; } interface JsonWebKey { crv?: string | undefined; @@ -548,13 +574,13 @@ declare module 'crypto' { * Example: Converting a `CryptoKey` instance to a `KeyObject`: * * ```js - * const { webcrypto, KeyObject } = await import('crypto'); - * const { subtle } = webcrypto; + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; * * const key = await subtle.generateKey({ * name: 'HMAC', * hash: 'SHA-256', - * length: 256 + * length: 256, * }, true, ['sign', 'verify']); * * const keyObject = KeyObject.from(key); @@ -625,9 +651,16 @@ declare module 'crypto' { * PKCS#1 and SEC1 encryption. * @since v11.6.0 */ - export(options: KeyExportOptions<'pem'>): string | Buffer; - export(options?: KeyExportOptions<'der'>): Buffer; + 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. @@ -641,9 +674,9 @@ declare module 'crypto' { */ 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 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 { @@ -656,28 +689,33 @@ declare module 'crypto' { authTagLength: number; } /** - * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * 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 is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * 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`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * 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/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * 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/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * 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 @@ -697,12 +735,13 @@ declare module 'crypto' { * initialization vector (`iv`). * * The `options` argument controls stream behavior and is optional except when a - * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * 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`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * 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 @@ -721,10 +760,30 @@ declare module 'crypto' { * @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; + 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: @@ -744,8 +803,8 @@ declare module 'crypto' { * const { * scrypt, * randomFill, - * createCipheriv - * } = await import('crypto'); + * createCipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -779,17 +838,17 @@ declare module 'crypto' { * import { * createReadStream, * createWriteStream, - * } from 'fs'; + * } from 'node:fs'; * * import { - * pipeline - * } from 'stream'; + * pipeline, + * } from 'node:stream'; * * const { * scrypt, * randomFill, - * createCipheriv - * } = await import('crypto'); + * createCipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -820,8 +879,8 @@ declare module 'crypto' { * const { * scrypt, * randomFill, - * createCipheriv - * } = await import('crypto'); + * createCipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -848,8 +907,8 @@ declare module 'crypto' { 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 `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. @@ -896,7 +955,7 @@ declare module 'crypto' { buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number; - } + }, ): this; getAuthTag(): Buffer; } @@ -905,7 +964,7 @@ declare module 'crypto' { buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number; - } + }, ): this; getAuthTag(): Buffer; } @@ -914,25 +973,30 @@ declare module 'crypto' { buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number; - } + }, ): this; getAuthTag(): Buffer; } /** - * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * 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 is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * 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/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * 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/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * 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 @@ -945,15 +1009,16 @@ declare module 'crypto' { /** @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`). + * 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 is used (e.g. `'aes-128-ccm'`). 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 + * 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`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * 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 @@ -972,10 +1037,30 @@ declare module 'crypto' { * @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; + 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: @@ -992,11 +1077,11 @@ declare module 'crypto' { * Example: Using `Decipher` objects as streams: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { * scryptSync, - * createDecipheriv - * } = await import('crypto'); + * createDecipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -1011,6 +1096,7 @@ declare module 'crypto' { * * let decrypted = ''; * decipher.on('readable', () => { + * let chunk; * while (null !== (chunk = decipher.read())) { * decrypted += chunk.toString('utf8'); * } @@ -1033,12 +1119,12 @@ declare module 'crypto' { * import { * createReadStream, * createWriteStream, - * } from 'fs'; - * import { Buffer } from 'buffer'; + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; * const { * scryptSync, - * createDecipheriv - * } = await import('crypto'); + * createDecipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -1058,11 +1144,11 @@ declare module 'crypto' { * Example: Using the `decipher.update()` and `decipher.final()` methods: * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { * scryptSync, - * createDecipheriv - * } = await import('crypto'); + * createDecipheriv, + * } = await import('node:crypto'); * * const algorithm = 'aes-192-cbc'; * const password = 'Password used to generate key'; @@ -1087,11 +1173,11 @@ declare module 'crypto' { 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 + * 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. + * 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. @@ -1114,7 +1200,7 @@ declare module 'crypto' { 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 + * 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 @@ -1133,7 +1219,7 @@ declare module 'crypto' { buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number; - } + }, ): this; } interface DecipherGCM extends Decipher { @@ -1142,7 +1228,7 @@ declare module 'crypto' { buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number; - } + }, ): this; } interface DecipherOCB extends Decipher { @@ -1151,70 +1237,78 @@ declare module 'crypto' { buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number; - } + }, ): this; } interface PrivateKeyInput { key: string | Buffer; format?: KeyFormat | undefined; - type?: 'pkcs1' | 'pkcs8' | 'sec1' | 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; + 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`. + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. * * ```js * const { - * generateKey - * } = await import('crypto'); + * generateKey, + * } = await import('node:crypto'); * - * generateKey('hmac', { length: 64 }, (err, key) => { + * 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', + type: "hmac" | "aes", options: { length: number; }, - callback: (err: Error | null, key: KeyObject) => void + 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`. + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. * * ```js * const { - * generateKeySync - * } = await import('crypto'); + * generateKeySync, + * } = await import('node:crypto'); * - * const key = generateKeySync('hmac', { length: 64 }); + * 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', + type: "hmac" | "aes", options: { length: number; - } + }, ): KeyObject; interface JsonWebKeyInput { key: JsonWebKey; - format: 'jwk'; + 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. + * 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. @@ -1223,7 +1317,7 @@ declare module 'crypto' { 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; + * 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. @@ -1231,7 +1325,7 @@ declare module 'crypto' { * 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 + * 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 */ @@ -1257,10 +1351,10 @@ declare module 'crypto' { * @param options `stream.Writable` options */ function createSign(algorithm: string, options?: stream.WritableOptions): Sign; - type DSAEncoding = 'der' | 'ieee-p1363'; + type DSAEncoding = "der" | "ieee-p1363"; interface SigningOptions { /** - * @See crypto.constants.RSA_PKCS1_PADDING + * @see crypto.constants.RSA_PKCS1_PADDING */ padding?: number | undefined; saltLength?: number | undefined; @@ -1270,10 +1364,12 @@ declare module 'crypto' { interface SignKeyObjectInput extends SigningOptions { key: KeyObject; } + interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} 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 @@ -1293,11 +1389,11 @@ declare module 'crypto' { * const { * generateKeyPairSync, * createSign, - * createVerify - * } = await import('crypto'); + * createVerify, + * } = await import('node:crypto'); * * const { privateKey, publicKey } = generateKeyPairSync('ec', { - * namedCurve: 'sect239k1' + * namedCurve: 'sect239k1', * }); * * const sign = createSign('SHA256'); @@ -1318,8 +1414,8 @@ declare module 'crypto' { * const { * generateKeyPairSync, * createSign, - * createVerify - * } = await import('crypto'); + * createVerify, + * } = await import('node:crypto'); * * const { privateKey, publicKey } = generateKeyPairSync('rsa', { * modulusLength: 2048, @@ -1355,7 +1451,7 @@ declare module 'crypto' { /** * 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 + * 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. @@ -1364,13 +1460,16 @@ declare module 'crypto' { * 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; + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + 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. + * 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 @@ -1390,7 +1489,7 @@ declare module 'crypto' { * * 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. + * 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 @@ -1401,7 +1500,7 @@ declare module 'crypto' { * 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. + * 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 @@ -1412,13 +1511,13 @@ declare module 'crypto' { /** * 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 + * 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`. + * 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 @@ -1428,14 +1527,21 @@ declare module 'crypto' { * be passed instead of a public key. * @since v0.1.92 */ - verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; - verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; + 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. + * 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. @@ -1447,11 +1553,27 @@ declare module 'crypto' { * @param [generator=2] * @param generatorEncoding The `encoding` of the `generator` string. */ - function createDiffieHellman(primeLength: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; - function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; - function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding): DiffieHellman; - function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman; - function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman; + 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. @@ -1459,11 +1581,11 @@ declare module 'crypto' { * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * const { - * createDiffieHellman - * } = await import('crypto'); + * createDiffieHellman, + * } = await import('node:crypto'); * * // Generate Alice's keys... * const alice = createDiffieHellman(2048); @@ -1485,10 +1607,15 @@ declare module 'crypto' { class DiffieHellman { private constructor(); /** - * Generates private and public Diffie-Hellman key values, and returns + * 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. */ @@ -1500,7 +1627,7 @@ declare module 'crypto' { * 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`. + * 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 @@ -1509,8 +1636,16 @@ declare module 'crypto' { */ 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; + 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 @@ -1548,7 +1683,7 @@ declare module 'crypto' { getPrivateKey(): Buffer; getPrivateKey(encoding: BinaryToTextEncoding): string; /** - * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * 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 @@ -1560,6 +1695,9 @@ declare module 'crypto' { * 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. */ @@ -1569,7 +1707,7 @@ declare module 'crypto' { * A bit field containing any warnings and/or errors resulting from a check * performed during initialization of the `DiffieHellman` object. * - * The following values are valid for this property (as defined in `constants`module): + * 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` @@ -1608,12 +1746,12 @@ declare module 'crypto' { (name: string): DiffieHellmanGroup; readonly prototype: DiffieHellmanGroup; } - type DiffieHellmanGroup = Omit; + type DiffieHellmanGroup = Omit; /** * Creates a predefined `DiffieHellmanGroup` key exchange object. The - * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, - * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The - * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * 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 @@ -1623,8 +1761,8 @@ declare module 'crypto' { * * ```js * const { - * getDiffieHellman - * } = await import('crypto'); + * getDiffieHellman, + * } = await import('node:crypto'); * const alice = getDiffieHellman('modp14'); * const bob = getDiffieHellman('modp14'); * @@ -1648,15 +1786,12 @@ declare module 'crypto' { /** * 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`. + * 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 + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be * thrown if any of the input arguments specify invalid values or types. * - * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, - * please specify a `digest` explicitly. - * * The `iterations` argument must be a number set as high as possible. The * higher the number of iterations, the more secure the derived key will be, * but will take a longer amount of time to complete. @@ -1668,8 +1803,8 @@ declare module 'crypto' { * * ```js * const { - * pbkdf2 - * } = await import('crypto'); + * pbkdf2, + * } = await import('node:crypto'); * * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { * if (err) throw err; @@ -1677,36 +1812,28 @@ declare module 'crypto' { * }); * ``` * - * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been - * deprecated and use should be avoided. - * - * ```js - * import crypto from 'crypto'; - * crypto.DEFAULT_ENCODING = 'hex'; - * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { - * if (err) throw err; - * console.log(derivedKey); // '3745e48...aa39b34' - * }); - * ``` - * * An array of supported digest functions can be retrieved using {@link getHashes}. * * This API uses libuv's threadpool, which can have surprising and * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. * @since v0.5.5 */ - function pbkdf2(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => void): void; + 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`. + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. * * If an error occurs an `Error` will be thrown, otherwise the derived key will be * returned as a `Buffer`. * - * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, - * please specify a `digest` explicitly. - * * The `iterations` argument must be a number set as high as possible. The * higher the number of iterations, the more secure the derived key will be, * but will take a longer amount of time to complete. @@ -1718,40 +1845,36 @@ declare module 'crypto' { * * ```js * const { - * pbkdf2Sync - * } = await import('crypto'); + * pbkdf2Sync, + * } = await import('node:crypto'); * * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); * console.log(key.toString('hex')); // '3745e48...08d59ae' * ``` * - * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use - * should be avoided. - * - * ```js - * import crypto from 'crypto'; - * crypto.DEFAULT_ENCODING = 'hex'; - * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); - * console.log(key); // '3745e48...aa39b34' - * ``` - * * An array of supported digest functions can be retrieved using {@link getHashes}. * @since v0.9.3 */ - function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; + 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. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. * * ```js * // Asynchronous * const { - * randomBytes - * } = await import('crypto'); + * randomBytes, + * } = await import('node:crypto'); * * randomBytes(256, (err, buf) => { * if (err) throw err; @@ -1766,8 +1889,8 @@ declare module 'crypto' { * ```js * // Synchronous * const { - * randomBytes - * } = await import('crypto'); + * randomBytes, + * } = await import('node:crypto'); * * const buf = randomBytes(256); * console.log( @@ -1799,7 +1922,7 @@ declare module 'crypto' { * 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 248. `min` and `max` must + * 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 @@ -1808,8 +1931,8 @@ declare module 'crypto' { * ```js * // Asynchronous * const { - * randomInt - * } = await import('crypto'); + * randomInt, + * } = await import('node:crypto'); * * randomInt(3, (err, n) => { * if (err) throw err; @@ -1820,8 +1943,8 @@ declare module 'crypto' { * ```js * // Synchronous * const { - * randomInt - * } = await import('crypto'); + * randomInt, + * } = await import('node:crypto'); * * const n = randomInt(3); * console.log(`Random number chosen from (0, 1, 2): ${n}`); @@ -1830,8 +1953,8 @@ declare module 'crypto' { * ```js * // With `min` argument * const { - * randomInt - * } = await import('crypto'); + * randomInt, + * } = await import('node:crypto'); * * const n = randomInt(1, 7); * console.log(`The dice rolled: ${n}`); @@ -1849,8 +1972,8 @@ declare module 'crypto' { * Synchronous version of {@link randomFill}. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFillSync } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); * * const buf = Buffer.alloc(10); * console.log(randomFillSync(buf).toString('hex')); @@ -1866,8 +1989,8 @@ declare module 'crypto' { * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFillSync } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); * * const a = new Uint32Array(10); * console.log(Buffer.from(randomFillSync(a).buffer, @@ -1895,8 +2018,8 @@ declare module 'crypto' { * If the `callback` function is not provided, an error will be thrown. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFill } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); * * const buf = Buffer.alloc(10); * randomFill(buf, (err, buf) => { @@ -1916,7 +2039,7 @@ declare module 'crypto' { * }); * ``` * - * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * 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 @@ -1925,8 +2048,8 @@ declare module 'crypto' { * distribution and have no meaningful lower or upper bounds. * * ```js - * import { Buffer } from 'buffer'; - * const { randomFill } = await import('crypto'); + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); * * const a = new Uint32Array(10); * randomFill(a, (err, buf) => { @@ -1962,9 +2085,21 @@ declare module 'crypto' { * @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; + 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; @@ -1984,7 +2119,7 @@ declare module 'crypto' { * * 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 + * 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 @@ -1992,8 +2127,8 @@ declare module 'crypto' { * * ```js * const { - * scrypt - * } = await import('crypto'); + * scrypt, + * } = await import('node:crypto'); * * // Using the factory defaults. * scrypt('password', 'salt', 64, (err, derivedKey) => { @@ -2008,8 +2143,19 @@ declare module 'crypto' { * ``` * @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; + 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 @@ -2028,8 +2174,8 @@ declare module 'crypto' { * * ```js * const { - * scryptSync - * } = await import('crypto'); + * scryptSync, + * } = await import('node:crypto'); * // Using the factory defaults. * * const key1 = scryptSync('password', 'salt', 64); @@ -2059,8 +2205,8 @@ declare module 'crypto' { * 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`. + * 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. @@ -2071,8 +2217,8 @@ declare module 'crypto' { * 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`. + * 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. @@ -2083,8 +2229,8 @@ declare module 'crypto' { * 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`. + * 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; @@ -2092,16 +2238,16 @@ declare module 'crypto' { * 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`. + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. * @since v1.1.0 */ function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; /** * ```js * const { - * getCiphers - * } = await import('crypto'); + * getCiphers, + * } = await import('node:crypto'); * * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] * ``` @@ -2112,8 +2258,8 @@ declare module 'crypto' { /** * ```js * const { - * getCurves - * } = await import('crypto'); + * getCurves, + * } = await import('node:crypto'); * * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] * ``` @@ -2127,7 +2273,8 @@ declare module 'crypto' { */ 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. + * 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. */ @@ -2135,8 +2282,8 @@ declare module 'crypto' { /** * ```js * const { - * getHashes - * } = await import('crypto'); + * getHashes, + * } = await import('node:crypto'); * * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] * ``` @@ -2151,11 +2298,11 @@ declare module 'crypto' { * Instances of the `ECDH` class can be created using the {@link createECDH} function. * * ```js - * import assert from 'assert'; + * import assert from 'node:assert'; * * const { - * createECDH - * } = await import('crypto'); + * createECDH, + * } = await import('node:crypto'); * * // Generate Alice's keys... * const alice = createECDH('secp521r1'); @@ -2187,17 +2334,17 @@ declare module 'crypto' { * 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 `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`. + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. * * Example (uncompressing a key): * * ```js * const { * createECDH, - * ECDH - * } = await import('crypto'); + * ECDH, + * } = await import('node:crypto'); * * const ecdh = createECDH('secp256k1'); * ecdh.generateKeys(); @@ -2222,15 +2369,15 @@ declare module 'crypto' { key: BinaryLike, curve: string, inputEncoding?: BinaryToTextEncoding, - outputEncoding?: 'latin1' | 'hex' | 'base64' | 'base64url', - format?: 'uncompressed' | 'compressed' | 'hybrid' + 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. + * 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 @@ -2245,11 +2392,11 @@ declare module 'crypto' { * 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`. + * 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 + * `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 @@ -2259,7 +2406,11 @@ declare module 'crypto' { 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; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; /** * If `encoding` is specified, a string is returned; otherwise a `Buffer` is * returned. @@ -2270,7 +2421,7 @@ declare module 'crypto' { 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. + * 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. @@ -2279,12 +2430,12 @@ declare module 'crypto' { * @param [format='uncompressed'] * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. */ - getPublicKey(): Buffer; + 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`. + * 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 @@ -2304,28 +2455,33 @@ declare module 'crypto' { */ function createECDH(curveName: string): ECDH; /** - * This function is based on a constant-time algorithm. - * Returns true if `a` is equal to `b`, without leaking timing information that + * 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. + * 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; - /** @deprecated since v10.0.0 */ - const DEFAULT_ENCODING: BufferEncoding; - type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; - type KeyFormat = 'pem' | 'der'; + type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; interface BasePrivateKeyEncodingOptions { format: T; cipher?: string | undefined; @@ -2344,6 +2500,10 @@ declare module 'crypto' { * Name of the curve to use */ namedCurve: string; + /** + * Must be `'named'` or `'explicit'`. Default: `'named'`. + */ + paramEncoding?: "explicit" | "named" | undefined; } interface RSAKeyPairKeyObjectOptions { /** @@ -2400,11 +2560,11 @@ declare module 'crypto' { */ publicExponent?: number | undefined; publicKeyEncoding: { - type: 'pkcs1' | 'spki'; + type: "pkcs1" | "spki"; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs1' | 'pkcs8'; + type: "pkcs1" | "pkcs8"; }; } interface RSAPSSKeyPairOptions { @@ -2430,11 +2590,11 @@ declare module 'crypto' { */ saltLength?: string; publicKeyEncoding: { - type: 'spki'; + type: "spki"; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; + type: "pkcs8"; }; } interface DSAKeyPairOptions { @@ -2447,60 +2607,56 @@ declare module 'crypto' { */ divisorLength: number; publicKeyEncoding: { - type: 'spki'; + type: "spki"; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; + type: "pkcs8"; }; } - interface ECKeyPairOptions { - /** - * Name of the curve to use. - */ - namedCurve: string; + interface ECKeyPairOptions extends ECKeyPairKeyObjectOptions { publicKeyEncoding: { - type: 'pkcs1' | 'spki'; + type: "pkcs1" | "spki"; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'sec1' | 'pkcs8'; + type: "sec1" | "pkcs8"; }; } interface ED25519KeyPairOptions { publicKeyEncoding: { - type: 'spki'; + type: "spki"; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; + type: "pkcs8"; }; } interface ED448KeyPairOptions { publicKeyEncoding: { - type: 'spki'; + type: "spki"; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; + type: "pkcs8"; }; } interface X25519KeyPairOptions { publicKeyEncoding: { - type: 'spki'; + type: "spki"; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; + type: "pkcs8"; }; } interface X448KeyPairOptions { publicKeyEncoding: { - type: 'spki'; + type: "spki"; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; + type: "pkcs8"; }; } interface KeyPairSyncResult { @@ -2521,8 +2677,8 @@ declare module 'crypto' { * * ```js * const { - * generateKeyPairSync - * } = await import('crypto'); + * generateKeyPairSync, + * } = await import('node:crypto'); * * const { * publicKey, @@ -2531,14 +2687,14 @@ declare module 'crypto' { * modulusLength: 4096, * publicKeyEncoding: { * type: 'spki', - * format: 'pem' + * format: 'pem', * }, * privateKeyEncoding: { * type: 'pkcs8', * format: 'pem', * cipher: 'aes-256-cbc', - * passphrase: 'top secret' - * } + * passphrase: 'top secret', + * }, * }); * ``` * @@ -2548,46 +2704,142 @@ declare module 'crypto' { * @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; + 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. @@ -2596,310 +2848,479 @@ declare module 'crypto' { * 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: + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: * * ```js * const { - * generateKeyPair - * } = await import('crypto'); + * generateKeyPair, + * } = await import('node:crypto'); * * generateKeyPair('rsa', { * modulusLength: 4096, * publicKeyEncoding: { * type: 'spki', - * format: 'pem' + * format: 'pem', * }, * privateKeyEncoding: { * type: 'pkcs8', * format: 'pem', * cipher: 'aes-256-cbc', - * passphrase: 'top secret' - * } + * 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. + * 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; + 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'> + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, ): Promise<{ publicKey: string; privateKey: string; }>; function __promisify__( - type: 'rsa', - options: RSAKeyPairOptions<'pem', 'der'> + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, ): Promise<{ publicKey: string; privateKey: Buffer; }>; function __promisify__( - type: 'rsa', - options: RSAKeyPairOptions<'der', 'pem'> + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, ): Promise<{ publicKey: Buffer; privateKey: string; }>; function __promisify__( - type: 'rsa', - options: RSAKeyPairOptions<'der', 'der'> + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, ): Promise<{ publicKey: Buffer; privateKey: Buffer; }>; - function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; function __promisify__( - type: 'rsa-pss', - options: RSAPSSKeyPairOptions<'pem', 'pem'> + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, ): Promise<{ publicKey: string; privateKey: string; }>; function __promisify__( - type: 'rsa-pss', - options: RSAPSSKeyPairOptions<'pem', 'der'> + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, ): Promise<{ publicKey: string; privateKey: Buffer; }>; function __promisify__( - type: 'rsa-pss', - options: RSAPSSKeyPairOptions<'der', 'pem'> + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, ): Promise<{ publicKey: Buffer; privateKey: string; }>; function __promisify__( - type: 'rsa-pss', - options: RSAPSSKeyPairOptions<'der', 'der'> + 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'> + 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'> + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, ): Promise<{ publicKey: string; privateKey: Buffer; }>; function __promisify__( - type: 'dsa', - options: DSAKeyPairOptions<'der', 'pem'> + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, ): Promise<{ publicKey: Buffer; privateKey: string; }>; function __promisify__( - type: 'dsa', - options: DSAKeyPairOptions<'der', 'der'> + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, ): Promise<{ publicKey: Buffer; privateKey: Buffer; }>; - function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; function __promisify__( - type: 'ec', - options: ECKeyPairOptions<'pem', 'pem'> + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, ): Promise<{ publicKey: string; privateKey: string; }>; function __promisify__( - type: 'ec', - options: ECKeyPairOptions<'pem', 'der'> + type: "ec", + options: ECKeyPairOptions<"pem", "der">, ): Promise<{ publicKey: string; privateKey: Buffer; }>; function __promisify__( - type: 'ec', - options: ECKeyPairOptions<'der', 'pem'> + type: "ec", + options: ECKeyPairOptions<"der", "pem">, ): Promise<{ publicKey: Buffer; privateKey: string; }>; function __promisify__( - type: 'ec', - options: ECKeyPairOptions<'der', 'der'> + type: "ec", + options: ECKeyPairOptions<"der", "der">, ): Promise<{ publicKey: Buffer; privateKey: Buffer; }>; - function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; function __promisify__( - type: 'ed25519', - options: ED25519KeyPairOptions<'pem', 'pem'> + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, ): Promise<{ publicKey: string; privateKey: string; }>; function __promisify__( - type: 'ed25519', - options: ED25519KeyPairOptions<'pem', 'der'> + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, ): Promise<{ publicKey: string; privateKey: Buffer; }>; function __promisify__( - type: 'ed25519', - options: ED25519KeyPairOptions<'der', 'pem'> + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, ): Promise<{ publicKey: Buffer; privateKey: string; }>; function __promisify__( - type: 'ed25519', - options: ED25519KeyPairOptions<'der', 'der'> + 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'> + 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'> + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, ): Promise<{ publicKey: string; privateKey: Buffer; }>; function __promisify__( - type: 'ed448', - options: ED448KeyPairOptions<'der', 'pem'> + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, ): Promise<{ publicKey: Buffer; privateKey: string; }>; function __promisify__( - type: 'ed448', - options: ED448KeyPairOptions<'der', 'der'> + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, ): Promise<{ publicKey: Buffer; privateKey: Buffer; }>; - function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; function __promisify__( - type: 'x25519', - options: X25519KeyPairOptions<'pem', 'pem'> + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, ): Promise<{ publicKey: string; privateKey: string; }>; function __promisify__( - type: 'x25519', - options: X25519KeyPairOptions<'pem', 'der'> + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, ): Promise<{ publicKey: string; privateKey: Buffer; }>; function __promisify__( - type: 'x25519', - options: X25519KeyPairOptions<'der', 'pem'> + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, ): Promise<{ publicKey: Buffer; privateKey: string; }>; function __promisify__( - type: 'x25519', - options: X25519KeyPairOptions<'der', 'der'> + 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'> + 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'> + type: "x448", + options: X448KeyPairOptions<"pem", "der">, ): Promise<{ publicKey: string; privateKey: Buffer; }>; function __promisify__( - type: 'x448', - options: X448KeyPairOptions<'der', 'pem'> + type: "x448", + options: X448KeyPairOptions<"der", "pem">, ): Promise<{ publicKey: Buffer; privateKey: string; }>; function __promisify__( - type: 'x448', - options: X448KeyPairOptions<'der', 'der'> + type: "x448", + options: X448KeyPairOptions<"der", "der">, ): Promise<{ publicKey: Buffer; privateKey: Buffer; }>; - function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; } /** * Calculates and returns the signature for `data` using the given private key and @@ -2913,15 +3334,19 @@ declare module 'crypto' { * 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 + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + 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 + * 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 @@ -2936,21 +3361,61 @@ declare module 'crypto' { * 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, signature: NodeJS.ArrayBufferView): boolean; function verify( algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, - key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, signature: NodeJS.ArrayBufferView, - callback: (error: Error | null, result: boolean) => void + ): 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). + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` (for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). * @since v13.9.0, v12.17.0 */ function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; - type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts'; + /** + * 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. @@ -3002,18 +3467,18 @@ declare module 'crypto' { */ 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. + * 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; + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; * otherwise `err` will be `null`. The successfully generated `derivedKey` will * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any * of the input arguments specify invalid values or types. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { - * hkdf - * } = await import('crypto'); + * hkdf, + * } = await import('node:crypto'); * * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { * if (err) throw err; @@ -3022,16 +3487,23 @@ declare module 'crypto' { * ``` * @since v15.0.0 * @param digest The digest algorithm to use. - * @param ikm The input keying material. It must be at least one byte in length. + * @param 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; + 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. + * 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). * @@ -3039,23 +3511,29 @@ declare module 'crypto' { * types, or if the derived key cannot be generated. * * ```js - * import { Buffer } from 'buffer'; + * import { Buffer } from 'node:buffer'; * const { - * hkdfSync - * } = await import('crypto'); + * 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. It must be at least one byte in length. + * @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; + 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. @@ -3089,40 +3567,41 @@ declare module 'crypto' { */ 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 + * @since v15.6.0, v14.17.0 */ - function randomUUID(options?: RandomUUIDOptions): string; + function randomUUID(options?: RandomUUIDOptions): UUID; interface X509CheckOptions { /** * @default 'always' */ - subject: 'always' | 'never'; + subject?: "always" | "default" | "never"; /** * @default true */ - wildcards: boolean; + wildcards?: boolean; /** * @default true */ - partialWildcards: boolean; + partialWildcards?: boolean; /** * @default false */ - multiLabelWildcards: boolean; + multiLabelWildcards?: boolean; /** * @default false */ - singleLabelSubdomains: boolean; + singleLabelSubdomains?: boolean; } /** * Encapsulates an X509 certificate and provides read-only access to * its information. * * ```js - * const { X509Certificate } = await import('crypto'); + * const { X509Certificate } = await import('node:crypto'); * * const x509 = new X509Certificate('{... pem encoded cert ...}'); * @@ -3132,12 +3611,16 @@ declare module 'crypto' { */ class X509Certificate { /** - * Will be \`true\` if this is a Certificate Authority (ca) certificate. + * 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; @@ -3148,23 +3631,53 @@ declare module 'crypto' { readonly fingerprint256: string; /** * The SHA-512 fingerprint of this certificate. - * @since v16.14.0 + * + * 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; + readonly fingerprint512: string; /** * The complete subject of this certificate. * @since v15.6.0 */ readonly subject: string; /** - * The subject alternative name specified for this certificate or `undefined` - * if not available. + * 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; /** - * The information access content of this certificate or `undefined` if not - * available. + * 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; @@ -3196,6 +3709,10 @@ declare module 'crypto' { 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; @@ -3212,18 +3729,50 @@ declare module 'crypto' { 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; + 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 `name` if the certificate matches, `undefined` if it does not. + * @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. */ @@ -3283,7 +3832,7 @@ declare module 'crypto' { /** * 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. + * 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: @@ -3299,7 +3848,7 @@ declare module 'crypto' { * * `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`. + * 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 @@ -3308,13 +3857,25 @@ declare module 'crypto' { * @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; + 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. + * 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: @@ -3330,7 +3891,7 @@ declare module 'crypto' { * * `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`. + * 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 @@ -3345,7 +3906,7 @@ declare module 'crypto' { 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. + * 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. * @@ -3359,7 +3920,11 @@ declare module 'crypto' { * @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; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; /** * Checks the primality of the `candidate`. * @since v15.8.0 @@ -3372,30 +3937,36 @@ declare module 'crypto' { * * `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`): + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): * - * - `crypto.constants.ENGINE_METHOD_RSA` - * - `crypto.constants.ENGINE_METHOD_DSA` - * - `crypto.constants.ENGINE_METHOD_DH` - * - `crypto.constants.ENGINE_METHOD_RAND` - * - `crypto.constants.ENGINE_METHOD_EC` - * - `crypto.constants.ENGINE_METHOD_CIPHERS` - * - `crypto.constants.ENGINE_METHOD_DIGESTS` - * - `crypto.constants.ENGINE_METHOD_PKEY_METHS` - * - `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` - * - `crypto.constants.ENGINE_METHOD_ALL` - * - `crypto.constants.ENGINE_METHOD_NONE` - * - * The flags below are deprecated in OpenSSL-1.1.0. - * - * - `crypto.constants.ENGINE_METHOD_ECDH` - * - `crypto.constants.ENGINE_METHOD_ECDSA` - * - `crypto.constants.ENGINE_METHOD_STORE` + * * `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=crypto.constants.ENGINE_METHOD_ALL] + * @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. * @@ -3405,9 +3976,17 @@ declare module 'crypto' { 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 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; @@ -3553,7 +4132,7 @@ declare module 'crypto' { * The UUID is generated using a cryptographic pseudorandom number generator. * @since v16.7.0 */ - randomUUID(): string; + randomUUID(): UUID; CryptoKey: CryptoKeyConstructor; } // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. @@ -3561,7 +4140,7 @@ declare module 'crypto' { /** Illegal constructor */ (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. readonly length: 0; - readonly name: 'CryptoKey'; + readonly name: "CryptoKey"; readonly prototype: CryptoKey; } /** @@ -3634,21 +4213,34 @@ declare module 'crypto' { * - `'AES-GCM'` * @since v15.0.0 */ - decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + 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 `length` is a multiple of `8`. + * 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: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; + 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`. @@ -3659,6 +4251,8 @@ declare module 'crypto' { * 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}. @@ -3667,9 +4261,14 @@ declare module 'crypto' { deriveKey( algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, - derivedKeyAlgorithm: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, + derivedKeyAlgorithm: + | AlgorithmIdentifier + | AesDerivedKeyParams + | HmacImportParams + | HkdfParams + | Pbkdf2Params, extractable: boolean, - keyUsages: ReadonlyArray + keyUsages: readonly KeyUsage[], ): Promise; /** * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. @@ -3699,7 +4298,11 @@ declare module 'crypto' { * - `'AES-GCM'` * @since v15.0.0 */ - encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; /** * Exports the given key into the specified format, if supported. * @@ -3714,8 +4317,8 @@ declare module 'crypto' { * @returns `` containing ``. * @since v15.0.0 */ - exportKey(format: 'jwk', key: CryptoKey): Promise; - exportKey(format: Exclude, key: CryptoKey): Promise; + 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. @@ -3727,7 +4330,11 @@ declare module 'crypto' { * - `'RSA-PSS'` * - `'RSA-OAEP'` * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` * - `'ECDH'` + * - `'X25519'` + * - `'X448'` * The `` (secret key) generating algorithms supported include: * * - `'HMAC'` @@ -3738,9 +4345,21 @@ declare module 'crypto' { * @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: ReadonlyArray): Promise; - generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray): Promise; - generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise; + 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. @@ -3752,18 +4371,28 @@ declare module 'crypto' { * @since v15.0.0 */ importKey( - format: 'jwk', + format: "jwk", keyData: JsonWebKey, - algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, extractable: boolean, - keyUsages: ReadonlyArray + keyUsages: readonly KeyUsage[], ): Promise; importKey( - format: Exclude, + format: Exclude, keyData: BufferSource, - algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, extractable: boolean, - keyUsages: KeyUsage[] + keyUsages: KeyUsage[], ): Promise; /** * Using the method and parameters given by `algorithm` and the keying material provided by `key`, @@ -3775,10 +4404,16 @@ declare module 'crypto' { * - `'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; + 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. @@ -3800,7 +4435,11 @@ declare module 'crypto' { * - `'RSA-PSS'` * - `'RSA-OAEP'` * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` * - `'ECDH'` + * - `'X25519'` + * - `'X448'` * - `'HMAC'` * - `'AES-CTR'` * - `'AES-CBC'` @@ -3815,9 +4454,14 @@ declare module 'crypto' { wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, - unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, extractable: boolean, - keyUsages: KeyUsage[] + keyUsages: KeyUsage[], ): Promise; /** * Using the method and parameters given in `algorithm` and the keying material provided by `key`, @@ -3829,10 +4473,17 @@ declare module 'crypto' { * - `'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; + 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`, @@ -3851,10 +4502,23 @@ declare module 'crypto' { * @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; + 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'; +declare module "node:crypto" { + export * from "crypto"; } diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/dgram.d.ts old mode 100755 new mode 100644 similarity index 77% rename from node_modules/@types/node/dgram.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/dgram.d.ts index d7b9ee2..3843f23 --- a/node_modules/@types/node/dgram.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/dgram.d.ts @@ -1,13 +1,13 @@ /** - * The `dgram` module provides an implementation of UDP datagram sockets. + * The `node:dgram` module provides an implementation of UDP datagram sockets. * * ```js - * import dgram from 'dgram'; + * import dgram from 'node:dgram'; * * const server = dgram.createSocket('udp4'); * * server.on('error', (err) => { - * console.log(`server error:\n${err.stack}`); + * console.error(`server error:\n${err.stack}`); * server.close(); * }); * @@ -23,15 +23,15 @@ * server.bind(41234); * // Prints: server listening 0.0.0.0:41234 * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/dgram.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/dgram.js) */ -declare module 'dgram' { - import { AddressInfo } from 'node:net'; - import * as dns from 'node:dns'; - import { EventEmitter, Abortable } from 'node:events'; +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'; + family: "IPv4" | "IPv6"; port: number; size: number; } @@ -41,7 +41,7 @@ declare module 'dgram' { exclusive?: boolean | undefined; fd?: number | undefined; } - type SocketType = 'udp4' | 'udp6'; + type SocketType = "udp4" | "udp6"; interface SocketOptions extends Abortable { type: SocketType; reuseAddr?: boolean | undefined; @@ -51,7 +51,13 @@ declare module 'dgram' { 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; + 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 @@ -60,7 +66,7 @@ declare module 'dgram' { * (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: + * 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(); @@ -87,7 +93,7 @@ declare module 'dgram' { */ 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 + * 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. @@ -98,8 +104,8 @@ declare module 'dgram' { * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: * * ```js - * import cluster from 'cluster'; - * import dgram from 'dgram'; + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; * * if (cluster.isPrimary) { * cluster.fork(); // Works ok. @@ -116,7 +122,7 @@ declare module 'dgram' { 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. + * 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 @@ -127,10 +133,10 @@ declare module 'dgram' { * 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 + * 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 + * 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 @@ -142,12 +148,12 @@ declare module 'dgram' { * Example of a UDP server listening on port 41234: * * ```js - * import dgram from 'dgram'; + * import dgram from 'node:dgram'; * * const server = dgram.createSocket('udp4'); * * server.on('error', (err) => { - * console.log(`server error:\n${err.stack}`); + * console.error(`server error:\n${err.stack}`); * server.close(); * }); * @@ -200,7 +206,7 @@ declare module 'dgram' { */ 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 + * 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. * @@ -221,6 +227,16 @@ declare module 'dgram' { * @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 @@ -253,14 +269,14 @@ declare module 'dgram' { * 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 + * 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 falsy, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. + * 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 @@ -271,7 +287,7 @@ declare module 'dgram' { * 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 + * 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. * @@ -284,8 +300,8 @@ declare module 'dgram' { * Example of sending a UDP packet to a port on `localhost`; * * ```js - * import dgram from 'dgram'; - * import { Buffer } from 'buffer'; + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; * * const message = Buffer.from('Some bytes'); * const client = dgram.createSocket('udp4'); @@ -297,8 +313,8 @@ declare module 'dgram' { * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; * * ```js - * import dgram from 'dgram'; - * import { Buffer } from 'buffer'; + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('Some '); * const buf2 = Buffer.from('bytes'); @@ -313,11 +329,11 @@ declare module 'dgram' { * 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`: + * Example of sending a UDP packet using a socket connected to a port on `localhost`: * * ```js - * import dgram from 'dgram'; - * import { Buffer } from 'buffer'; + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; * * const message = Buffer.from('Some bytes'); * const client = dgram.createSocket('udp4'); @@ -335,12 +351,42 @@ declare module 'dgram' { * @param address Destination host name or IP address. * @param callback Called when the message has been sent. */ - send(msg: string | Uint8Array | ReadonlyArray, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: string | Uint8Array | ReadonlyArray, port?: number, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: string | Uint8Array | ReadonlyArray, 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; + 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. @@ -451,7 +497,7 @@ declare module 'dgram' { * 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 between 1 and 255\. The default on most systems + * 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. @@ -465,7 +511,7 @@ declare module 'dgram' { * process active, allowing the process to exit even if the socket is still * listening. * - * Calling `socket.unref()` multiple times will have no addition effect. + * 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. @@ -473,10 +519,10 @@ declare module 'dgram' { */ 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 + * 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. + * 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. @@ -484,7 +530,7 @@ declare module 'dgram' { */ 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 + * 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. @@ -503,43 +549,48 @@ declare module 'dgram' { * 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; + 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; + 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; + 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; + 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; + 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; + 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'; +declare module "node:dgram" { + export * from "dgram"; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..e25ca69 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,554 @@ +/** + * 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.13.1/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. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```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. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```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. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```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/.deno/@types+node@20.16.5/node_modules/@types/node/dns.d.ts old mode 100755 new mode 100644 similarity index 50% rename from node_modules/@types/node/dns.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/dns.d.ts index 78776f4..f5b6b74 --- a/node_modules/@types/node/dns.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/dns.d.ts @@ -1,5 +1,5 @@ /** - * The `dns` module enables name resolution. For example, use it to look up IP + * 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 @@ -9,7 +9,7 @@ * system do, use {@link lookup}. * * ```js - * const dns = require('dns'); + * const dns = require('node:dns'); * * dns.lookup('example.org', (err, address, family) => { * console.log('address: %j family: IPv%s', address, family); @@ -17,13 +17,13 @@ * // address: "93.184.216.34" family: IPv4 * ``` * - * All other functions in the `dns` module connect to an actual DNS server to + * 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('dns'); + * const dns = require('node:dns'); * * dns.resolve4('archive.org', (err, addresses) => { * if (err) throw err; @@ -41,13 +41,21 @@ * }); * ``` * - * See the `Implementation considerations section` for more information. - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/dns.js) + * 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.13.1/lib/dns.js) */ -declare module 'dns' { - import * as dnsPromises from 'node:dns/promises'; +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 @@ -55,9 +63,38 @@ declare module 'dns' { */ export const ALL: number; export interface LookupOptions { - family?: number | undefined; + /** + * 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 `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 + * addresses before IPv4 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 `verbatim` (addresses are not reordered) + */ + order?: "ipv4first" | "ipv6first" | "verbatim" | 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. This option will be deprecated in favor of `order`. When both are specified, + * `order` has higher precedence. New code should only use `order`. 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 { @@ -67,16 +104,23 @@ declare module 'dns' { 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 not provided, then IPv4 - * and IPv6 addresses are both returned if found. + * 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 + * 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. @@ -86,14 +130,15 @@ declare module 'dns' { * * `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 + * 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` before using`dns.lookup()`. + * 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('dns'); + * const dns = require('node:dns'); * const options = { * family: 6, * hints: dns.ADDRCONFIG | dns.V4MAPPED, @@ -109,14 +154,34 @@ declare module 'dns' { * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] * ``` * - * If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties. + * 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 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; @@ -127,26 +192,32 @@ declare module 'dns' { * 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. + * 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` object, where `err.code` is the error code. + * 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('dns'); + * 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()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. + * 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 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 + port: number, ): Promise<{ hostname: string; service: string; @@ -165,13 +236,13 @@ declare module 'dns' { /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; export interface AnyARecord extends RecordWithTtl { - type: 'A'; + type: "A"; } export interface AnyAaaaRecord extends RecordWithTtl { - type: 'AAAA'; + type: "AAAA"; } export interface CaaRecord { - critial: number; + critical: number; issue?: string | undefined; issuewild?: string | undefined; iodef?: string | undefined; @@ -183,7 +254,7 @@ declare module 'dns' { exchange: string; } export interface AnyMxRecord extends MxRecord { - type: 'MX'; + type: "MX"; } export interface NaptrRecord { flags: string; @@ -194,7 +265,7 @@ declare module 'dns' { preference: number; } export interface AnyNaptrRecord extends NaptrRecord { - type: 'NAPTR'; + type: "NAPTR"; } export interface SoaRecord { nsname: string; @@ -206,7 +277,7 @@ declare module 'dns' { minttl: number; } export interface AnySoaRecord extends SoaRecord { - type: 'SOA'; + type: "SOA"; } export interface SrvRecord { priority: number; @@ -215,122 +286,217 @@ declare module 'dns' { name: string; } export interface AnySrvRecord extends SrvRecord { - type: 'SRV'; + type: "SRV"; } export interface AnyTxtRecord { - type: 'TXT'; + type: "TXT"; entries: string[]; } export interface AnyNsRecord { - type: 'NS'; + type: "NS"; value: string; } export interface AnyPtrRecord { - type: 'PTR'; + type: "PTR"; value: string; } export interface AnyCnameRecord { - type: 'CNAME'; + type: "CNAME"; value: string; } - export type AnyRecord = AnyARecord | AnyAaaaRecord | AnyCnameRecord | AnyMxRecord | AnyNaptrRecord | AnyNsRecord | AnyPtrRecord | AnySoaRecord | AnySrvRecord | AnyTxtRecord; + 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 + * 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` object, where `err.code` is one of the `DNS error codes`. + * 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, + 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 + 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; + 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 + * 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 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 a IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * 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 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']`). + * 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 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 + * 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 + * @since v15.0.0, v14.17.0 */ - export function resolveCaa(hostname: string, callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void): void; + 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'}, ...]`). + * 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 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 + * 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` @@ -352,25 +518,34 @@ declare module 'dns' { * ``` * @since v0.9.12 */ - export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + 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']`). + * 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 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 + * 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 function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; export namespace resolvePtr { function __promisify__(hostname: string): Promise; } @@ -400,12 +575,15 @@ declare module 'dns' { * ``` * @since v0.11.10 */ - export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; + 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 + * 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` @@ -423,18 +601,24 @@ declare module 'dns' { * ``` * @since v0.1.27 */ - export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + 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 + * 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 function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; export namespace resolveTxt { function __promisify__(hostname: string): Promise; } @@ -465,10 +649,13 @@ declare module 'dns' { * 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). + * 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 function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; export namespace resolveAny { function __promisify__(hostname: string): Promise; } @@ -476,11 +663,24 @@ declare module 'dns' { * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an * array of host names. * - * On error, `err` is an `Error` object, where `err.code` is - * one of the `DNS error codes`. + * 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; + export function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `order` defaulting to `ipv4first`. + * * `ipv6first`: for `order` defaulting to `ipv6first`. + * * `verbatim`: for `order` defaulting to `verbatim`. + * @since v18.17.0 + */ + export function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "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 @@ -500,16 +700,16 @@ declare module 'dns' { * 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}). + * 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 + * 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` formatted addresses + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses */ - export function setServers(servers: ReadonlyArray): void; + 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 @@ -527,44 +727,53 @@ declare module 'dns' { */ export function getServers(): string[]; /** - * Set the default value of `verbatim` in {@link lookup}. The value could be: - * - `ipv4first`: sets default `verbatim` `false`. - * - `verbatim`: sets default `verbatim` `true`. + * Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: * - * The default is `ipv4first` and {@link setDefaultResultOrder} have higher priority than `--dns-result-order`. - * When using worker threads, {@link setDefaultResultOrder} from the main thread won't affect the default dns orders in workers. - * @since v14.18.0 - * @param order must be 'ipv4first' or 'verbatim'. + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * 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'`, `'ipv6first'` or `'verbatim'`. */ - export function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; + export function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; // Error codes - export const NODATA: string; - export const FORMERR: string; - export const SERVFAIL: string; - export const NOTFOUND: string; - export const NOTIMP: string; - export const REFUSED: string; - export const BADQUERY: string; - export const BADNAME: string; - export const BADFAMILY: string; - export const BADRESP: string; - export const CONNREFUSED: string; - export const TIMEOUT: string; - export const EOF: string; - export const FILE: string; - export const NOMEM: string; - export const DESTRUCTION: string; - export const BADSTR: string; - export const BADFLAGS: string; - export const NONAME: string; - export const BADHINTS: string; - export const NOTINITIALIZED: string; - export const LOADIPHLPAPI: string; - export const ADDRGETNETWORKPARAMS: string; - export const CANCELLED: string; + export const NODATA: "ENODATA"; + export const FORMERR: "EFORMERR"; + export const SERVFAIL: "ESERVFAIL"; + export const NOTFOUND: "ENOTFOUND"; + export const NOTIMP: "ENOTIMP"; + export const REFUSED: "EREFUSED"; + export const BADQUERY: "EBADQUERY"; + export const BADNAME: "EBADNAME"; + export const BADFAMILY: "EBADFAMILY"; + export const BADRESP: "EBADRESP"; + export const CONNREFUSED: "ECONNREFUSED"; + export const TIMEOUT: "ETIMEOUT"; + export const EOF: "EOF"; + export const FILE: "EFILE"; + export const NOMEM: "ENOMEM"; + export const DESTRUCTION: "EDESTRUCTION"; + export const BADSTR: "EBADSTR"; + export const BADFLAGS: "EBADFLAGS"; + export const NONAME: "ENONAME"; + export const BADHINTS: "EBADHINTS"; + export const NOTINITIALIZED: "ENOTINITIALIZED"; + export const LOADIPHLPAPI: "ELOADIPHLPAPI"; + export const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + export const CANCELLED: "ECANCELLED"; 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; @@ -573,11 +782,11 @@ declare module 'dns' { * 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()` does not affect + * 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('dns'); + * const { Resolver } = require('node:dns'); * const resolver = new Resolver(); * resolver.setServers(['4.4.4.4']); * @@ -587,7 +796,7 @@ declare module 'dns' { * }); * ``` * - * The following methods from the `dns` module are available: + * The following methods from the `node:dns` module are available: * * * `resolver.getServers()` * * `resolver.resolve()` @@ -620,6 +829,7 @@ declare module 'dns' { resolve4: typeof resolve4; resolve6: typeof resolve6; resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; resolveCname: typeof resolveCname; resolveMx: typeof resolveMx; resolveNaptr: typeof resolveNaptr; @@ -634,13 +844,13 @@ declare module 'dns' { * 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 + * 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 + * @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. */ @@ -649,6 +859,6 @@ declare module 'dns' { } export { dnsPromises as promises }; } -declare module 'node:dns' { - export * from 'dns'; +declare module "node:dns" { + export * from "dns"; } diff --git a/node_modules/@types/node/dns/promises.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/dns/promises.d.ts old mode 100755 new mode 100644 similarity index 57% rename from node_modules/@types/node/dns/promises.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/dns/promises.d.ts index a236b5a..cb4c03b --- a/node_modules/@types/node/dns/promises.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/dns/promises.d.ts @@ -1,26 +1,26 @@ /** * 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('dns').promises` or `require('dns/promises')`. + * via `require('node:dns').promises` or `require('node:dns/promises')`. * @since v10.6.0 */ -declare module 'dns/promises' { +declare module "dns/promises" { import { - LookupAddress, - LookupOneOptions, - LookupAllOptions, - LookupOptions, AnyRecord, CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, MxRecord, NaptrRecord, - SoaRecord, - SrvRecord, - ResolveWithTtlOptions, RecordWithTtl, ResolveOptions, ResolverOptions, - } from 'node:dns'; + 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 @@ -43,24 +43,24 @@ declare module 'dns/promises' { * 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`. + * 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` object, where `err.code`is the error code. + * 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()` does not necessarily have anything to do with the DNS + * [`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 + * 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` before + * 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('dns'); + * const dns = require('node:dns'); * const dnsPromises = dns.promises; * const options = { * family: 6, @@ -91,12 +91,12 @@ declare module 'dns/promises' { * 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. + * 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` object, where `err.code`is the error code. + * 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('dns').promises; + * const dnsPromises = require('node:dns').promises; * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { * console.log(result.hostname, result.service); * // Prints: localhost ssh @@ -106,7 +106,7 @@ declare module 'dns/promises' { */ function lookupService( address: string, - port: number + port: number, ): Promise<{ hostname: string; service: string; @@ -119,27 +119,31 @@ declare module 'dns/promises' { * * * - * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * 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; + 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 + * 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. @@ -148,7 +152,7 @@ declare module 'dns/promises' { 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 + * 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. @@ -188,8 +192,8 @@ declare module 'dns/promises' { /** * 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 + * 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; /** @@ -200,13 +204,13 @@ declare module 'dns/promises' { */ 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 + * 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 + * 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` @@ -230,13 +234,13 @@ declare module 'dns/promises' { */ 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 + * 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 + * 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 */ @@ -269,7 +273,7 @@ declare module 'dns/promises' { */ 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 + * 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` @@ -289,7 +293,7 @@ declare module 'dns/promises' { */ 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 + * 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. @@ -300,10 +304,20 @@ declare module 'dns/promises' { * 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` object, where `err.code`is one of the `DNS error codes`. + * 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 @@ -324,32 +338,111 @@ declare module 'dns/promises' { * 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 + * 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: ReadonlyArray): void; + function setServers(servers: readonly string[]): void; /** - * Set the default value of `verbatim` in {@link lookup}. The value could be: - * - `ipv4first`: sets default `verbatim` `false`. - * - `verbatim`: sets default `verbatim` `true`. + * Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be: * - * The default is `ipv4first` and {@link setDefaultResultOrder} have higher priority than `--dns-result-order`. - * When using worker threads, {@link setDefaultResultOrder} from the main thread won't affect the default dns orders in workers. - * @since v14.18.0 - * @param order must be 'ipv4first' or 'verbatim'. + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * 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'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + + /** + * 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 */ - function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; 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; @@ -359,10 +452,25 @@ declare module 'dns/promises' { 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'; +declare module "node:dns/promises" { + export * from "dns/promises"; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/dom-events.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/dom-events.d.ts new file mode 100644 index 0000000..f47f71d --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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/ts4.8/domain.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/domain.d.ts old mode 100755 new mode 100644 similarity index 91% rename from node_modules/@types/node/ts4.8/domain.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/domain.d.ts index a3ce7ee..d8bc999 --- a/node_modules/@types/node/ts4.8/domain.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/domain.d.ts @@ -9,13 +9,13 @@ * 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 + * 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/v16.9.0/lib/domain.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/domain.js) */ -declare module 'domain' { - import EventEmitter = require('node:events'); +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. @@ -29,7 +29,7 @@ declare module '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 + * 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 @@ -47,7 +47,7 @@ declare module 'domain' { * 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. + * 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 @@ -56,15 +56,15 @@ declare module 'domain' { exit(): void; /** * Run the supplied function in the context of the domain, implicitly - * binding all event emitters, timers, and lowlevel requests that are + * 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('domain'); - * const fs = require('fs'); + * const domain = require('node:domain'); + * const fs = require('node:fs'); * const d = domain.create(); * d.on('error', (er) => { * console.error('Caught error!', er); @@ -165,6 +165,6 @@ declare module 'domain' { } function create(): Domain; } -declare module 'node:domain' { - export * from 'domain'; +declare module "node:domain" { + export * from "domain"; } diff --git a/node_modules/@types/node/events.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/events.d.ts old mode 100755 new mode 100644 similarity index 50% rename from node_modules/@types/node/events.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/events.d.ts index 631841a..e7c2341 --- a/node_modules/@types/node/events.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/events.d.ts @@ -22,7 +22,7 @@ * the `eventEmitter.emit()` method is used to trigger the event. * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; * * class MyEmitter extends EventEmitter {} * @@ -32,36 +32,96 @@ * }); * myEmitter.emit('event'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/events.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/events.js) */ -declare module 'events' { +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 NodeEventTarget { - once(eventName: string | symbol, listener: (...args: any[]) => void): this; - } - interface DOMEventTarget { - addEventListener( - eventName: string, - listener: (...args: any[]) => void, - opts?: { - once: boolean; - } - ): any; - } interface StaticEventEmitterOptions { + /** + * Can be used to cancel awaiting events. + */ signal?: AbortSignal | undefined; } - interface EventEmitter extends NodeJS.EventEmitter {} + interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions { + /** + * Names of events that will end the iteration. + */ + close?: string[] | undefined; + /** + * The high watermark. The emitter is paused every time the size of events being buffered is higher than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default Number.MAX_SAFE_INTEGER + */ + highWaterMark?: number | undefined; + /** + * The low watermark. The emitter is resumed every time the size of events being buffered is lower than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default 1 + */ + lowWaterMark?: number | undefined; + } + interface EventEmitter = DefaultEventMap> extends NodeJS.EventEmitter {} + type EventMap = Record | DefaultEventMap; + type DefaultEventMap = [never]; + type AnyRest = [...args: any[]]; + type Args = T extends DefaultEventMap ? AnyRest : ( + K extends keyof T ? T[K] : never + ); + type Key = T extends DefaultEventMap ? string | symbol : K | keyof T; + type Key2 = T extends DefaultEventMap ? string | symbol : K & keyof T; + type Listener = T extends DefaultEventMap ? F : ( + K extends keyof T ? ( + T[K] extends unknown[] ? (...args: T[K]) => void : never + ) + : never + ); + type Listener1 = Listener void>; + type Listener2 = Listener; + /** - * The `EventEmitter` class is defined and exposed by the `events` module: + * The `EventEmitter` class is defined and exposed by the `node:events` module: * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; * ``` * * All `EventEmitter`s emit the event `'newListener'` when new listeners are @@ -70,8 +130,11 @@ declare module 'events' { * It supports the following option: * @since v0.1.26 */ - class EventEmitter { + 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. @@ -82,45 +145,42 @@ declare module 'events' { * semantics and does not listen to the `'error'` event. * * ```js - * const { once, EventEmitter } = require('events'); + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; * - * async function run() { - * const ee = new EventEmitter(); + * const ee = new EventEmitter(); * - * process.nextTick(() => { - * ee.emit('myevent', 42); - * }); + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); * - * const [value] = await once(ee, 'myevent'); - * console.log(value); + * const [value] = await once(ee, 'myevent'); + * console.log(value); * - * const err = new Error('kaboom'); - * process.nextTick(() => { - * ee.emit('error', err); - * }); + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); * - * try { - * await once(ee, 'myevent'); - * } catch (err) { - * console.log('error happened', err); - * } + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); * } - * - * run(); * ``` * - * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the + * The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the * '`error'` event itself, then it is treated as any other kind of event without * special handling: * * ```js - * const { EventEmitter, once } = require('events'); + * import { EventEmitter, once } from 'node:events'; * * const ee = new EventEmitter(); * * once(ee, 'error') * .then(([err]) => console.log('ok', err.message)) - * .catch((err) => console.log('error', err.message)); + * .catch((err) => console.error('error', err.message)); * * ee.emit('error', new Error('boom')); * @@ -130,7 +190,7 @@ declare module 'events' { * An `AbortSignal` can be used to cancel waiting for the event: * * ```js - * const { EventEmitter, once } = require('events'); + * import { EventEmitter, once } from 'node:events'; * * const ee = new EventEmitter(); * const ac = new AbortController(); @@ -154,29 +214,32 @@ declare module 'events' { * ``` * @since v11.13.0, v10.16.0 */ - static once(emitter: NodeEventTarget, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise; - static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + static once( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; /** * ```js - * const { on, EventEmitter } = require('events'); + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; * - * (async () => { - * const ee = new EventEmitter(); + * const ee = new EventEmitter(); * - * // Emit later on - * process.nextTick(() => { - * ee.emit('foo', 'bar'); - * ee.emit('foo', 42); - * }); + * // 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 - * })(); + * 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 @@ -187,7 +250,9 @@ declare module 'events' { * An `AbortSignal` can be used to cancel waiting on events: * * ```js - * const { on, EventEmitter } = require('events'); + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * * const ac = new AbortController(); * * (async () => { @@ -210,16 +275,47 @@ declare module 'events' { * * process.nextTick(() => ac.abort()); * ``` - * @since v13.6.0, v12.16.0 - * @param eventName The name of the event being listened for - * @return that iterates `eventName` events emitted by the `emitter` - */ - static on(emitter: NodeJS.EventEmitter, eventName: string, options?: StaticEventEmitterOptions): AsyncIterableIterator; - /** - * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * Use the `close` option to specify an array of event names that will end the iteration: * * ```js - * const { EventEmitter, listenerCount } = require('events'); + * 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); + * ee.emit('close'); + * }); + * + * for await (const event of on(ee, 'foo', { close: ['close'] })) { + * console.log(event); // prints ['bar'] [42] + * } + * // the loop will exit after 'close' is emitted + * console.log('done'); // prints 'done' + * ``` + * @since v13.6.0, v12.16.0 + * @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterIteratorOptions, + ): AsyncIterableIterator; + static on( + emitter: EventTarget, + eventName: string, + options?: StaticEventEmitterIteratorOptions, + ): 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', () => {}); @@ -242,30 +338,56 @@ declare module 'events' { * event target. This is useful for debugging and diagnostic purposes. * * ```js - * const { getEventListeners, EventEmitter } = require('events'); + * import { getEventListeners, EventEmitter } from 'node:events'; * * { * const ee = new EventEmitter(); * const listener = () => console.log('Events are fun'); * ee.on('foo', listener); - * getEventListeners(ee, 'foo'); // [listener] + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] * } * { * const et = new EventTarget(); * const listener = () => console.log('Events are fun'); * et.addEventListener('foo', listener); - * getEventListeners(et, 'foo'); // [listener] + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] * } * ``` - * @since v15.2.0 + * @since v15.2.0, v14.17.0 */ - static getEventListeners(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + 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 - * const { - * setMaxListeners, - * EventEmitter - * } = require('events'); + * import { setMaxListeners, EventEmitter } from 'node:events'; * * const target = new EventTarget(); * const emitter = new EventEmitter(); @@ -277,26 +399,105 @@ declare module 'events' { * @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; + static setMaxListeners(n?: number, ...eventTargets: Array): void; /** - * 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. + * Listens once to the `abort` event on the provided `signal`. * - * 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 + * 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; /** - * Sets or gets the default captureRejection value for all emitters. + * 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 */ - // TODO: These should be described using static getter/setter pairs: 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'); + 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 }; @@ -306,20 +507,99 @@ declare module 'events' { */ 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 { + interface EventEmitter = DefaultEventMap> { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; /** * Alias for `emitter.on(eventName, listener)`. * @since v0.1.26 */ - addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + 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. + * 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) => { @@ -329,10 +609,11 @@ declare module 'events' { * * 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 + * 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')); @@ -345,9 +626,9 @@ declare module 'events' { * @param eventName The name of the event. * @param listener The callback function */ - on(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: Key, listener: Listener1): this; /** - * Adds a **one-time**`listener` function for the event named `eventName`. The + * 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 @@ -358,10 +639,11 @@ declare module 'events' { * * 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 + * 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')); @@ -374,9 +656,9 @@ declare module 'events' { * @param eventName The name of the event. * @param listener The callback function */ - once(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: Key, listener: Listener1): this; /** - * Removes the specified `listener` from the listener array for the event named`eventName`. + * Removes the specified `listener` from the listener array for the event named `eventName`. * * ```js * const callback = (stream) => { @@ -393,10 +675,12 @@ declare module 'events' { * 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. + * 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 = () => { @@ -434,9 +718,10 @@ declare module 'events' { * * 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: + * recently added instance. In the example the `once('ping')` listener is removed: * * ```js + * import { EventEmitter } from 'node:events'; * const ee = new EventEmitter(); * * function pong() { @@ -454,12 +739,12 @@ declare module 'events' { * Returns a reference to the `EventEmitter`, so that calls can be chained. * @since v0.1.26 */ - removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + removeListener(eventName: Key, listener: Listener1): this; /** * Alias for `emitter.removeListener()`. * @since v10.0.0 */ - off(eventName: string | symbol, listener: (...args: any[]) => void): this; + off(eventName: Key, listener: Listener1): this; /** * Removes all listeners, or those of the specified `eventName`. * @@ -470,12 +755,12 @@ declare module 'events' { * Returns a reference to the `EventEmitter`, so that calls can be chained. * @since v0.1.26 */ - removeAllListeners(event?: string | symbol): this; + 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. + * 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 @@ -499,12 +784,13 @@ declare module 'events' { * ``` * @since v0.1.26 */ - listeners(eventName: string | symbol): Function[]; + 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')); * @@ -529,15 +815,15 @@ declare module 'events' { * ``` * @since v9.4.0 */ - rawListeners(eventName: string | symbol): Function[]; + 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 + * Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments * to each. * * Returns `true` if the event had listeners, `false` otherwise. * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; * const myEmitter = new EventEmitter(); * * // First listener @@ -570,18 +856,21 @@ declare module 'events' { * ``` * @since v0.1.26 */ - emit(eventName: string | symbol, ...args: any[]): boolean; + emit(eventName: Key, ...args: Args): boolean; /** - * Returns the number of listeners listening to the event named `eventName`. + * 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: string | symbol): number; + 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. + * 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) => { @@ -594,9 +883,9 @@ declare module 'events' { * @param eventName The name of the event. * @param listener The callback function */ - prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + 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 + * 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 @@ -610,13 +899,14 @@ declare module 'events' { * @param eventName The name of the event. * @param listener The callback function */ - prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(eventName: Key, listener: Listener1): this; /** * Returns an array listing the events for which the emitter has registered * listeners. The values in the array are strings or `Symbol`s. * * ```js - * const EventEmitter = require('events'); + * import { EventEmitter } from 'node:events'; + * * const myEE = new EventEmitter(); * myEE.on('foo', () => {}); * myEE.on('bar', () => {}); @@ -629,13 +919,13 @@ declare module 'events' { * ``` * @since v6.0.0 */ - eventNames(): Array; + eventNames(): Array<(string | symbol) & Key2>; } } } export = EventEmitter; } -declare module 'node:events' { - import events = require('events'); +declare module "node:events" { + import events = require("events"); export = events; } diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/fs.d.ts old mode 100755 new mode 100644 similarity index 78% rename from node_modules/@types/node/fs.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/fs.d.ts index a7b46c0..dc1d5da --- a/node_modules/@types/node/fs.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/fs.d.ts @@ -1,28 +1,28 @@ /** - * The `fs` module enables interacting with the file system in a + * 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 'fs/promises'; + * import * as fs from 'node:fs/promises'; * ``` * * To use the callback and sync APIs: * * ```js - * import * as fs from 'fs'; + * 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/v16.9.0/lib/fs.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/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'; +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". @@ -32,10 +32,10 @@ declare module 'fs' { export type TimeLike = string | number | Date; export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; export type BufferEncodingOption = - | 'buffer' + | "buffer" | { - encoding: 'buffer'; - }; + encoding: "buffer"; + }; export interface ObjectEncodingOptions { encoding?: BufferEncoding | null | undefined; } @@ -73,11 +73,11 @@ declare module 'fs' { /** * A `fs.Stats` object provides information about a file. * - * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * 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`. + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. * * ```console * Stats { @@ -131,6 +131,62 @@ declare module 'fs' { * @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 @@ -184,6 +240,17 @@ declare module 'fs' { * @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. @@ -191,7 +258,7 @@ declare module 'fs' { * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. * * ```js - * import { opendir } from 'fs/promises'; + * import { opendir } from 'node:fs/promises'; * * try { * const dir = await opendir('./'); @@ -220,7 +287,7 @@ declare module 'fs' { * Asynchronously close the directory's underlying resource handle. * Subsequent reads will result in errors. * - * A promise is returned that will be resolved after the resource has been + * A promise is returned that will be fulfilled after the resource has been * closed. * @since v12.12.0 */ @@ -235,7 +302,7 @@ declare module 'fs' { /** * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. * - * A promise is returned that will be resolved with an `fs.Dirent`, or `null`if there are no more directory entries to read. + * 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. @@ -268,18 +335,22 @@ declare module 'fs' { */ 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 - * 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. */ 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 - * 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. */ unref(): this; } @@ -289,31 +360,51 @@ declare module 'fs' { * @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. error + * 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: 'error', listener: (error: Error) => void): this; - addListener(event: 'close', listener: () => 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: 'error', listener: (error: Error) => void): this; - on(event: 'close', listener: () => 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: 'error', listener: (error: Error) => void): this; - once(event: 'close', listener: () => 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: 'error', listener: (error: Error) => void): this; - prependListener(event: 'close', listener: () => 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: 'error', listener: (error: Error) => void): this; - prependOnceListener(event: 'close', listener: () => 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. @@ -345,55 +436,55 @@ declare module 'fs' { * 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: "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: "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: "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: "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: "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; } /** @@ -434,50 +525,50 @@ declare module 'fs' { * 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: "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: "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: "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: "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: "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; } /** @@ -490,7 +581,7 @@ declare module 'fs' { * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). * * ```js - * import { rename } from 'fs'; + * import { rename } from 'node:fs'; * * rename('oldFile.txt', 'newFile.txt', (err) => { * if (err) throw err; @@ -523,7 +614,7 @@ declare module 'fs' { * first argument. In this case, `fs.ftruncate()` is called. * * ```js - * import { truncate } from 'fs'; + * import { truncate } from 'node:fs'; * // Assuming that 'path/file.txt' is a regular file. * truncate('path/file.txt', (err) => { * if (err) throw err; @@ -575,7 +666,7 @@ declare module 'fs' { * file: * * ```js - * import { open, close, ftruncate } from 'fs'; + * import { open, close, ftruncate } from 'node:fs'; * * function closeFd(fd) { * close(fd, (err) => { @@ -732,7 +823,7 @@ declare module 'fs' { * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. * * ```js - * import { chmod } from 'fs'; + * import { chmod } from 'node:fs'; * * chmod('my_file.txt', 0o775, (err) => { * if (err) throw err; @@ -814,7 +905,10 @@ declare module 'fs' { * * In case of an error, the `err.code` will be one of `Common System Errors`. * - * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * {@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. * @@ -831,7 +925,7 @@ declare module 'fs' { * The next program will check for the stats of the given paths: * * ```js - * import { stat } from 'fs'; + * import { stat } from 'node:fs'; * * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; * @@ -896,19 +990,23 @@ declare module 'fs' { path: PathLike, options: | (StatOptions & { - bigint?: false | undefined; - }) + bigint?: false | undefined; + }) | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + 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 + 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 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. @@ -918,13 +1016,13 @@ declare module 'fs' { path: PathLike, options?: StatOptions & { bigint?: false | undefined; - } + }, ): Promise; function __promisify__( path: PathLike, options: StatOptions & { bigint: true; - } + }, ): Promise; function __promisify__(path: PathLike, options?: StatOptions): Promise; } @@ -935,33 +1033,33 @@ declare module 'fs' { 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; } @@ -981,19 +1079,23 @@ declare module 'fs' { fd: number, options: | (StatOptions & { - bigint?: false | undefined; - }) + bigint?: false | undefined; + }) | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + 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 + 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 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. @@ -1003,34 +1105,35 @@ declare module 'fs' { fd: number, options?: StatOptions & { bigint?: false | undefined; - } + }, ): Promise; function __promisify__( fd: number, options: StatOptions & { bigint: true; - } + }, ): Promise; function __promisify__(fd: number, options?: StatOptions): Promise; } /** - * Synchronous fstat(2) - Get file status. - * @param fd A file descriptor. + * 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 @@ -1044,19 +1147,23 @@ declare module 'fs' { path: PathLike, options: | (StatOptions & { - bigint?: false | undefined; - }) + bigint?: false | undefined; + }) | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + 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 + 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 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. @@ -1066,16 +1173,86 @@ declare module 'fs' { 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. @@ -1109,30 +1286,37 @@ declare module 'fs' { * * The `type` argument is only available on Windows and ignored on other platforms. * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is - * not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If - * the `target` does not exist, `'file'` will be used. Windows junction points - * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. + * 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. + * Relative targets are relative to the link's parent directory. * * ```js - * import { symlink } from 'fs'; + * import { symlink } from 'node:fs'; * - * symlink('./mew', './example/mewtwo', callback); + * symlink('./mew', './mewtwo', callback); * ``` * - * The above example creates a symbolic link `mewtwo` in the `example` which points - * to `mew` in the same directory: + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: * * ```bash - * $ tree example/ - * example/ + * $ 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; + 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. @@ -1148,7 +1332,7 @@ declare module 'fs' { * 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'; + type Type = "dir" | "file" | "junction"; } /** * Returns `undefined`. @@ -1156,6 +1340,7 @@ declare module 'fs' { * 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; /** @@ -1170,24 +1355,39 @@ declare module 'fs' { * 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; + 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; + 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; + 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 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. @@ -1233,7 +1433,7 @@ declare module 'fs' { */ export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; /** - * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and * symbolic links. * * A canonical pathname is not necessarily unique. Hard links and bind mounts can @@ -1245,7 +1445,7 @@ declare module 'fs' { * 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. + * 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. * @@ -1258,24 +1458,39 @@ declare module 'fs' { * 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; + 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; + 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; + 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 function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; export namespace realpath { /** * Asynchronous realpath(3) - return the canonicalized absolute pathname. @@ -1312,10 +1527,25 @@ declare module 'fs' { * 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; + 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. @@ -1347,7 +1577,7 @@ declare module 'fs' { * possible exception are given to the completion callback. * * ```js - * import { unlink } from 'fs'; + * import { unlink } from 'node:fs'; * // Assuming that 'path/file.txt' is a regular file. * unlink('path/file.txt', (err) => { * if (err) throw err; @@ -1390,7 +1620,7 @@ declare module 'fs' { * Use `fs.rm(path, { recursive: true, force: true })` instead. * * If `true`, perform a recursive directory removal. In - * recursive mode soperations are retried on failure. + * recursive mode, operations are retried on failure. * @default false */ recursive?: boolean | undefined; @@ -1459,7 +1689,7 @@ declare module 'fs' { 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 + * 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 */ @@ -1472,7 +1702,7 @@ declare module 'fs' { function __promisify__(path: PathLike, options?: RmOptions): Promise; } /** - * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * 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; @@ -1494,18 +1724,19 @@ declare module 'fs' { * * 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. + * 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 + * 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. + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. * * ```js - * import { mkdir } from 'fs'; + * import { mkdir } from 'node:fs'; * - * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. - * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { * if (err) throw err; * }); * ``` @@ -1514,7 +1745,7 @@ declare module 'fs' { * result in an error: * * ```js - * import { mkdir } from 'fs'; + * import { mkdir } from 'node:fs'; * * mkdir('/', { recursive: true }, (err) => { * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] @@ -1529,7 +1760,7 @@ declare module 'fs' { options: MakeDirectoryOptions & { recursive: true; }, - callback: (err: NodeJS.ErrnoException | null, path?: string) => void + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, ): void; /** * Asynchronous mkdir(2) - create a directory. @@ -1542,11 +1773,11 @@ declare module 'fs' { options: | Mode | (MakeDirectoryOptions & { - recursive?: false | undefined; - }) + recursive?: false | undefined; + }) | null | undefined, - callback: NoParamCallback + callback: NoParamCallback, ): void; /** * Asynchronous mkdir(2) - create a directory. @@ -1554,7 +1785,11 @@ declare module 'fs' { * @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; + 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. @@ -1571,7 +1806,7 @@ declare module 'fs' { path: PathLike, options: MakeDirectoryOptions & { recursive: true; - } + }, ): Promise; /** * Asynchronous mkdir(2) - create a directory. @@ -1584,9 +1819,9 @@ declare module 'fs' { options?: | Mode | (MakeDirectoryOptions & { - recursive?: false | undefined; - }) - | null + recursive?: false | undefined; + }) + | null, ): Promise; /** * Asynchronous mkdir(2) - create a directory. @@ -1594,10 +1829,13 @@ declare module 'fs' { * @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; + 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. + * 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. @@ -1607,7 +1845,7 @@ declare module 'fs' { path: PathLike, options: MakeDirectoryOptions & { recursive: true; - } + }, ): string | undefined; /** * Synchronous mkdir(2) - create a directory. @@ -1620,9 +1858,9 @@ declare module 'fs' { options?: | Mode | (MakeDirectoryOptions & { - recursive?: false | undefined; - }) - | null + recursive?: false | undefined; + }) + | null, ): void; /** * Synchronous mkdir(2) - create a directory. @@ -1634,7 +1872,7 @@ declare module 'fs' { /** * 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 + * 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. @@ -1646,9 +1884,11 @@ declare module 'fs' { * object with an `encoding` property specifying the character encoding to use. * * ```js - * import { mkdtemp } from 'fs'; + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; * - * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * 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 @@ -1658,11 +1898,11 @@ declare module 'fs' { * The `fs.mkdtemp()` method will append the six randomly selected characters * directly to the `prefix` string. For instance, given a directory `/tmp`, if the * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator - * (`require('path').sep`). + * (`require('node:path').sep`). * * ```js - * import { tmpdir } from 'os'; - * import { mkdtemp } from 'fs'; + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; * * // The parent directory for the new temporary directory * const tmpDir = tmpdir(); @@ -1677,7 +1917,7 @@ declare module 'fs' { * }); * * // This method is *CORRECT*: - * import { sep } from 'path'; + * import { sep } from 'node:path'; * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { * if (err) throw err; * console.log(directory); @@ -1688,7 +1928,11 @@ declare module 'fs' { * ``` * @since v5.10.0 */ - export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + 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. @@ -1697,23 +1941,30 @@ declare module 'fs' { export function mkdtemp( prefix: string, options: - | 'buffer' + | "buffer" | { - encoding: 'buffer'; - }, - callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void + 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; + 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 function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; export namespace mkdtemp { /** * Asynchronously creates a unique temporary directory. @@ -1758,7 +2009,7 @@ declare module 'fs' { */ 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 `'..'`. + * 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. * @@ -1774,13 +2025,14 @@ declare module 'fs' { path: PathLike, options: | { - encoding: BufferEncoding | null; - withFileTypes?: false | undefined; - } + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[]) => void + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, ): void; /** * Asynchronous readdir(3) - read a directory. @@ -1791,11 +2043,12 @@ declare module 'fs' { path: PathLike, options: | { - encoding: 'buffer'; - withFileTypes?: false | undefined; - } - | 'buffer', - callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, ): void; /** * Asynchronous readdir(3) - read a directory. @@ -1806,18 +2059,22 @@ declare module 'fs' { path: PathLike, options: | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - }) + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void + 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; + 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. @@ -1827,8 +2084,9 @@ declare module 'fs' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; + recursive?: boolean | undefined; }, - callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, ): void; export namespace readdir { /** @@ -1840,11 +2098,12 @@ declare module 'fs' { path: PathLike, options?: | { - encoding: BufferEncoding | null; - withFileTypes?: false | undefined; - } + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } | BufferEncoding - | null + | null, ): Promise; /** * Asynchronous readdir(3) - read a directory. @@ -1854,11 +2113,12 @@ declare module 'fs' { function __promisify__( path: PathLike, options: - | 'buffer' + | "buffer" | { - encoding: 'buffer'; - withFileTypes?: false | undefined; - } + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, ): Promise; /** * Asynchronous readdir(3) - read a directory. @@ -1869,10 +2129,11 @@ declare module 'fs' { path: PathLike, options?: | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - }) + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) | BufferEncoding - | null + | null, ): Promise; /** * Asynchronous readdir(3) - read a directory. @@ -1883,7 +2144,8 @@ declare module 'fs' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; - } + recursive?: boolean | undefined; + }, ): Promise; } /** @@ -1903,11 +2165,12 @@ declare module 'fs' { path: PathLike, options?: | { - encoding: BufferEncoding | null; - withFileTypes?: false | undefined; - } + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } | BufferEncoding - | null + | null, ): string[]; /** * Synchronous readdir(3) - read a directory. @@ -1918,10 +2181,11 @@ declare module 'fs' { path: PathLike, options: | { - encoding: 'buffer'; - withFileTypes?: false | undefined; - } - | 'buffer' + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", ): Buffer[]; /** * Synchronous readdir(3) - read a directory. @@ -1932,10 +2196,11 @@ declare module 'fs' { path: PathLike, options?: | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - }) + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) | BufferEncoding - | null + | null, ): string[] | Buffer[]; /** * Synchronous readdir(3) - read a directory. @@ -1946,7 +2211,8 @@ declare module 'fs' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; - } + recursive?: boolean | undefined; + }, ): Dirent[]; /** * Closes the file descriptor. No arguments other than a possible exception are @@ -1993,13 +2259,22 @@ declare module 'fs' { * @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; + 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 [flags='r'] See `support of file system `flags``. * @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; + 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. @@ -2028,8 +2303,8 @@ declare module 'fs' { * * 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. + * * 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; @@ -2093,8 +2368,7 @@ declare module 'fs' { */ export function fsyncSync(fd: number): void; /** - * Write `buffer` to the file specified by `fd`. If `buffer` is a normal object, it - * must have an own `toString` function property. + * 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. @@ -2103,7 +2377,7 @@ declare module 'fs' { * 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`. + * 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. @@ -2116,6 +2390,9 @@ declare module 'fs' { * 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, @@ -2123,7 +2400,7 @@ declare module 'fs' { offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, ): void; /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. @@ -2136,7 +2413,7 @@ declare module 'fs' { buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, ): void; /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. @@ -2147,13 +2424,17 @@ declare module 'fs' { fd: number, buffer: TBuffer, offset: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + 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; + 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. @@ -2166,7 +2447,7 @@ declare module 'fs' { string: string, position: number | undefined | null, encoding: BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, ): void; /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. @@ -2174,13 +2455,22 @@ declare module 'fs' { * @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; + 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 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. @@ -2194,7 +2484,7 @@ declare module 'fs' { buffer?: TBuffer, offset?: number, length?: number, - position?: number | null + position?: number | null, ): Promise<{ bytesWritten: number; buffer: TBuffer; @@ -2210,21 +2500,28 @@ declare module 'fs' { fd: number, string: string, position?: number | null, - encoding?: BufferEncoding | null + encoding?: BufferEncoding | null, ): Promise<{ bytesWritten: number; buffer: string; }>; } /** - * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. - * * 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; + 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. @@ -2232,8 +2529,30 @@ declare module 'fs' { * @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 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`. * @@ -2257,7 +2576,25 @@ declare module 'fs' { offset: number, length: number, position: ReadPosition | null, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void + 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 { /** @@ -2272,25 +2609,22 @@ declare module 'fs' { buffer: TBuffer, offset: number, length: number, - position: number | null + position: number | null, ): Promise<{ bytesRead: number; buffer: TBuffer; }>; - } - export interface ReadSyncOptions { - /** - * @default 0 - */ - offset?: number | undefined; - /** - * @default `length of buffer` - */ - length?: number | undefined; - /** - * @default null - */ - position?: ReadPosition | null | undefined; + 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`. @@ -2298,8 +2632,15 @@ declare module 'fs' { * 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; + 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. @@ -2309,7 +2650,7 @@ declare module 'fs' { * Asynchronously reads the entire contents of a file. * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * readFile('/etc/passwd', (err, data) => { * if (err) throw err; @@ -2325,7 +2666,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * readFile('/etc/passwd', 'utf8', callback); * ``` @@ -2335,7 +2676,7 @@ declare module 'fs' { * will be returned. * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * // macOS, Linux, and Windows * readFile('', (err, data) => { @@ -2352,7 +2693,7 @@ declare module 'fs' { * request is aborted the callback is called with an `AbortError`: * * ```js - * import { readFile } from 'fs'; + * import { readFile } from 'node:fs'; * * const controller = new AbortController(); * const signal = controller.signal; @@ -2375,12 +2716,12 @@ declare module 'fs' { path: PathOrFileDescriptor, options: | ({ - encoding?: null | undefined; - flag?: string | undefined; - } & Abortable) + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) | undefined | null, - callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, ): void; /** * Asynchronously reads the entire contents of a file. @@ -2393,11 +2734,11 @@ declare module 'fs' { path: PathOrFileDescriptor, options: | ({ - encoding: BufferEncoding; - flag?: string | undefined; - } & Abortable) + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) | BufferEncoding, - callback: (err: NodeJS.ErrnoException | null, data: string) => void + callback: (err: NodeJS.ErrnoException | null, data: string) => void, ): void; /** * Asynchronously reads the entire contents of a file. @@ -2410,19 +2751,22 @@ declare module 'fs' { path: PathOrFileDescriptor, options: | (ObjectEncodingOptions & { - flag?: string | undefined; - } & Abortable) + flag?: string | undefined; + } & Abortable) | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void + 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 function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, + ): void; export namespace readFile { /** * Asynchronously reads the entire contents of a file. @@ -2436,7 +2780,7 @@ declare module 'fs' { options?: { encoding?: null | undefined; flag?: string | undefined; - } | null + } | null, ): Promise; /** * Asynchronously reads the entire contents of a file. @@ -2450,10 +2794,10 @@ declare module 'fs' { path: PathOrFileDescriptor, options: | { - encoding: BufferEncoding; - flag?: string | undefined; - } - | BufferEncoding + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, ): Promise; /** * Asynchronously reads the entire contents of a file. @@ -2467,10 +2811,10 @@ declare module 'fs' { path: PathOrFileDescriptor, options?: | (ObjectEncodingOptions & { - flag?: string | undefined; - }) + flag?: string | undefined; + }) | BufferEncoding - | null + | null, ): Promise; } /** @@ -2482,10 +2826,10 @@ declare module 'fs' { * 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. + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. * * ```js - * import { readFileSync } from 'fs'; + * import { readFileSync } from 'node:fs'; * * // macOS, Linux, and Windows * readFileSync(''); @@ -2502,7 +2846,7 @@ declare module 'fs' { options?: { encoding?: null | undefined; flag?: string | undefined; - } | null + } | null, ): Buffer; /** * Synchronously reads the entire contents of a file. @@ -2515,10 +2859,10 @@ declare module 'fs' { path: PathOrFileDescriptor, options: | { - encoding: BufferEncoding; - flag?: string | undefined; - } - | BufferEncoding + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, ): string; /** * Synchronously reads the entire contents of a file. @@ -2531,35 +2875,37 @@ declare module 'fs' { path: PathOrFileDescriptor, options?: | (ObjectEncodingOptions & { - flag?: string | undefined; - }) + flag?: string | undefined; + }) | BufferEncoding - | null + | null, ): string | Buffer; export type WriteFileOptions = - | (ObjectEncodingOptions & - Abortable & { - mode?: Mode | undefined; - flag?: string | undefined; - }) + | ( + & 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 + * 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. * - * If `data` is a plain object, it must have an own (not inherited) `toString`function property. - * * ```js - * import { writeFile } from 'fs'; - * import { Buffer } from 'buffer'; + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; * * const data = new Uint8Array(Buffer.from('Hello Node.js')); * writeFile('message.txt', data, (err) => { @@ -2571,7 +2917,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { writeFile } from 'fs'; + * import { writeFile } from 'node:fs'; * * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); * ``` @@ -2589,8 +2935,8 @@ declare module 'fs' { * to be written. * * ```js - * import { writeFile } from 'fs'; - * import { Buffer } from 'buffer'; + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; * * const controller = new AbortController(); * const { signal } = controller; @@ -2607,14 +2953,23 @@ declare module 'fs' { * @since v0.1.29 * @param file filename or file descriptor */ - export function writeFile(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; + 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 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. @@ -2628,13 +2983,15 @@ declare module 'fs' { * 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; + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; } /** * Returns `undefined`. * - * If `data` is a plain object, it must have an own (not inherited) `toString`function property. - * * 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 @@ -2642,7 +2999,11 @@ declare module 'fs' { * @since v0.1.29 * @param file filename or file descriptor */ - export function writeFileSync(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; + 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`. @@ -2650,7 +3011,7 @@ declare module 'fs' { * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js - * import { appendFile } from 'fs'; + * import { appendFile } from 'node:fs'; * * appendFile('message.txt', 'data to append', (err) => { * if (err) throw err; @@ -2661,7 +3022,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { appendFile } from 'fs'; + * import { appendFile } from 'node:fs'; * * appendFile('message.txt', 'data to append', 'utf8', callback); * ``` @@ -2671,7 +3032,7 @@ declare module 'fs' { * not be closed automatically. * * ```js - * import { open, close, appendFile } from 'fs'; + * import { open, close, appendFile } from 'node:fs'; * * function closeFd(fd) { * close(fd, (err) => { @@ -2696,7 +3057,12 @@ declare module 'fs' { * @since v0.6.7 * @param path filename or file descriptor */ - export function appendFile(path: PathOrFileDescriptor, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void; + 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. @@ -2717,7 +3083,11 @@ declare module 'fs' { * 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; + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; } /** * Synchronously append data to a file, creating the file if it does not yet @@ -2726,7 +3096,7 @@ declare module 'fs' { * The `mode` option only affects the newly created file. See {@link open} for more details. * * ```js - * import { appendFileSync } from 'fs'; + * import { appendFileSync } from 'node:fs'; * * try { * appendFileSync('message.txt', 'data to append'); @@ -2739,7 +3109,7 @@ declare module 'fs' { * If `options` is a string, then it specifies the encoding: * * ```js - * import { appendFileSync } from 'fs'; + * import { appendFileSync } from 'node:fs'; * * appendFileSync('message.txt', 'data to append', 'utf8'); * ``` @@ -2749,7 +3119,7 @@ declare module 'fs' { * not be closed automatically. * * ```js - * import { openSync, closeSync, appendFileSync } from 'fs'; + * import { openSync, closeSync, appendFileSync } from 'node:fs'; * * let fd; * @@ -2766,12 +3136,16 @@ declare module 'fs' { * @since v0.6.7 * @param path filename or file descriptor */ - export function appendFileSync(path: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): void; + 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 + * 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. @@ -2800,7 +3174,7 @@ declare module 'fs' { * 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. + * 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 @@ -2818,29 +3192,75 @@ declare module 'fs' { 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; - }) + bigint?: false | undefined; + }) | undefined, - listener: (curr: Stats, prev: Stats) => void + listener: StatsListener, ): StatWatcher; export function watchFile( filename: PathLike, options: | (WatchFileOptions & { - bigint: true; - }) + bigint: true; + }) | undefined, - listener: (curr: BigIntStats, prev: BigIntStats) => void + 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: (curr: Stats, prev: Stats) => void): StatWatcher; + 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, @@ -2849,18 +3269,21 @@ declare module 'fs' { * 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. + * 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?: (curr: Stats, prev: Stats) => void): void; + 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; + encoding?: BufferEncoding | "buffer" | undefined; persistent?: boolean | undefined; recursive?: boolean | undefined; } - export type WatchEventType = 'rename' | 'change'; - export type WatchListener = (event: WatchEventType, filename: T) => void; + 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. @@ -2874,7 +3297,7 @@ declare module 'fs' { * 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`. + * 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`. @@ -2885,10 +3308,10 @@ declare module 'fs' { filename: PathLike, options: | (WatchOptions & { - encoding: 'buffer'; - }) - | 'buffer', - listener?: WatchListener + encoding: "buffer"; + }) + | "buffer", + listener?: WatchListener, ): FSWatcher; /** * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. @@ -2898,7 +3321,11 @@ declare module 'fs' { * 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; + 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. @@ -2907,7 +3334,11 @@ declare module 'fs' { * 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; + 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. @@ -2918,7 +3349,7 @@ declare module 'fs' { * Then call the `callback` argument with either true or false: * * ```js - * import { exists } from 'fs'; + * import { exists } from 'node:fs'; * * exists('/etc/passwd', (e) => { * console.log(e ? 'it exists' : 'no passwd!'); @@ -2926,11 +3357,11 @@ declare module 'fs' { * ``` * * **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 + * **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 + * 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. @@ -2938,7 +3369,7 @@ declare module 'fs' { * **write (NOT RECOMMENDED)** * * ```js - * import { exists, open, close } from 'fs'; + * import { exists, open, close } from 'node:fs'; * * exists('myfile', (e) => { * if (e) { @@ -2962,7 +3393,7 @@ declare module 'fs' { * **write (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * open('myfile', 'wx', (err, fd) => { * if (err) { * if (err.code === 'EEXIST') { @@ -2986,7 +3417,7 @@ declare module 'fs' { * **read (NOT RECOMMENDED)** * * ```js - * import { open, close, exists } from 'fs'; + * import { open, close, exists } from 'node:fs'; * * exists('myfile', (e) => { * if (e) { @@ -3010,7 +3441,7 @@ declare module 'fs' { * **read (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * * open('myfile', 'r', (err, fd) => { * if (err) { @@ -3036,7 +3467,7 @@ declare module 'fs' { * 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 + * 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 @@ -3057,11 +3488,11 @@ declare module 'fs' { * 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 + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other * Node.js callbacks. `fs.existsSync()` does not use a callback. * * ```js - * import { existsSync } from 'fs'; + * import { existsSync } from 'node:fs'; * * if (existsSync('/etc/passwd')) * console.log('The path exists.'); @@ -3186,16 +3617,16 @@ declare module 'fs' { /** * 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. Check `File access constants` for possible values - * of `mode`. It is possible to create a mask consisting of the bitwise OR of - * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * 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. + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. * * ```js - * import { access, constants } from 'fs'; + * import { access, constants } from 'node:fs'; * * const file = 'package.json'; * @@ -3214,18 +3645,13 @@ declare module 'fs' { * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); * }); * - * // Check if the file exists in the current directory, and if it is writable. - * access(file, constants.F_OK | constants.W_OK, (err) => { - * if (err) { - * console.error( - * `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`); - * } else { - * console.log(`${file} exists, and it 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 + * 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. @@ -3233,7 +3659,7 @@ declare module 'fs' { * **write (NOT RECOMMENDED)** * * ```js - * import { access, open, close } from 'fs'; + * import { access, open, close } from 'node:fs'; * * access('myfile', (err) => { * if (!err) { @@ -3258,7 +3684,7 @@ declare module 'fs' { * **write (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * * open('myfile', 'wx', (err, fd) => { * if (err) { @@ -3283,7 +3709,7 @@ declare module 'fs' { * **read (NOT RECOMMENDED)** * * ```js - * import { access, open, close } from 'fs'; + * import { access, open, close } from 'node:fs'; * access('myfile', (err) => { * if (err) { * if (err.code === 'ENOENT') { @@ -3311,7 +3737,7 @@ declare module 'fs' { * **read (RECOMMENDED)** * * ```js - * import { open, close } from 'fs'; + * import { open, close } from 'node:fs'; * * open('myfile', 'r', (err, fd) => { * if (err) { @@ -3365,16 +3791,15 @@ declare module 'fs' { /** * 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. Check `File access constants` for - * possible values of `mode`. It is possible to create a mask consisting of - * the bitwise OR of two or more values - * (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. * * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, * the method will return `undefined`. * * ```js - * import { accessSync, constants } from 'fs'; + * import { accessSync, constants } from 'node:fs'; * * try { * accessSync('etc/passwd', constants.R_OK | constants.W_OK); @@ -3393,19 +3818,33 @@ declare module 'fs' { fd?: number | promises.FileHandle | undefined; mode?: number | undefined; autoClose?: boolean | undefined; - /** - * @default false - */ 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 kb default `highWaterMark` for a `stream.Readable`, the stream - * returned by this method has a default `highWaterMark` of 64 kb. + * 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 @@ -3426,12 +3865,12 @@ declare module 'fs' { * 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 + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is * also required. * * ```js - * import { createReadStream } from 'fs'; + * import { createReadStream } from 'node:fs'; * * // Create a stream from some character device. * const stream = createReadStream('/dev/input/event0'); @@ -3459,7 +3898,7 @@ declare module 'fs' { * An example to read the last 10 bytes of a file which is 100 bytes long: * * ```js - * import { createReadStream } from 'fs'; + * import { createReadStream } from 'node:fs'; * * createReadStream('sample.txt', { start: 90, end: 99 }); * ``` @@ -3471,11 +3910,11 @@ declare module 'fs' { /** * `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`. + * \[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, + * 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. @@ -3483,19 +3922,19 @@ declare module 'fs' { * 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 + * 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. + * 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 + * 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 | StreamOptions): WriteStream; + 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 @@ -3538,7 +3977,7 @@ declare module 'fs' { * copy-on-write, then the operation will fail. * * ```js - * import { copyFile, constants } from 'fs'; + * import { copyFile, constants } from 'node:fs'; * * function callback(err) { * if (err) throw err; @@ -3581,7 +4020,7 @@ declare module 'fs' { * copy-on-write, then the operation will fail. * * ```js - * import { copyFileSync, constants } from 'fs'; + * import { copyFileSync, constants } from 'node:fs'; * * // destination.txt will be created or overwritten by default. * copyFileSync('source.txt', 'destination.txt'); @@ -3597,15 +4036,15 @@ declare module 'fs' { */ export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; /** - * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * 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`. + * 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. + * 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}. @@ -3614,28 +4053,38 @@ declare module 'fs' { * 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: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void; export function writev( fd: number, - buffers: ReadonlyArray, + 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 + 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: ReadonlyArray, position?: number): Promise; + 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: ReadonlyArray, position?: number): number; + 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()`. @@ -3644,34 +4093,77 @@ declare module 'fs' { * 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. + * 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: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void; export function readv( fd: number, - buffers: ReadonlyArray, + 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 + 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: ReadonlyArray, position?: number): Promise; + 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: ReadonlyArray, position?: number): number; + 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 @@ -3680,6 +4172,10 @@ declare module 'fs' { * @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). @@ -3704,7 +4200,11 @@ declare module 'fs' { * @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 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; } @@ -3742,6 +4242,10 @@ declare module 'fs' { * @default true */ force?: boolean; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number; /** * When `true` timestamps from `src` will * be preserved. @@ -3753,6 +4257,11 @@ declare module 'fs' { * @default false */ recursive?: boolean; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; } export interface CopyOptions extends CopyOptionsBase { /** @@ -3779,8 +4288,17 @@ declare module 'fs' { * @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; + 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. @@ -3794,6 +4312,6 @@ declare module 'fs' { */ export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; } -declare module 'node:fs' { - export * from 'fs'; +declare module "node:fs" { + export * from "fs"; } diff --git a/node_modules/@types/node/ts4.8/fs/promises.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/fs/promises.d.ts old mode 100755 new mode 100644 similarity index 76% rename from node_modules/@types/node/ts4.8/fs/promises.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/fs/promises.d.ts index c1667d8..3199063 --- a/node_modules/@types/node/ts4.8/fs/promises.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/fs/promises.d.ts @@ -8,11 +8,13 @@ * 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'; +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, @@ -28,26 +30,30 @@ declare module 'fs/promises' { ReadVResult, RmDirOptions, RmOptions, + StatFsOptions, StatOptions, Stats, + StatsFs, + TimeLike, WatchEventType, WatchOptions, WriteStream, WriteVResult, - } from 'node:fs'; + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; interface FileChangeInfo { eventType: WatchEventType; - filename: T; + filename: T | null; } interface FlagAndOpenMode { mode?: Mode | undefined; flag?: OpenMode | undefined; } - interface FileReadResult { + interface FileReadResult { bytesRead: number; buffer: T; } - interface FileReadOptions { + interface FileReadOptions { /** * @default `Buffer.alloc(0xffff)` */ @@ -75,6 +81,15 @@ declare module 'fs/promises' { 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 { @@ -91,7 +106,13 @@ declare module 'fs/promises' { * @since v10.0.0 * @return Fulfills with `undefined` upon success. */ - appendFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + 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 @@ -108,8 +129,8 @@ declare module 'fs/promises' { */ chmod(mode: Mode): Promise; /** - * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream - * returned by this method has a default `highWaterMark` of 64 kb. + * 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 @@ -127,7 +148,7 @@ declare module 'fs/promises' { * destroyed. Set the `emitClose` option to `false` to change this behavior. * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * const fd = await open('/dev/input/event0'); * // Create a stream from some character device. @@ -153,7 +174,7 @@ declare module 'fs/promises' { * An example to read the last 10 bytes of a file which is 100 bytes long: * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * const fd = await open('sample.txt'); * fd.createReadStream({ start: 90, end: 99 }); @@ -164,11 +185,11 @@ declare module 'fs/promises' { /** * `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`. + * \[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, + * 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. @@ -192,7 +213,7 @@ declare module 'fs/promises' { * device. The specific implementation is operating system and device specific. * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. * @since v10.0.0 - * @return Fufills with `undefined` upon success. + * @return Fulfills with `undefined` upon success. */ sync(): Promise; /** @@ -208,8 +229,38 @@ declare module 'fs/promises' { * 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>; + 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. * @@ -217,7 +268,7 @@ declare module 'fs/promises' { * * 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 + * 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 @@ -228,7 +279,7 @@ declare module 'fs/promises' { options?: { encoding?: null | undefined; flag?: OpenMode | undefined; - } | null + } | null, ): Promise; /** * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. @@ -239,10 +290,10 @@ declare module 'fs/promises' { readFile( options: | { - encoding: BufferEncoding; - flag?: OpenMode | undefined; - } - | BufferEncoding + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding, ): Promise; /** * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. @@ -253,11 +304,27 @@ declare module 'fs/promises' { readFile( options?: | (ObjectEncodingOptions & { - flag?: OpenMode | undefined; - }) + flag?: OpenMode | undefined; + }) | BufferEncoding - | null + | 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. @@ -265,12 +332,12 @@ declare module 'fs/promises' { stat( opts?: StatOptions & { bigint?: false | undefined; - } + }, ): Promise; stat( opts: StatOptions & { bigint: true; - } + }, ): Promise; stat(opts?: StatOptions): Promise; /** @@ -282,7 +349,7 @@ declare module 'fs/promises' { * The following example retains only the first four bytes of the file: * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * let filehandle = null; * try { @@ -303,55 +370,58 @@ declare module 'fs/promises' { */ truncate(len?: number): Promise; /** - * Change the file system timestamps of the object referenced by the `FileHandle` then resolves the promise with no arguments upon success. + * 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: string | number | Date, mtime: string | number | Date): Promise; + utimes(atime: TimeLike, mtime: TimeLike): Promise; /** - * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an - * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or - * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object, or an - * object with an own `toString` function - * property. The promise is resolved with no arguments upon success. + * 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 resolved (or rejected). + * 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) | BufferEncoding | null): Promise; + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & FlagAndOpenMode & Abortable & { flush?: boolean | undefined }) + | BufferEncoding + | null, + ): Promise; /** * Write `buffer` to the file. * - * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. - * - * The promise is resolved with an object containing two properties: + * 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 resolved (or rejected). For this - * scenario, use `fs.createWriteStream()`. + * 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=0] The start position from within `buffer` where the data to write begins. - * @param [length=buffer.byteLength] The number of bytes from `buffer` to write. - * @param position The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. - * See the POSIX pwrite(2) documentation for more detail. + * @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 + position?: number | null, ): Promise<{ bytesWritten: number; buffer: TBuffer; @@ -359,7 +429,7 @@ declare module 'fs/promises' { write( data: string, position?: number | null, - encoding?: BufferEncoding | null + encoding?: BufferEncoding | null, ): Promise<{ bytesWritten: number; buffer: string; @@ -367,32 +437,32 @@ declare module 'fs/promises' { /** * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. * - * The promise is resolved with an object containing a two properties: + * 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 resolved (or rejected). + * 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 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 + * @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: ReadonlyArray, position?: number): Promise; + writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; /** * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s * @since v13.13.0, v12.17.0 - * @param position The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @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: ReadonlyArray, position?: number): Promise; + readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; /** * Closes the file handle after waiting for any pending operation on the handle to * complete. * * ```js - * import { open } from 'fs/promises'; + * import { open } from 'node:fs/promises'; * * let filehandle; * try { @@ -405,24 +475,27 @@ declare module 'fs/promises' { * @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. Check `File access constants` for possible values - * of `mode`. It is possible to create a mask consisting of the bitwise OR of - * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. * - * If the accessibility check is successful, the promise is resolved with no + * 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 } from 'fs/promises'; - * import { constants } from 'fs'; + * import { access, constants } from 'node:fs/promises'; * * try { * await access('/etc/passwd', constants.R_OK | constants.W_OK); @@ -451,14 +524,13 @@ declare module 'fs/promises' { * will be made to remove the destination. * * ```js - * import { constants } from 'fs'; - * import { copyFile } from 'fs/promises'; + * 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.log('The file could not be copied'); + * console.error('The file could not be copied'); * } * * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. @@ -466,7 +538,7 @@ declare module 'fs/promises' { * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); * console.log('source.txt was copied to destination.txt'); * } catch { - * console.log('The file could not be copied'); + * console.error('The file could not be copied'); * } * ``` * @since v10.0.0 @@ -498,7 +570,7 @@ declare module 'fs/promises' { */ function rename(oldPath: PathLike, newPath: PathLike): Promise; /** - * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * 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. @@ -508,7 +580,7 @@ declare module 'fs/promises' { * 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. + * 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 @@ -525,9 +597,22 @@ declare module 'fs/promises' { * 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 + * 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`. */ @@ -535,7 +620,7 @@ declare module 'fs/promises' { path: PathLike, options: MakeDirectoryOptions & { recursive: true; - } + }, ): Promise; /** * Asynchronous mkdir(2) - create a directory. @@ -548,9 +633,9 @@ declare module 'fs/promises' { options?: | Mode | (MakeDirectoryOptions & { - recursive?: false | undefined; - }) - | null + recursive?: false | undefined; + }) + | null, ): Promise; /** * Asynchronous mkdir(2) - create a directory. @@ -567,10 +652,10 @@ declare module 'fs/promises' { * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned * will be passed as `Buffer` objects. * - * If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects. + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. * * ```js - * import { readdir } from 'fs/promises'; + * import { readdir } from 'node:fs/promises'; * * try { * const files = await readdir(path); @@ -587,10 +672,11 @@ declare module 'fs/promises' { path: PathLike, options?: | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - }) + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) | BufferEncoding - | null + | null, ): Promise; /** * Asynchronous readdir(3) - read a directory. @@ -601,10 +687,11 @@ declare module 'fs/promises' { path: PathLike, options: | { - encoding: 'buffer'; - withFileTypes?: false | undefined; - } - | 'buffer' + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", ): Promise; /** * Asynchronous readdir(3) - read a directory. @@ -615,10 +702,11 @@ declare module 'fs/promises' { path: PathLike, options?: | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - }) + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) | BufferEncoding - | null + | null, ): Promise; /** * Asynchronous readdir(3) - read a directory. @@ -629,11 +717,12 @@ declare module 'fs/promises' { path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true; - } + recursive?: boolean | undefined; + }, ): Promise; /** * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is - * resolved with the`linkString` upon success. + * 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 @@ -658,11 +747,14 @@ declare module 'fs/promises' { /** * Creates a symbolic link. * - * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. Windows junction points require the destination path - * to be absolute. When using `'junction'`, the `target` argument will - * automatically be normalized to absolute path. + * 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='file'] + * @param [type='null'] * @return Fulfills with `undefined` upon success. */ function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; @@ -677,13 +769,13 @@ declare module 'fs/promises' { path: PathLike, opts?: StatOptions & { bigint?: false | undefined; - } + }, ): Promise; function lstat( path: PathLike, opts: StatOptions & { bigint: true; - } + }, ): Promise; function lstat(path: PathLike, opts?: StatOptions): Promise; /** @@ -694,15 +786,32 @@ declare module 'fs/promises' { 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 @@ -744,7 +853,7 @@ declare module 'fs/promises' { * @since v14.5.0, v12.19.0 * @return Fulfills with `undefined` upon success. */ - function lutimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; /** * Changes the ownership of a file. * @since v10.0.0 @@ -758,13 +867,13 @@ declare module 'fs/promises' { * * * 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. + * * 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: string | number | Date, mtime: string | number | Date): Promise; + 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. + * 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. * @@ -791,7 +900,10 @@ declare module 'fs/promises' { * @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; + 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 @@ -803,21 +915,23 @@ declare module 'fs/promises' { * object with an `encoding` property specifying the character encoding to use. * * ```js - * import { mkdtemp } from 'fs/promises'; + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; * * try { - * await mkdtemp(path.join(os.tmpdir(), 'foo-')); + * 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 + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing * platform-specific path separator - * (`require('path').sep`). + * (`require('node:path').sep`). * @since v10.0.0 - * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. + * @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; /** @@ -833,7 +947,9 @@ declare module 'fs/promises' { */ 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`, or, an object with an own (not inherited)`toString` function property. + * 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. * @@ -848,15 +964,15 @@ declare module 'fs/promises' { * * 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()`. + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. * * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. * Cancelation is "best effort", and some amount of data is likely still * to be written. * * ```js - * import { writeFile } from 'fs/promises'; - * import { Buffer } from 'buffer'; + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; * * try { * const controller = new AbortController(); @@ -882,14 +998,25 @@ declare module 'fs/promises' { */ function writeFile( file: PathLike | FileHandle, - data: string | NodeJS.ArrayBufferView | Iterable | AsyncIterable | Stream, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, options?: | (ObjectEncodingOptions & { - mode?: Mode | undefined; - flag?: OpenMode | undefined; - } & Abortable) + 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 + | null, ): Promise; /** * Asynchronously append data to a file, creating the file if it does not yet @@ -905,7 +1032,11 @@ declare module 'fs/promises' { * @param path filename or {FileHandle} * @return Fulfills with `undefined` upon success. */ - function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + 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. * @@ -919,11 +1050,25 @@ declare module 'fs/promises' { * 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 'fs/promises'; + * import { readFile } from 'node:fs/promises'; * * try { * const controller = new AbortController(); @@ -952,10 +1097,10 @@ declare module 'fs/promises' { path: PathLike | FileHandle, options?: | ({ - encoding?: null | undefined; - flag?: OpenMode | undefined; - } & Abortable) - | null + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, ): Promise; /** * Asynchronously reads the entire contents of a file. @@ -968,10 +1113,10 @@ declare module 'fs/promises' { path: PathLike | FileHandle, options: | ({ - encoding: BufferEncoding; - flag?: OpenMode | undefined; - } & Abortable) - | BufferEncoding + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, ): Promise; /** * Asynchronously reads the entire contents of a file. @@ -983,12 +1128,15 @@ declare module 'fs/promises' { function readFile( path: PathLike | FileHandle, options?: - | (ObjectEncodingOptions & - Abortable & { - flag?: OpenMode | undefined; - }) + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) | BufferEncoding - | null + | 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. @@ -1002,7 +1150,7 @@ declare module 'fs/promises' { * Example using async iteration: * * ```js - * import { opendir } from 'fs/promises'; + * import { opendir } from 'node:fs/promises'; * * try { * const dir = await opendir('./'); @@ -1023,7 +1171,7 @@ declare module 'fs/promises' { * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. * * ```js - * const { watch } = require('fs/promises'); + * const { watch } = require('node:fs/promises'); * * const ac = new AbortController(); * const { signal } = ac; @@ -1046,16 +1194,16 @@ declare module 'fs/promises' { * disappears in the directory. * * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. - * @since v15.9.0 + * @since v15.9.0, v14.18.0 * @return of objects with the properties: */ function watch( filename: PathLike, options: | (WatchOptions & { - encoding: 'buffer'; - }) - | 'buffer' + encoding: "buffer"; + }) + | "buffer", ): AsyncIterable>; /** * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. @@ -1074,7 +1222,10 @@ declare module 'fs/promises' { * 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>; + function watch( + filename: PathLike, + options: WatchOptions | string, + ): AsyncIterable> | AsyncIterable>; /** * Asynchronously copies the entire directory structure from `src` to `dest`, * including subdirectories and files. @@ -1089,6 +1240,6 @@ declare module 'fs/promises' { */ function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; } -declare module 'node:fs/promises' { - export * from 'fs/promises'; +declare module "node:fs/promises" { + export * from "fs/promises"; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/globals.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..4bdf964 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/globals.d.ts @@ -0,0 +1,503 @@ +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 _MessageEvent = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").MessageEvent; +type _RequestInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").RequestInit; +type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").ResponseInit; +// #endregion Fetch and friends + +// #region DOMException +type _DOMException = typeof globalThis extends { onmessage: any } ? {} : NodeDOMException; +interface NodeDOMException extends Error { + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + /** [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; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; +} +interface NodeDOMExceptionConstructor { + prototype: DOMException; + new(message?: string, nameOrOptions?: string | { name?: string; cause?: unknown }): DOMException; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; +} +// #endregion DOMException + +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; + any(signals: AbortSignal[]): 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; + + // #region DOMException + /** + * @since v17.0.0 + * An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) + */ + interface DOMException extends _DOMException {} + + /** + * @since v17.0.0 + * + * The WHATWG `DOMException` class. See [DOMException](https://developer.mozilla.org/docs/Web/API/DOMException) for more details. + */ + var DOMException: typeof globalThis extends { onmessage: any; DOMException: infer T } ? T + : NodeDOMExceptionConstructor; + // #endregion DOMException + + /*----------------------------------------------* + * * + * 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 MessageEvent extends _MessageEvent {} + /** + * @since v15.0.0 + */ + var MessageEvent: typeof globalThis extends { + onmessage: any; + MessageEvent: infer T; + } ? T + : typeof import("undici-types").MessageEvent; +} diff --git a/node_modules/@types/node/globals.global.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/globals.global.d.ts old mode 100755 new mode 100644 similarity index 100% rename from node_modules/@types/node/globals.global.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/globals.global.d.ts diff --git a/node_modules/@types/node/ts4.8/http.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/http.d.ts old mode 100755 new mode 100644 similarity index 59% rename from node_modules/@types/node/ts4.8/http.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/http.d.ts index 4a37bb0..a1018ee --- a/node_modules/@types/node/ts4.8/http.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/http.d.ts @@ -1,5 +1,5 @@ /** - * To use the HTTP server and client one must `require('http')`. + * 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. @@ -9,12 +9,12 @@ * * HTTP message headers are represented by an object like this: * - * ```js - * { 'content-length': '123', - * 'content-type': 'text/plain', - * 'connection': 'keep-alive', - * 'host': 'mysite.com', - * 'accept': '*' } + * ```json + * { "content-length": "123", + * "content-type": "text/plain", + * "connection": "keep-alive", + * "host": "example.com", + * "accept": "*" } * ``` * * Keys are lowercased. Values are not modified. @@ -26,50 +26,52 @@ * * 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: + * 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', 'mysite.com', + * 'Host', 'example.com', * 'accepT', '*' ] * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/http.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/http.js) */ -declare module 'http' { - import * as stream from 'node:stream'; - import { URL } from 'node:url'; - import { TcpSocketConnectOpts, Socket, Server as NetServer, LookupFunction } from 'node:net'; +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; + "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; + "alt-svc"?: string | undefined; authorization?: string | undefined; - 'cache-control'?: 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; + "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; @@ -78,91 +80,217 @@ declare module 'http' { 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; + "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; + "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; + "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; + "transfer-encoding"?: string | undefined; upgrade?: string | undefined; - 'user-agent'?: string | undefined; + "user-agent"?: string | undefined; vary?: string | undefined; via?: string | undefined; warning?: string | undefined; - 'www-authenticate'?: 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 {} + 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 { - signal?: AbortSignal | undefined; - protocol?: string | null | undefined; + _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; - family?: number | undefined; - port?: number | string | null | undefined; - defaultPort?: number | string | undefined; + insecureHTTPParser?: boolean | undefined; localAddress?: string | undefined; - socketPath?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; /** - * @default 8192 + * @default 16384 */ maxHeaderSize?: number | undefined; method?: string | undefined; path?: string | null | undefined; - headers?: OutgoingHttpHeaders | undefined; - auth?: string | null | undefined; - agent?: Agent | boolean | undefined; - _defaultAgent?: Agent | undefined; - timeout?: number | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; setHost?: boolean | undefined; - // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 - createConnection?: - | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) - | undefined; - lookup?: LookupFunction | 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; /** - * 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 8192 + * 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 */ - maxHeaderSize?: number | undefined; + requestTimeout?: number | undefined; /** - * Use an insecure HTTP parser that accepts invalid HTTP headers when true. + * 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 false + * @default true * @since v16.5.0 */ noDelay?: boolean | undefined; @@ -179,6 +307,11 @@ declare module 'http' { * @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, @@ -241,14 +374,12 @@ declare module 'http' { * Limit the amount of time the parser will wait to receive the complete HTTP * headers. * - * In case of inactivity, the rules defined in `server.timeout` apply. However, - * that inactivity based timeout would still allow the connection to be kept open - * if the headers are being sent very slowly (by default, up to a byte per 2 - * minutes). In order to prevent this, whenever header data arrives an additional - * check is made that more than `server.headersTimeout` milliseconds has not - * passed since the connection was established. If the check fails, a `'timeout'`event is emitted on the server object, and (by default) the socket is destroyed. - * See `server.timeout` for more information on how timeout behavior can be - * customized. + * 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; @@ -256,7 +387,7 @@ declare module 'http' { * 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`. + * 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. @@ -281,112 +412,135 @@ declare module 'http' { * @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: "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', + event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, ): this; - addListener(event: 'request', listener: RequestListener): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; addListener( - event: 'upgrade', + 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: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; emit( - event: 'checkContinue', + event: "checkContinue", req: InstanceType, res: InstanceType & { req: InstanceType }, ): boolean; emit( - event: 'checkExpectation', + 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: "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', + event: "request", req: InstanceType, res: InstanceType & { req: InstanceType }, ): boolean; - emit(event: 'upgrade', req: InstanceType, socket: stream.Duplex, head: Buffer): 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: 'request', listener: RequestListener): this; - on(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => 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: "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', + event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, ): this; - once(event: 'request', listener: RequestListener): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; once( - event: 'upgrade', + 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: "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', + event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, ): this; - prependListener(event: 'request', listener: RequestListener): this; prependListener( - event: 'upgrade', + 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: "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', + event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, ): this; - prependOnceListener(event: 'request', listener: RequestListener): this; prependOnceListener( - event: 'upgrade', + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, ): this; } /** - * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from - * the perspective of the participants of HTTP transaction. + * 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 { @@ -405,9 +559,9 @@ declare module 'http' { */ readonly headersSent: boolean; /** - * Aliases of `outgoingMessage.socket` + * Alias of `outgoingMessage.socket`. * @since v0.3.0 - * @deprecated Since v15.12.0 - Use `socket` instead. + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. */ readonly connection: Socket | null; /** @@ -420,21 +574,39 @@ declare module 'http' { 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. + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. * @since v0.9.12 * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. */ setTimeout(msecs: number, callback?: () => void): this; /** - * Sets a single header value for the header object. + * 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 | ReadonlyArray): this; + setHeader(name: string, value: number | string | readonly string[]): this; /** - * Gets the value of HTTP header with the given name. If such a name doesn't - * exist in message, it will be `undefined`. + * 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 */ @@ -447,8 +619,8 @@ declare module 'http' { * 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()`, + * 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 @@ -458,13 +630,13 @@ declare module 'http' { * const headers = outgoingMessage.getHeaders(); * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } * ``` - * @since v8.0.0 + * @since v7.7.0 */ getHeaders(): OutgoingHttpHeaders; /** - * Returns an array of names of headers of the outgoing outgoingMessage. All - * names are lowercase. - * @since v8.0.0 + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 */ getHeaderNames(): string[]; /** @@ -474,7 +646,7 @@ declare module 'http' { * ```js * const hasContentType = outgoingMessage.hasHeader('content-type'); * ``` - * @since v8.0.0 + * @since v7.7.0 */ hasHeader(name: string): boolean; /** @@ -484,16 +656,17 @@ declare module 'http' { * outgoingMessage.removeHeader('Content-Encoding'); * ``` * @since v0.4.0 + * @param name Header name */ removeHeader(name: string): void; /** * Adds HTTP trailers (headers but at the end of the message) to the message. * - * Trailers are **only** be emitted if the message is chunked encoded. If not, - * the trailer will be silently discarded. + * 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 fields in its value, e.g. + * with a list of header field names in its value, e.g. * * ```js * message.writeHead(200, { 'Content-Type': 'text/plain', @@ -509,7 +682,7 @@ declare module 'http' { */ addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; /** - * Compulsorily flushes the message headers + * 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 @@ -517,7 +690,7 @@ declare module 'http' { * packet. * * It is usually desired (it saves a TCP round-trip), but not when the first - * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. * @since v1.6.0 */ flushHeaders(): void; @@ -557,15 +730,56 @@ declare module 'http' { * @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 a HTTP/1.1 100 Continue message to the client, indicating that - * the request body should be sent. See the `'checkContinue'` event on`Server`. + * 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. @@ -584,7 +798,7 @@ declare module 'http' { * response * .writeHead(200, { * 'Content-Length': Buffer.byteLength(body), - * 'Content-Type': 'text/plain' + * 'Content-Type': 'text/plain', * }) * .end(body); * ``` @@ -615,12 +829,12 @@ declare module 'http' { * }); * ``` * - * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js - * does not check whether `Content-Length` and the length of the body which has + * `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 `TypeError` being thrown. + * will result in a \[`Error`\]\[\] being thrown. * @since v0.1.30 */ writeHead( @@ -648,10 +862,10 @@ declare module 'http' { /** * 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 + * 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 + * 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}. * @@ -667,10 +881,13 @@ declare module 'http' { * 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. + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. * - * Node.js does not check whether Content-Length and the length of the - * body which has been transmitted are equal or not. + * 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 { @@ -678,6 +895,7 @@ declare module 'http' { * 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; /** @@ -691,13 +909,58 @@ declare module 'http' { */ protocol: string; /** - * Whether the request is send through a reused socket. + * 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. - * @default 2000 */ maxHeadersCount: number; constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); @@ -747,109 +1010,124 @@ declare module 'http' { * const headerNames = request.getRawHeaderNames(); * // headerNames === ['Foo', 'Set-Cookie'] * ``` - * @since v15.13.0 + * @since v15.13.0, v14.17.0 */ getRawHeaderNames(): string[]; - addListener(event: 'abort', listener: () => void): this; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; addListener( - event: 'connect', + 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: "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', + 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: "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; - 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; + /** + * @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; - 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; + /** + * @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; - prependListener(event: 'abort', listener: () => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; prependListener( - event: 'connect', + 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: "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', + 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: "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; - prependOnceListener(event: 'abort', listener: () => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; prependOnceListener( - event: 'connect', + 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: "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', + 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: "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. + * 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 + * 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 @@ -860,6 +1138,7 @@ declare module 'http' { * 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; /** @@ -867,7 +1146,7 @@ declare module 'http' { * 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. + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. * @since v0.1.1 */ httpVersion: string; @@ -884,7 +1163,7 @@ declare module 'http' { * const req = http.request({ * host: '127.0.0.1', * port: 8080, - * method: 'POST' + * method: 'POST', * }, (res) => { * res.resume(); * res.on('end', () => { @@ -911,7 +1190,7 @@ declare module 'http' { * * 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`. + * type other than `net.Socket` or internally nulled. * @since v0.3.0 */ socket: Socket; @@ -932,14 +1211,32 @@ declare module 'http' { * 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. + * * 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 ', '. + * * 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. * @@ -970,6 +1267,13 @@ declare module 'http' { * @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. @@ -1002,29 +1306,32 @@ declare module 'http' { * To parse the URL into its parts: * * ```js - * new URL(request.url, `http://${request.headers.host}`); + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); * ``` * - * When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`: + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: * * ```console * $ node - * > new URL(request.url, `http://${request.headers.host}`) + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); * URL { - * href: 'http://localhost:3000/status?name=ryan', - * origin: 'http://localhost:3000', + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', * protocol: 'http:', * username: '', * password: '', - * host: 'localhost:3000', + * host: 'localhost', * hostname: 'localhost', - * port: '3000', + * port: '', * pathname: '/status', * search: '?name=ryan', * searchParams: URLSearchParams { 'name' => 'ryan' }, * hash: '' * } * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. * @since v0.1.90 */ url?: string | undefined; @@ -1043,7 +1350,7 @@ declare module 'http' { */ 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 + * 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 */ @@ -1079,7 +1386,7 @@ declare module 'http' { * Scheduling strategy to apply when picking the next free socket to use. * @default `lifo` */ - scheduling?: 'fifo' | 'lifo' | undefined; + scheduling?: "fifo" | "lifo" | undefined; } /** * An `Agent` is responsible for managing connection persistence @@ -1087,7 +1394,7 @@ declare module 'http' { * 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`. + * 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 @@ -1118,7 +1425,7 @@ declare module 'http' { * }); * ``` * - * 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 + * 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. * @@ -1129,16 +1436,27 @@ declare module 'http' { * hostname: 'localhost', * port: 80, * path: '/', - * agent: false // Create a new agent just for this one request + * agent: false, // Create a new agent just for this one request * }, (res) => { * // Do stuff with response * }); * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v20.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * const http = require('node:http'); + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` * @since v0.3.4 */ - class Agent { + class Agent extends EventEmitter { /** - * By default set to 256\. For agents with `keepAlive` enabled, this + * 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 @@ -1200,6 +1518,37 @@ declare module 'http' { * * 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< @@ -1209,18 +1558,23 @@ declare module 'http' { function createServer< Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse = typeof ServerResponse, - >(options: ServerOptions, requestListener?: RequestListener): Server; + >( + 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. + * 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. @@ -1229,10 +1583,11 @@ declare module 'http' { * upload a file with a POST request, then write to the `ClientRequest` object. * * ```js - * const http = require('http'); + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; * * const postData = JSON.stringify({ - * 'msg': 'Hello World!' + * 'msg': 'Hello World!', * }); * * const options = { @@ -1242,8 +1597,8 @@ declare module 'http' { * method: 'POST', * headers: { * 'Content-Type': 'application/json', - * 'Content-Length': Buffer.byteLength(postData) - * } + * 'Content-Length': Buffer.byteLength(postData), + * }, * }; * * const req = http.request(options, (res) => { @@ -1319,7 +1674,7 @@ declare module 'http' { * the following events will be emitted in the following order: * * * `'socket'` - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'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, @@ -1330,15 +1685,15 @@ declare module 'http' { * * `'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'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` * * `'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'` + * * `'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 @@ -1346,7 +1701,7 @@ declare module 'http' { * * * `'socket'` * * (`req.destroy()` called here) - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'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 @@ -1357,8 +1712,8 @@ declare module 'http' { * * `'data'` any number of times, on the `res` object * * (`req.destroy()` called here) * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. * * `'close'` + * * `'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'` on the `res` object * * If `req.abort()` is called before a socket is assigned, the following @@ -1374,7 +1729,7 @@ declare module 'http' { * * `'socket'` * * (`req.abort()` called here) * * `'abort'` - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'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 @@ -1386,15 +1741,16 @@ declare module 'http' { * * (`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'`. + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. * * `'close'` * * `'close'` on the `res` object * * Setting the `timeout` option or using the `setTimeout()` function will * not abort the request or do anything besides add a `'timeout'` event. * - * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the - * request itself. + * 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; @@ -1405,8 +1761,8 @@ declare module 'http' { ): ClientRequest; /** * Since most requests are GET requests without bodies, Node.js provides this - * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the - * response + * 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}. @@ -1454,36 +1810,92 @@ declare module 'http' { * const server = http.createServer((req, res) => { * res.writeHead(200, { 'Content-Type': 'application/json' }); * res.end(JSON.stringify({ - * data: 'Hello World!' + * data: 'Hello World!', * })); * }); * * server.listen(8000); * ``` * @since v0.3.6 - * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored. + * @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'`. - * @param name Header name + * 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'`. + * 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 - * @since v14.3.0 */ 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; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ let globalAgent: Agent; /** * Read-only property specifying the maximum allowed size of HTTP headers in bytes. @@ -1491,6 +1903,6 @@ declare module 'http' { */ const maxHeaderSize: number; } -declare module 'node:http' { - export * from 'http'; +declare module "node:http" { + export * from "http"; } diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/http2.d.ts old mode 100755 new mode 100644 similarity index 66% rename from node_modules/@types/node/http2.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/http2.d.ts index f46a33e..5212c9b --- a/node_modules/@types/node/http2.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/http2.d.ts @@ -1,30 +1,35 @@ /** - * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It - * can be accessed using: + * 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('http2'); + * const http2 = require('node:http2'); * ``` * @since v8.4.0 - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/http2.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/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, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http'; - export { OutgoingHttpHeaders } from 'node:http'; +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; + ":status"?: number | undefined; } export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { - ':path'?: string | undefined; - ':method'?: string | undefined; - ':authority'?: string | undefined; - ':scheme'?: string | undefined; + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; } // Http2Stream export interface StreamPriorityOptions { @@ -50,6 +55,7 @@ declare module 'http2' { 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; @@ -83,14 +89,14 @@ declare module 'http2' { */ readonly destroyed: boolean; /** - * Set the `true` if the `END_STREAM` flag was set in the request or response + * 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. + * 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; @@ -103,7 +109,7 @@ declare module 'http2' { /** * 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. + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. * @since v8.4.0 */ readonly rstCode: number; @@ -128,9 +134,9 @@ declare module 'http2' { * value will be `undefined` after the `Http2Stream` instance is destroyed. * @since v8.4.0 */ - readonly session: Http2Session; + readonly session: Http2Session | undefined; /** - * Provides miscellaneous information about the current state of the`Http2Stream`. + * Provides miscellaneous information about the current state of the `Http2Stream`. * * A current state of this `Http2Stream`. * @since v8.4.0 @@ -151,7 +157,7 @@ declare module 'http2' { priority(options: StreamPriorityOptions): void; /** * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const client = http2.connect('http://example.org:8000'); * const { NGHTTP2_CANCEL } = http2.constants; * const req = client.request({ ':path': '/' }); @@ -171,7 +177,7 @@ declare module 'http2' { * trailers can be sent. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond(undefined, { waitForTrailers: true }); @@ -187,127 +193,157 @@ declare module 'http2' { * @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: "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: "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: "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: "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: "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: "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: "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: "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: "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: "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: "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: "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 { @@ -319,7 +355,7 @@ declare module 'http2' { /** * 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`. + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. * @since v8.4.0 */ readonly pushAllowed: boolean; @@ -329,10 +365,10 @@ declare module 'http2' { */ 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. + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond({ ':status': 200 }); @@ -346,18 +382,25 @@ declare module 'http2' { * ``` * * 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. + * 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; + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; /** * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond({ ':status': 200 }); @@ -365,16 +408,15 @@ declare module 'http2' { * }); * ``` * - * 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. + * 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`. + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respond({ ':status': 200 }, { waitForTrailers: true }); @@ -397,8 +439,8 @@ declare module 'http2' { * automatically. * * ```js - * const http2 = require('http2'); - * const fs = require('fs'); + * const http2 = require('node:http2'); + * const fs = require('node:fs'); * * const server = http2.createServer(); * server.on('stream', (stream) => { @@ -408,7 +450,7 @@ declare module 'http2' { * const headers = { * 'content-length': stat.size, * 'last-modified': stat.mtime.toUTCString(), - * 'content-type': 'text/plain; charset=utf-8' + * 'content-type': 'text/plain; charset=utf-8', * }; * stream.respondWithFD(fd, headers); * stream.on('close', () => fs.closeSync(fd)); @@ -417,7 +459,7 @@ declare module 'http2' { * * 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 + * 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 @@ -436,11 +478,11 @@ declare module 'http2' { * 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`. + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. * * ```js - * const http2 = require('http2'); - * const fs = require('fs'); + * const http2 = require('node:http2'); + * const fs = require('node:fs'); * * const server = http2.createServer(); * server.on('stream', (stream) => { @@ -450,7 +492,7 @@ declare module 'http2' { * const headers = { * 'content-length': stat.size, * 'last-modified': stat.mtime.toUTCString(), - * 'content-type': 'text/plain; charset=utf-8' + * 'content-type': 'text/plain; charset=utf-8', * }; * stream.respondWithFD(fd, headers, { waitForTrailers: true }); * stream.on('wantTrailers', () => { @@ -463,7 +505,11 @@ declare module 'http2' { * @since v8.4.0 * @param fd A readable file descriptor. */ - respondWithFD(fd: number | fs.promises.FileHandle, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + 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. @@ -475,14 +521,14 @@ declare module 'http2' { * 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 + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. If the `onError` callback is * defined, then it will be called. Otherwise * the stream will be destroyed. * * Example using a file path: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * function statCheck(stat, headers) { @@ -500,7 +546,7 @@ declare module 'http2' { * } * } catch (err) { * // Perform actual error handling. - * console.log(err); + * console.error(err); * } * stream.end(); * } @@ -513,10 +559,10 @@ declare module 'http2' { * * 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: + * results to determine if the file has been modified to return an appropriate `304` response: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * function statCheck(stat, headers) { @@ -549,7 +595,7 @@ declare module 'http2' { * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer(); * server.on('stream', (stream) => { * stream.respondWithFile('/some/file', @@ -562,7 +608,11 @@ declare module 'http2' { * ``` * @since v8.4.0 */ - respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; } // Http2Session export interface Settings { @@ -597,18 +647,18 @@ declare module 'http2' { /** * 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. + * 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`. + * 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. + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. * @since v10.0.0 */ readonly connecting: boolean; @@ -627,7 +677,7 @@ declare module 'http2' { */ 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. + * 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; @@ -642,7 +692,7 @@ declare module 'http2' { 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. + * 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; @@ -672,7 +722,7 @@ declare module 'http2' { */ readonly state: SessionState; /** - * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * 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 @@ -689,11 +739,11 @@ declare module 'http2' { */ close(callback?: () => void): void; /** - * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * 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. + * 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. + * 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`. @@ -709,17 +759,17 @@ declare module 'http2' { 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. + * 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. + * 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 + * 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. + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. * * ```js * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { @@ -736,9 +786,12 @@ declare module 'http2' { * @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; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: Buffer) => void, + ): boolean; /** - * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. * @since v9.4.0 */ ref(): void; @@ -748,7 +801,7 @@ declare module 'http2' { * the delta. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * const server = http2.createServer(); * const expectedWindowSize = 2 ** 20; @@ -758,7 +811,7 @@ declare module 'http2' { * session.setLocalWindowSize(expectedWindowSize); * }); * ``` - * @since v15.3.0 + * @since v15.3.0, v14.18.0 */ setLocalWindowSize(windowSize: number): void; /** @@ -769,9 +822,9 @@ declare module 'http2' { */ 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. + * 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 + * 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 @@ -780,80 +833,106 @@ declare module 'http2' { * @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; + 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: "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: "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: "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: "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: "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: "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 + * 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. * - * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const clientSession = http2.connect('https://localhost:1234'); * const { * HTTP2_HEADER_PATH, - * HTTP2_HEADER_STATUS + * HTTP2_HEADER_STATUS, * } = http2.constants; * * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); @@ -883,35 +962,87 @@ declare module 'http2' { * @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: "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: ReadonlyArray): 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: "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: "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: "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: "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: "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 { @@ -923,7 +1054,7 @@ declare module 'http2' { * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * const server = http2.createServer(); * server.on('session', (session) => { @@ -964,7 +1095,7 @@ declare module 'http2' { * authoritative responses. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const options = getSecureOptionsSomehow(); * const server = http2.createSecureServer(options); * server.on('stream', (stream) => { @@ -977,7 +1108,7 @@ declare module 'http2' { * ``` * * 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 + * 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. * @@ -990,7 +1121,7 @@ declare module 'http2' { * server using the `http2.createSecureServer()` method: * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const options = getSecureOptionsSomehow(); * options.origins = ['https://example.com', 'https://example.org']; * const server = http2.createSecureServer(options); @@ -1007,27 +1138,54 @@ declare module 'http2' { | string | url.URL | { - origin: string; - } + 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: "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: "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: "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: "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: "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: "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 @@ -1040,6 +1198,7 @@ declare module 'http2' { 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 @@ -1048,12 +1207,11 @@ declare module 'http2' { */ unknownProtocolTimeout?: number | undefined; selectPadding?(frameLen: number, maxFrameLen: number): number; - createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; } export interface ClientSessionOptions extends SessionOptions { maxReservedRemoteStreams?: number | undefined; createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; - protocol?: 'http:' | 'https:' | undefined; + protocol?: "http:" | "https:" | undefined; } export interface ServerSessionOptions extends SessionOptions { Http1IncomingMessage?: typeof IncomingMessage | undefined; @@ -1077,97 +1235,175 @@ declare module 'http2' { 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: "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: "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: "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: "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: "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: "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: "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: "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: "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: "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: "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: "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; } /** @@ -1177,7 +1413,12 @@ declare module 'http2' { * @since v8.4.0 */ export class Http2ServerRequest extends stream.Readable { - constructor(stream: ServerHttp2Stream, headers: IncomingHttpHeaders, options: stream.ReadableOptions, rawHeaders: ReadonlyArray); + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); /** * The `request.aborted` property will be `true` if the request has * been aborted. @@ -1186,7 +1427,7 @@ declare module 'http2' { 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']`. + * 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; @@ -1233,9 +1474,9 @@ declare module 'http2' { 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'`. + * 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. + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. * @since v8.4.0 */ readonly httpVersion: string; @@ -1290,11 +1531,11 @@ declare module 'http2' { * `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`. + * `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 + * `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, @@ -1357,53 +1598,53 @@ declare module 'http2' { * 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 + * 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: "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: "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: "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: "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: "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: "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; } /** @@ -1419,6 +1660,28 @@ declare module 'http2' { * @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`. @@ -1432,7 +1695,7 @@ declare module 'http2' { */ readonly headersSent: boolean; /** - * A reference to the original HTTP2 request object. + * A reference to the original HTTP2 `request` object. * @since v15.7.0 */ readonly req: Http2ServerRequest; @@ -1443,17 +1706,17 @@ declare module 'http2' { * `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`. + * `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 + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for * more information. * * All other interactions will be routed directly to the socket. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const server = http2.createServer((req, res) => { * const ip = req.socket.remoteAddress; * const port = req.socket.remotePort; @@ -1496,7 +1759,7 @@ declare module 'http2' { * an empty string. * @since v8.4.0 */ - statusMessage: ''; + statusMessage: ""; /** * This method adds HTTP trailing headers (a header but at the end of the * message) to the response. @@ -1551,7 +1814,7 @@ declare module 'http2' { * 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()`, + * 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_. * @@ -1617,7 +1880,7 @@ declare module 'http2' { * ``` * @since v8.4.0 */ - setHeader(name: string, value: number | string | ReadonlyArray): void; + 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 @@ -1625,7 +1888,7 @@ declare module 'http2' { * * 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. + * 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; @@ -1636,8 +1899,8 @@ declare module 'http2' { * This sends a chunk of the response body. This method may * be called multiple times to provide successive parts of the body. * - * In the `http` module, the response body is omitted when the - * request is a HEAD request. Similarly, the `204` and `304` responses_must not_ include a message body. + * 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. @@ -1661,10 +1924,35 @@ declare module 'http2' { 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`. + * 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. @@ -1687,7 +1975,7 @@ declare module 'http2' { * `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. + * 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. * @@ -1724,48 +2012,51 @@ declare module 'http2' { * @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; + 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: "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: "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: "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: "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: "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 { @@ -1826,7 +2117,13 @@ declare module 'http2' { 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; @@ -1984,7 +2281,7 @@ declare module 'http2' { */ 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 + * 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 */ @@ -1995,7 +2292,7 @@ declare module 'http2' { * for use with the `HTTP2-Settings` header field. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * const packed = http2.getPackedSettings({ enablePush: false }); * @@ -2013,14 +2310,14 @@ declare module 'http2' { */ export function getUnpackedSettings(buf: Uint8Array): Settings; /** - * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. * * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when * communicating * with browser clients. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * * // Create an unencrypted HTTP/2 server. * // Since there are no browsers known that support @@ -2031,28 +2328,33 @@ declare module 'http2' { * server.on('stream', (stream, headers) => { * stream.respond({ * 'content-type': 'text/html; charset=utf-8', - * ':status': 200 + * ':status': 200, * }); * stream.end('

Hello World

'); * }); * - * server.listen(80); + * 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; + 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. + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. * * ```js - * const http2 = require('http2'); - * const fs = require('fs'); + * const http2 = require('node:http2'); + * const fs = require('node:fs'); * * const options = { * key: fs.readFileSync('server-key.pem'), - * cert: fs.readFileSync('server-cert.pem') + * cert: fs.readFileSync('server-cert.pem'), * }; * * // Create a secure HTTP/2 server @@ -2061,23 +2363,28 @@ declare module 'http2' { * server.on('stream', (stream, headers) => { * stream.respond({ * 'content-type': 'text/html; charset=utf-8', - * ':status': 200 + * ':status': 200, * }); * stream.end('

Hello World

'); * }); * - * server.listen(80); + * 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; + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer( + options: SecureServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; /** * Returns a `ClientHttp2Session` instance. * * ```js - * const http2 = require('http2'); + * const http2 = require('node:http2'); * const client = http2.connect('https://localhost:1234'); * * // Use the client @@ -2089,13 +2396,23 @@ declare module 'http2' { * 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, + 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 + 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'; +declare module "node:http2" { + export * from "http2"; } diff --git a/node_modules/@types/node/https.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/https.d.ts old mode 100755 new mode 100644 similarity index 71% rename from node_modules/@types/node/https.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/https.d.ts index 9514866..76c6d73 --- a/node_modules/@types/node/https.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/https.d.ts @@ -1,19 +1,22 @@ /** * 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/v16.9.0/lib/https.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/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'; +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 & { + type RequestOptions = + & http.RequestOptions + & tls.SecureContextOptions + & { + checkServerIdentity?: typeof tls.checkServerIdentity | undefined; rejectUnauthorized?: boolean | undefined; // Defaults to true servername?: string | undefined; // SNI TLS Extension }; @@ -46,14 +49,24 @@ declare module 'https' { 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: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; addListener( - event: 'newSession', + event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, ): this; addListener( - event: 'OCSPRequest', + event: "OCSPRequest", listener: ( certificate: Buffer, issuer: Buffer, @@ -61,74 +74,80 @@ declare module 'https' { ) => void, ): this; addListener( - event: 'resumeSession', + 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: "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', + event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, ): this; - addListener(event: 'request', listener: http.RequestListener): this; + addListener(event: "request", listener: http.RequestListener): this; addListener( - event: 'upgrade', + 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: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; emit( - event: 'newSession', + event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void, ): boolean; emit( - event: 'OCSPRequest', + 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: "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', + event: "checkContinue", req: InstanceType, - res: InstanceType & { req: InstanceType }, + res: InstanceType & { + req: InstanceType; + }, ): boolean; emit( - event: 'checkExpectation', + event: "checkExpectation", req: InstanceType, - res: InstanceType & { 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: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: Buffer): boolean; emit( - event: 'request', + event: "request", req: InstanceType, - res: InstanceType & { req: InstanceType }, + res: InstanceType & { + req: InstanceType; + }, ): boolean; - emit(event: 'upgrade', req: InstanceType, socket: Duplex, head: Buffer): 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: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; on( - event: 'newSession', + event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, ): this; on( - event: 'OCSPRequest', + event: "OCSPRequest", listener: ( certificate: Buffer, issuer: Buffer, @@ -136,29 +155,29 @@ declare module 'https' { ) => void, ): this; on( - event: 'resumeSession', + 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; + 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: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; once( - event: 'newSession', + event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, ): this; once( - event: 'OCSPRequest', + event: "OCSPRequest", listener: ( certificate: Buffer, issuer: Buffer, @@ -166,29 +185,29 @@ declare module 'https' { ) => void, ): this; once( - event: 'resumeSession', + 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; + 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: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; prependListener( - event: 'newSession', + event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, ): this; prependListener( - event: 'OCSPRequest', + event: "OCSPRequest", listener: ( certificate: Buffer, issuer: Buffer, @@ -196,35 +215,35 @@ declare module 'https' { ) => void, ): this; prependListener( - event: 'resumeSession', + 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: "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', + event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, ): this; - prependListener(event: 'request', listener: http.RequestListener): this; + prependListener(event: "request", listener: http.RequestListener): this; prependListener( - event: 'upgrade', + 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: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; prependOnceListener( - event: 'newSession', + event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, ): this; prependOnceListener( - event: 'OCSPRequest', + event: "OCSPRequest", listener: ( certificate: Buffer, issuer: Buffer, @@ -232,37 +251,37 @@ declare module 'https' { ) => void, ): this; prependOnceListener( - event: 'resumeSession', + 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: "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', + event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, ): this; - prependOnceListener(event: 'request', listener: http.RequestListener): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; prependOnceListener( - event: 'upgrade', + event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, ): this; } /** * ```js * // curl -k https://localhost:8000/ - * const https = require('https'); - * const fs = require('fs'); + * const 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') + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), * }; * * https.createServer(options, (req, res) => { @@ -274,12 +293,12 @@ declare module 'https' { * Or * * ```js - * const https = require('https'); - * const fs = require('fs'); + * const https = require('node:https'); + * const fs = require('node:fs'); * * const options = { * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), - * passphrase: 'sample' + * passphrase: 'sample', * }; * * https.createServer(options, (req, res) => { @@ -305,8 +324,8 @@ declare module 'https' { /** * 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`. + * 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. @@ -315,13 +334,13 @@ declare module 'https' { * upload a file with a POST request, then write to the `ClientRequest` object. * * ```js - * const https = require('https'); + * const https = require('node:https'); * * const options = { * hostname: 'encrypted.google.com', * port: 443, * path: '/', - * method: 'GET' + * method: 'GET', * }; * * const req = https.request(options, (res) => { @@ -348,7 +367,7 @@ declare module 'https' { * path: '/', * method: 'GET', * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), - * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), * }; * options.agent = new https.Agent(options); * @@ -367,7 +386,7 @@ declare module 'https' { * method: 'GET', * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), - * agent: false + * agent: false, * }; * * const req = https.request(options, (res) => { @@ -388,9 +407,9 @@ declare module 'https' { * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): * * ```js - * const tls = require('tls'); - * const https = require('https'); - * const crypto = require('crypto'); + * 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'); @@ -407,7 +426,7 @@ declare module 'https' { * return err; * } * - * // Pin the public key, similar to HPKP pin-sha25 pinning + * // 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: ' + @@ -498,7 +517,7 @@ declare module 'https' { * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. * * ```js - * const https = require('https'); + * const https = require('node:https'); * * https.get('https://encrypted.google.com/', (res) => { * console.log('statusCode:', res.statusCode); @@ -526,6 +545,6 @@ declare module 'https' { ): http.ClientRequest; let globalAgent: Agent; } -declare module 'node:https' { - export * from 'https'; +declare module "node:https" { + export * from "https"; } diff --git a/node_modules/@types/node/ts4.8/index.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/index.d.ts old mode 100755 new mode 100644 similarity index 95% rename from node_modules/@types/node/ts4.8/index.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/index.d.ts index cb60f9a..f043abe --- a/node_modules/@types/node/ts4.8/index.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/index.d.ts @@ -22,7 +22,7 @@ * IN THE SOFTWARE. */ -// NOTE: These definitions support NodeJS and TypeScript 4.8 and earlier +// NOTE: These definitions support NodeJS and TypeScript 4.9+. // Reference required types from the default lib: /// @@ -47,6 +47,7 @@ /// /// /// +/// /// /// /// @@ -63,7 +64,9 @@ /// /// /// +/// /// +/// /// /// /// diff --git a/node_modules/@types/node/ts4.8/inspector.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/inspector.d.ts old mode 100755 new mode 100644 similarity index 65% rename from node_modules/@types/node/ts4.8/inspector.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/inspector.d.ts index f79313f..079ab8e --- a/node_modules/@types/node/ts4.8/inspector.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/inspector.d.ts @@ -1,28 +1,21 @@ -// eslint-disable-next-line dt-header -// Type definitions for inspector - -// These definitions are auto-generated. -// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 -// for more information. - -// tslint:disable:max-line-length +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). /** - * The `inspector` module provides an API for interacting with the V8 inspector. - * - * It can be accessed using: - * - * ```js - * const inspector = require('inspector'); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/inspector.js) + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v20.x/lib/inspector.js) */ declare module 'inspector' { import EventEmitter = require('node:events'); + interface InspectorNotification { method: string; params: T; } + namespace Schema { /** * Description of the protocol domain. @@ -1466,48 +1459,6 @@ declare module 'inspector' { */ 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. @@ -1542,12 +1493,6 @@ declare module 'inspector' { */ result: ScriptCoverage[]; } - interface TakeTypeProfileReturnType { - /** - * Type profile for all scripts since startTypeProfile() was turned on. - */ - result: ScriptTypeProfile[]; - } interface ConsoleProfileStartedEventDataType { id: string; /** @@ -1688,7 +1633,7 @@ declare module 'inspector' { /** * Controls how the trace buffer stores data. */ - recordMode?: string; + recordMode?: string | undefined; /** * Included category filters. */ @@ -1763,6 +1708,7 @@ declare module 'inspector' { enabled: boolean; } } + /** * The `inspector.Session` is used for dispatching messages to the V8 inspector * back-end and receiving message responses and notifications. @@ -1770,29 +1716,29 @@ declare module 'inspector' { 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. + * 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; + /** - * Connects a session to the main thread inspector back-end. - * An exception will be thrown if this API was not called on a Worker - * thread. + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. * @since v12.11.0 */ connectToMainThread(): 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 + * 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. */ 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 @@ -1804,21 +1750,16 @@ declare module 'inspector' { * // 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/). + * 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 + * 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; + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; /** * Returns supported domains. */ @@ -2075,21 +2016,6 @@ declare module 'inspector' { * 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; @@ -2150,17 +2076,25 @@ declare module 'inspector' { */ 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 events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable', callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable', 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; + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; /** * Issued when new execution context is created. */ @@ -2258,8 +2192,13 @@ declare module 'inspector' { * waiting for all frontends to disconnect. */ addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; - emit(event: 'inspectorNotification', message: InspectorNotification<{}>): 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; @@ -2286,11 +2225,12 @@ declare module 'inspector' { emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): 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; + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; /** * Issued when new execution context is created. */ @@ -2388,11 +2328,16 @@ declare module 'inspector' { * waiting for all frontends to disconnect. */ on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', 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; + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; /** * Issued when new execution context is created. */ @@ -2490,11 +2435,16 @@ declare module 'inspector' { * waiting for all frontends to disconnect. */ once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', 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; + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; /** * Issued when new execution context is created. */ @@ -2592,11 +2542,16 @@ declare module 'inspector' { * waiting for all frontends to disconnect. */ prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', 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; + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; /** * Issued when new execution context is created. */ @@ -2694,7 +2649,13 @@ declare module 'inspector' { * waiting for all frontends to disconnect. */ prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; } + /** * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has * started. @@ -2702,28 +2663,32 @@ declare module 'inspector' { * 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. + * See the [security warning](https://nodejs.org/docs/latest-v20.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. */ - function open(port?: number, host?: string, wait?: boolean): void; + 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 + * 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 + * For help, see: https://nodejs.org/en/docs/inspector * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a * * $ node -p 'inspector.url()' @@ -2731,15 +2696,1001 @@ declare module 'inspector' { * ``` */ function url(): string | undefined; + /** - * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * 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; + + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; } + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + */ declare module 'node:inspector' { - import EventEmitter = require('inspector'); - export = EventEmitter; + export * from 'inspector'; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v20.x/lib/inspector/promises.js) + * @since v19.0.0 + */ +declare module 'inspector/promises' { + import EventEmitter = require('node:events'); + import { + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + NodeRuntime, + } from 'inspector'; + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + 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. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + */ + connectToMainThread(): 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. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { 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. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains'): Promise; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * 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): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger'): Promise; + /** + * 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'): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable'): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries'): Promise; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType): Promise; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: 'Runtime.globalLexicalScopeNames', params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * 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'): Promise; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable'): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * 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): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: 'Debugger.getPossibleBreakpoints', params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver'): Promise; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut'): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause'): Promise; + /** + * 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'): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume'): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * 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): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * 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): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * 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): Promise; + /** + * 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): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable'): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable'): Promise; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages'): Promise; + post(method: 'Profiler.enable'): Promise; + post(method: 'Profiler.disable'): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: 'Profiler.start'): Promise; + post(method: 'Profiler.stop'): Promise; + /** + * 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): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage'): Promise; + post(method: 'HeapProfiler.enable'): Promise; + post(method: 'HeapProfiler.disable'): Promise; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: 'HeapProfiler.collectGarbage'): Promise; + post(method: 'HeapProfiler.getObjectByHeapObjectId', params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * 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): Promise; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: 'HeapProfiler.stopSampling'): Promise; + post(method: 'HeapProfiler.getSamplingProfile'): Promise; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories'): Promise; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop'): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable'): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable'): Promise; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable'): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + + 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; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', 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; + emit(event: 'NodeRuntime.waitingForDebugger'): 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; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', 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; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', 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; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', 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; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + } + + export { + Session, + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + NodeRuntime, + }; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @since v19.0.0 + */ +declare module 'node:inspector/promises' { + export * from 'inspector/promises'; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/module.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..c38a9b8 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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/.deno/@types+node@20.16.5/node_modules/@types/node/net.d.ts old mode 100755 new mode 100644 similarity index 65% rename from node_modules/@types/node/net.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/net.d.ts index 195b393..238c6a6 --- a/node_modules/@types/node/net.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/net.d.ts @@ -1,22 +1,26 @@ /** * > Stability: 2 - Stable * - * The `net` module provides an asynchronous network API for creating stream-based + * 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('net'); + * const net = require('node:net'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/net.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/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.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; +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; @@ -57,12 +61,20 @@ declare module 'net' { 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'; + 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 @@ -79,6 +91,12 @@ declare module 'net' { */ 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. @@ -131,6 +149,14 @@ declare module 'net' { * @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. @@ -208,12 +234,21 @@ declare module 'net' { */ 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). + * 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 @@ -243,13 +278,19 @@ declare module 'net' { */ readonly bytesWritten: number; /** - * If `true`,`socket.connect(options[, connectListener])` was + * 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. */ @@ -266,9 +307,18 @@ declare module 'net' { * @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. - * @see {https://nodejs.org/api/net.html#socketreadystate} + * + * * 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; @@ -279,17 +329,20 @@ declare module 'net' { */ readonly remoteAddress?: string | undefined; /** - * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + * 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`. + * 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. + * 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; @@ -310,73 +363,131 @@ declare module 'net' { * events.EventEmitter * 1. close * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout + * 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: '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; + 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: '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; + 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: '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; + 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: '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; + 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: '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; + 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: '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; + 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; @@ -422,6 +533,14 @@ declare module 'net' { */ 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 @@ -445,7 +564,7 @@ declare module 'net' { * * 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). + * 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). @@ -461,7 +580,7 @@ declare module 'net' { * ```js * server.on('error', (e) => { * if (e.code === 'EADDRINUSE') { - * console.log('Address in use, retrying...'); + * console.error('Address in use, retrying...'); * setTimeout(() => { * server.close(); * server.listen(PORT, HOST); @@ -526,7 +645,7 @@ declare module 'net' { */ 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). + * 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 */ @@ -551,56 +670,68 @@ declare module 'net' { * Indicates whether or not the server is listening for connections. * @since v5.7.0 */ - listening: boolean; + 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: "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: "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: "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: "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: "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: "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'; + 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 + * @since v15.0.0, v14.18.0 */ class BlockList { /** * Adds a rule to block the given IP address. - * @since v15.0.0 + * @since v15.0.0, v14.18.0 * @param address An IPv4 or IPv6 address. * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. */ @@ -608,7 +739,7 @@ declare module 'net' { addAddress(address: SocketAddress): void; /** * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). - * @since v15.0.0 + * @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'`. @@ -617,7 +748,7 @@ declare module 'net' { 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 + * @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'`. @@ -641,12 +772,17 @@ declare module 'net' { * 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 + * @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; @@ -672,11 +808,11 @@ declare module 'net' { * * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. * - * Here is an example of an TCP echo server which listens for connections + * Here is an example of a TCP echo server which listens for connections * on port 8124: * * ```js - * const net = require('net'); + * const net = require('node:net'); * const server = net.createServer((c) => { * // 'connection' listener. * console.log('client connected'); @@ -696,8 +832,8 @@ declare module 'net' { * * Test this by using `telnet`: * - * ```console - * $ telnet localhost 8124 + * ```bash + * telnet localhost 8124 * ``` * * To listen on the socket `/tmp/echo.sock`: @@ -710,8 +846,8 @@ declare module 'net' { * * Use `nc` to connect to a Unix domain socket server: * - * ```console - * $ nc -U /tmp/echo.sock + * ```bash + * nc -U /tmp/echo.sock * ``` * @since v0.5.0 * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. @@ -751,19 +887,64 @@ declare module 'net' { function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; function createConnection(path: string, connectionListener?: () => void): Socket; /** - * Tests if input is an IP address. Returns `0` for invalid strings, - * returns `4` for IP version 4 addresses, and returns `6` for IP version 6 - * addresses. + * 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` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.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 a version 4 IP address, otherwise returns `false`. + * 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 a version 6 IP address, otherwise returns `false`. + * 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; @@ -789,29 +970,30 @@ declare module 'net' { port?: number | undefined; } /** - * @since v15.14.0 + * @since v15.14.0, v14.18.0 */ class SocketAddress { constructor(options: SocketAddressInitOptions); /** - * @since v15.14.0 + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 */ readonly address: string; /** * Either \`'ipv4'\` or \`'ipv6'\`. - * @since v15.14.0 + * @since v15.14.0, v14.18.0 */ readonly family: IPVersion; /** - * @since v15.14.0 + * @since v15.14.0, v14.18.0 */ readonly port: number; /** - * @since v15.14.0 + * @since v15.14.0, v14.18.0 */ readonly flowlabel: number; } } -declare module 'node:net' { - export * from 'net'; +declare module "node:net" { + export * from "net"; } diff --git a/node_modules/@types/node/ts4.8/os.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/os.d.ts old mode 100755 new mode 100644 similarity index 81% rename from node_modules/@types/node/ts4.8/os.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/os.d.ts index 3186267..0b9a68c --- a/node_modules/@types/node/ts4.8/os.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/os.d.ts @@ -1,21 +1,26 @@ /** - * The `os` module provides operating system-related utility methods and + * The `node:os` module provides operating system-related utility methods and * properties. It can be accessed using: * * ```js - * const os = require('os'); + * const os = require('node:os'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/os.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/os.js) */ -declare module 'os' { +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; }; } @@ -27,18 +32,18 @@ declare module 'os' { cidr: string | null; } interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { - family: 'IPv4'; + family: "IPv4"; scopeid?: undefined; } interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { - family: 'IPv6'; + family: "IPv6"; scopeid: number; } interface UserInfo { username: T; uid: number; gid: number; - shell: T; + shell: T | null; homedir: T; } type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; @@ -75,6 +80,7 @@ declare module 'os' { 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: * @@ -88,8 +94,8 @@ declare module 'os' { * nice: 0, * sys: 30340, * idle: 1070356870, - * irq: 0 - * } + * irq: 0, + * }, * }, * { * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', @@ -99,8 +105,8 @@ declare module 'os' { * nice: 0, * sys: 26980, * idle: 1071569080, - * irq: 0 - * } + * irq: 0, + * }, * }, * { * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', @@ -110,8 +116,8 @@ declare module 'os' { * nice: 0, * sys: 21750, * idle: 1070919370, - * irq: 0 - * } + * irq: 0, + * }, * }, * { * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', @@ -121,17 +127,28 @@ declare module 'os' { * nice: 0, * sys: 19430, * idle: 1070905480, - * irq: 20 - * } + * 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. @@ -217,17 +234,17 @@ declare module 'os' { /** * 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 `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. * * The value of `homedir` returned by `os.userInfo()` is provided by the operating * system. This differs from the result of `os.homedir()`, which queries * environment variables for the home directory before falling back to the * operating system response. * - * Throws a `SystemError` if a user has no `username` or `homedir`. + * 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: "buffer" }): UserInfo; function userInfo(options?: { encoding: BufferEncoding }): UserInfo; type SignalConstants = { [key in NodeJS.Signals]: number; @@ -375,6 +392,13 @@ declare module 'os' { 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; @@ -385,12 +409,18 @@ declare module 'os' { } } 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'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * 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`. + * 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; @@ -403,8 +433,9 @@ declare module 'os' { */ function version(): string; /** - * Returns a string identifying the operating system platform. The value is set - * at compile time. Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * 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`. * @@ -413,6 +444,14 @@ declare module '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. @@ -426,7 +465,7 @@ declare module 'os' { * Possible values are `'BE'` for big endian and `'LE'` for little endian. * @since v0.9.4 */ - function endianness(): 'BE' | 'LE'; + 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. @@ -435,15 +474,15 @@ declare module 'os' { */ 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. + * 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 + * 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`. + * 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. @@ -451,6 +490,6 @@ declare module 'os' { function setPriority(priority: number): void; function setPriority(pid: number, priority: number): void; } -declare module 'node:os' { - export * from 'os'; +declare module "node:os" { + export * from "os"; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/package.json b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/package.json new file mode 100644 index 0000000..f7aedd0 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/package.json @@ -0,0 +1,217 @@ +{ + "name": "@types/node", + "version": "20.16.5", + "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": "~6.19.2" + }, + "typesPublisherContentHash": "0031738d9b4600037faf992f8a3057514a229d4bdf728ed6eb4b4e33cdf5c119", + "typeScriptVersion": "4.8" +} \ No newline at end of file diff --git a/node_modules/@types/node/ts4.8/path.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/path.d.ts old mode 100755 new mode 100644 similarity index 88% rename from node_modules/@types/node/ts4.8/path.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/path.d.ts index a647f13..0c6b46d --- a/node_modules/@types/node/ts4.8/path.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/path.d.ts @@ -1,21 +1,21 @@ -declare module 'path/posix' { - import path = require('path'); +declare module "path/posix" { + import path = require("path"); export = path; } -declare module 'path/win32' { - import path = require('path'); +declare module "path/win32" { + import path = require("path"); export = path; } /** - * The `path` module provides utilities for working with file and directory paths. - * It can be accessed using: + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: * * ```js - * const path = require('path'); + * const path = require('node:path'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/path.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/path.js) */ -declare module 'path' { +declare module "path" { namespace path { /** * A parsed path object generated by path.parse() or consumed by path.format(). @@ -90,7 +90,7 @@ declare module 'path' { * 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 string paths to join. + * @param paths A sequence of paths or path segments. * @throws {TypeError} if any of the arguments is not a string. */ resolve(...paths: string[]): string; @@ -122,10 +122,10 @@ declare module 'path' { * Often used to extract the file name from a fully qualified path. * * @param path the path to evaluate. - * @param ext optionally, an extension to remove from the result. + * @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, ext?: string): 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. @@ -137,11 +137,11 @@ declare module 'path' { /** * The platform-specific file separator. '\\' or '/'. */ - readonly sep: '\\' | '/'; + readonly sep: "\\" | "/"; /** * The platform-specific file delimiter. ';' or ':'. */ - readonly delimiter: ';' | ':'; + readonly delimiter: ";" | ":"; /** * Returns an object from a path string - the opposite of format(). * @@ -177,15 +177,15 @@ declare module 'path' { const path: path.PlatformPath; export = path; } -declare module 'node:path' { - import path = require('path'); +declare module "node:path" { + import path = require("path"); export = path; } -declare module 'node:path/posix' { - import path = require('path/posix'); +declare module "node:path/posix" { + import path = require("path/posix"); export = path; } -declare module 'node:path/win32' { - import path = require('path/win32'); +declare module "node:path/win32" { + import path = require("path/win32"); export = path; } diff --git a/node_modules/@types/node/ts4.8/perf_hooks.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/perf_hooks.d.ts old mode 100755 new mode 100644 similarity index 51% rename from node_modules/@types/node/ts4.8/perf_hooks.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/perf_hooks.d.ts index 6d57bb7..408c18f --- a/node_modules/@types/node/ts4.8/perf_hooks.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/perf_hooks.d.ts @@ -7,9 +7,10 @@ * * [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('perf_hooks'); + * const { PerformanceObserver, performance } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((items) => { * console.log(items.getEntries()[0].duration); @@ -26,14 +27,24 @@ * performance.measure('A to B', 'A', 'B'); * }); * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/perf_hooks.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/perf_hooks.js) */ -declare module 'perf_hooks' { - import { AsyncResource } from 'node:async_hooks'; - type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web interface NodeGCPerformanceDetail { /** - * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * 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. */ @@ -46,6 +57,7 @@ declare module 'perf_hooks' { readonly flags?: number | undefined; } /** + * The constructor of this class is not exposed to users directly. * @since v8.5.0 */ class PerformanceEntry { @@ -85,6 +97,24 @@ declare module 'perf_hooks' { * @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._ @@ -130,6 +160,11 @@ declare module 'perf_hooks' { * @since v8.5.0 */ readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; /** * The high resolution millisecond timestamp at which the V8 platform was * initialized. @@ -143,10 +178,13 @@ declare module 'perf_hooks' { 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 + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. */ - type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization; + type EventLoopUtilityFunction = ( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ) => EventLoopUtilization; interface MarkOptions { /** * Additional optional detail to include with the mark. @@ -154,7 +192,7 @@ declare module 'perf_hooks' { detail?: unknown | undefined; /** * An optional timestamp to be used as the mark time. - * @default `performance.now()`. + * @default `performance.now()` */ startTime?: number | undefined; } @@ -178,26 +216,36 @@ declare module 'perf_hooks' { } interface TimerifyOptions { /** - * A histogram object created using - * `perf_hooks.createHistogram()` that will record runtime durations in - * nanoseconds. + * 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 + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 */ 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 + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. * @since v16.7.0 */ clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * 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; /** * 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 @@ -221,13 +269,35 @@ declare module 'perf_hooks' { */ 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. + * 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. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. * @param name */ - mark(name?: string, options?: MarkOptions): void; + mark(name: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new `PerformanceResourceTiming` entry in the Resource Timeline. + * A `PerformanceResourceTiming` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'resource'`. + * Performance resources are used to mark moments in the Resource Timeline. + * @param timingInfo [Fetch Timing Info](https://fetch.spec.whatwg.org/#fetch-timing-info) + * @param requestedUrl The resource url + * @param initiatorType The initiator name, e.g: 'fetch' + * @param global + * @param cacheMode The cache mode must be an empty string ('') or 'local' + * @since v18.2.0, v16.17.0 + */ + markResourceTiming( + timingInfo: object, + requestedUrl: string, + initiatorType: string, + global: object, + cacheMode: "" | "local", + ): PerformanceResourceTiming; /** * Creates a new PerformanceMeasure entry in the Performance Timeline. * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', @@ -242,35 +312,79 @@ declare module 'perf_hooks' { * @param name * @param startMark * @param endMark + * @return The PerformanceMeasure entry that was created */ - measure(name: string, startMark?: string, endMark?: string): void; - measure(name: string, options: MeasureOptions): void; + 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. + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 */ readonly nodeTiming: PerformanceNodeTiming; /** - * @return the current high resolution millisecond timestamp + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 */ now(): number; /** - * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 */ readonly timeOrigin: number; /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * * 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. + * A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported + * once the finally handler is invoked. * @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. + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 */ - eventLoopUtilization: EventLoopUtilityFunction; + toJSON(): any; } - interface PerformanceObserverEntryList { + class PerformanceObserverEntryList { /** * Returns a list of `PerformanceEntry` objects in chronological order * with respect to `performanceEntry.startTime`. @@ -278,8 +392,8 @@ declare module 'perf_hooks' { * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntries()); @@ -289,16 +403,20 @@ declare module 'perf_hooks' { * * name: 'test', * * entryType: 'mark', * * startTime: 81.465639, - * * duration: 0 + * * duration: 0, + * * detail: null * * }, * * PerformanceEntry { * * name: 'meow', * * entryType: 'mark', * * startTime: 81.860064, - * * duration: 0 + * * duration: 0, + * * detail: null * * } * * ] * + * performance.clearMarks(); + * performance.clearMeasures(); * observer.disconnect(); * }); * obs.observe({ type: 'mark' }); @@ -317,8 +435,8 @@ declare module 'perf_hooks' { * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntriesByName('meow')); @@ -328,7 +446,8 @@ declare module 'perf_hooks' { * * name: 'meow', * * entryType: 'mark', * * startTime: 98.545991, - * * duration: 0 + * * duration: 0, + * * detail: null * * } * * ] * @@ -341,11 +460,15 @@ declare module 'perf_hooks' { * * name: 'test', * * entryType: 'mark', * * startTime: 63.518931, - * * duration: 0 + * * duration: 0, + * * detail: null * * } * * ] * * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); * observer.disconnect(); * }); * obs.observe({ entryTypes: ['mark', 'measure'] }); @@ -358,13 +481,13 @@ declare module 'perf_hooks' { 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`. + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. * * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntriesByType('mark')); @@ -374,16 +497,20 @@ declare module 'perf_hooks' { * * name: 'test', * * entryType: 'mark', * * startTime: 55.897834, - * * duration: 0 + * * duration: 0, + * * detail: null * * }, * * PerformanceEntry { * * name: 'meow', * * entryType: 'mark', * * startTime: 56.350146, - * * duration: 0 + * * duration: 0, + * * detail: null * * } * * ] * + * performance.clearMarks(); + * performance.clearMeasures(); * observer.disconnect(); * }); * obs.observe({ type: 'mark' }); @@ -396,6 +523,9 @@ declare module 'perf_hooks' { getEntriesByType(type: EntryType): PerformanceEntry[]; } type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ class PerformanceObserver extends AsyncResource { constructor(callback: PerformanceObserverCallback); /** @@ -404,16 +534,16 @@ declare module 'perf_hooks' { */ disconnect(): void; /** - * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: * * ```js * const { * performance, - * PerformanceObserver - * } = require('perf_hooks'); + * PerformanceObserver, + * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((list, observer) => { - * // Called three times synchronously. `list` contains one item. + * // Called once asynchronously. `list` contains three items. * }); * obs.observe({ type: 'mark' }); * @@ -425,15 +555,113 @@ declare module 'perf_hooks' { observe( options: | { - entryTypes: ReadonlyArray; - buffered?: boolean | undefined; - } + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } | { - type: EntryType; - buffered?: boolean | undefined; - } + type: EntryType; + buffered?: boolean | undefined; + }, ): void; } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + readonly entryType: "resource"; + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } namespace constants { const NODE_PERFORMANCE_GC_MAJOR: number; const NODE_PERFORMANCE_GC_MINOR: number; @@ -458,10 +686,15 @@ declare module 'perf_hooks' { } interface Histogram { /** - * Returns a `Map` object detailing the accumulated percentile distribution. - * @since v11.10.0 + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 */ - readonly percentiles: Map; + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; /** * The number of times the event loop delay exceeded the maximum 1 hour event * loop delay threshold. @@ -469,36 +702,67 @@ declare module 'perf_hooks' { */ readonly exceeds: number; /** - * The minimum recorded event loop delay. - * @since v11.10.0 + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 */ - readonly min: number; + readonly exceedsBigInt: bigint; /** * The maximum recorded event loop delay. * @since v11.10.0 */ readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: 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. + * The minimum recorded event loop delay. * @since v11.10.0 */ - readonly stddev: number; + readonly min: number; /** - * Resets the collected histogram data. - * @since v11.10.0 + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 */ - reset(): void; + readonly minBigInt: bigint; /** * 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; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; } interface IntervalHistogram extends Histogram { /** @@ -516,18 +780,21 @@ declare module 'perf_hooks' { } interface RecordableHistogram extends Histogram { /** - * @since v15.9.0 + * @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 + * @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._ @@ -542,7 +809,7 @@ declare module 'perf_hooks' { * detect. * * ```js - * const { monitorEventLoopDelay } = require('perf_hooks'); + * const { monitorEventLoopDelay } = require('node:perf_hooks'); * const h = monitorEventLoopDelay({ resolution: 20 }); * h.enable(); * // Do something. @@ -577,10 +844,91 @@ declare module 'perf_hooks' { } /** * Returns a `RecordableHistogram`. - * @since v15.9.0 + * @since v15.9.0, v14.18.0 */ function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; + global { + /** + * `PerformanceEntry` is a global reference for `require('node:perf_hooks').PerformanceEntry` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `require('node:perf_hooks').PerformanceMark` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `require('node:perf_hooks').PerformanceMeasure` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `require('node:perf_hooks').PerformanceObserver` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `require('node:perf_hooks').PerformanceObserverEntryList` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `require('node:perf_hooks').PerformanceResourceTiming` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `require('node:perf_hooks').performance` + * @see https://nodejs.org/docs/latest-v20.x/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'; +declare module "node:perf_hooks" { + export * from "perf_hooks"; } diff --git a/node_modules/@types/node/process.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/process.d.ts old mode 100755 new mode 100644 similarity index 62% rename from node_modules/@types/node/process.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/process.d.ts index 2d0ef86..67a479d --- a/node_modules/@types/node/process.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/process.d.ts @@ -1,6 +1,121 @@ -declare module 'process' { - import * as tty from 'node:tty'; - import { Worker } from 'node:worker_threads'; +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "sys": typeof import("util"); + "node:sys": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + global { var process: NodeJS.Process; namespace NodeJS { @@ -21,10 +136,25 @@ declare module 'process' { 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 { @@ -48,47 +178,71 @@ declare module 'process' { modules: string; openssl: string; } - type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; + 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'; + | "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; @@ -96,13 +250,17 @@ declare module 'process' { 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 the the value is an Error. + * 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 MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; type WorkerListener = (worker: Worker) => void; interface Socket extends ReadWriteStream { isTTY?: true | undefined; @@ -116,27 +274,76 @@ declare module 'process' { } 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 { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; /** * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current * 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 where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. */ filename: string; /** - * Returns a JSON-formatted diagnostic report for the running process. - * The report's JavaScript stack trace is taken from err, if present. + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. */ - getReport(err?: Error): string; + getReport(err?: Error): object; /** * If true, a diagnostic report is generated on fatal errors, * such as out of memory errors or failed C++ assertions. @@ -162,18 +369,19 @@ declare module 'process' { /** * 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. + * The report's JavaScript stack trace is taken from `err`, if present. * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. * @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. + * @param err 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; + writeReport(err?: Error): string; } interface ResourceUsage { fsRead: number; @@ -249,7 +457,7 @@ declare module 'process' { * For example, to copy `process.stdin` to `process.stdout`: * * ```js - * import { stdin, stdout } from 'process'; + * import { stdin, stdout } from 'node:process'; * * stdin.pipe(stdout); * ``` @@ -279,12 +487,11 @@ declare module 'process' { * 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. + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. */ stdin: ReadStream & { fd: 0; }; - openStdin(): Socket; /** * The `process.argv` property returns an array containing the command-line * arguments passed when the Node.js process was launched. The first element will @@ -296,7 +503,7 @@ declare module 'process' { * For example, assuming the following script for `process-args.js`: * * ```js - * import { argv } from 'process'; + * import { argv } from 'node:process'; * * // print process.argv * argv.forEach((val, index) => { @@ -306,8 +513,8 @@ declare module 'process' { * * Launching the Node.js process as: * - * ```console - * $ node process-args.js one two=three four + * ```bash + * node process-args.js one two=three four * ``` * * Would generate the output: @@ -343,14 +550,14 @@ declare module 'process' { * the script name. These options are useful in order to spawn child processes with * the same execution environment as the parent. * - * ```console - * $ node --harmony script.js --version + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version * ``` * * Results in `process.execArgv`: * * ```js - * ['--harmony'] + * ["--icu-data-dir=./foo", "--require", "./bar.js"] * ``` * * And `process.argv`: @@ -388,7 +595,7 @@ declare module 'process' { * the specified `directory` does not exist). * * ```js - * import { chdir, cwd } from 'process'; + * import { chdir, cwd } from 'node:process'; * * console.log(`Starting directory: ${cwd()}`); * try { @@ -408,7 +615,7 @@ declare module 'process' { * process. * * ```js - * import { cwd } from 'process'; + * import { cwd } from 'node:process'; * * console.log(`Current directory: ${cwd()}`); * ``` @@ -419,34 +626,70 @@ declare module 'process' { * The port used by the Node.js debugger when enabled. * * ```js - * import process from 'process'; + * 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 'process'; + * import { emitWarning } from 'node:process'; * - * // Emit a warning with a code and additional detail. - * emitWarning('Something happened!', { - * code: 'MY_WARNING', - * detail: 'This is some additional information' - * }); - * // Emits: - * // (node:56338) [MY_WARNING] Warning: Something happened! - * // This is some additional information + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! * ``` * - * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * ```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 process from 'process'; + * 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' @@ -457,7 +700,30 @@ declare module 'process' { * }); * ``` * - * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * 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. */ @@ -491,14 +757,14 @@ declare module 'process' { * to other `Worker` threads. * In other words, the following example would not work: * - * ```console - * $ node -e 'process.env.foo = "bar"' && echo $foo + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo * ``` * * While the following will: * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.foo = 'bar'; * console.log(env.foo); @@ -509,7 +775,7 @@ declare module 'process' { * throw an error when the value is not a string, number, or boolean. * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.test = null; * console.log(env.test); @@ -522,7 +788,7 @@ declare module 'process' { * Use `delete` to delete a property from `process.env`. * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.TEST = 1; * delete env.TEST; @@ -533,7 +799,7 @@ declare module 'process' { * On Windows operating systems, environment variables are case-insensitive. * * ```js - * import { env } from 'process'; + * import { env } from 'node:process'; * * env.TEST = 1; * console.log(env.test); @@ -542,10 +808,11 @@ declare module 'process' { * * 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 + * 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. + * 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; @@ -559,7 +826,7 @@ declare module 'process' { * To exit with a 'failure' code: * * ```js - * import { exit } from 'process'; + * import { exit } from 'node:process'; * * exit(1); * ``` @@ -568,17 +835,17 @@ declare module 'process' { * * 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`. + * 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_ + * 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 + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being * truncated and lost: * * ```js - * import { exit } from 'process'; + * import { exit } from 'node:process'; * * // This is an example of what *not* to do: * if (someConditionNotMet()) { @@ -589,13 +856,13 @@ declare module 'process' { * * 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. + * 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 + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding * scheduling any additional work for the event loop: * * ```js - * import process from 'process'; + * import process from 'node:process'; * * // How to properly set the exit code while letting * // the process exit gracefully. @@ -612,9 +879,9 @@ declare module 'process' { * In `Worker` threads, this function stops the current thread rather * than the current process. * @since v0.1.13 - * @param [code=0] The exit code. + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. */ - exit(code?: number): never; + 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 @@ -622,15 +889,41 @@ declare module 'process' { * * Specifying a code to {@link exit} will override any * previous setting of `process.exitCode`. + * @default undefined * @since v0.11.8 */ - exitCode?: number | undefined; + 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[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + * @since v20.16.0 + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; /** * The `process.getgid()` method returns the numerical group identity of the * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getgid) { * console.log(`Current gid: ${process.getgid()}`); @@ -641,7 +934,7 @@ declare module 'process' { * Android). * @since v0.1.31 */ - getgid(): number; + 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 @@ -649,7 +942,7 @@ declare module 'process' { * associated numeric ID. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getgid && process.setgid) { * console.log(`Current gid: ${process.getgid()}`); @@ -668,13 +961,13 @@ declare module 'process' { * @since v0.1.31 * @param id The group name or ID */ - setgid(id: number | string): void; + setgid?: (id: number | string) => void; /** * The `process.getuid()` method returns the numeric user identity of the process. * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getuid) { * console.log(`Current uid: ${process.getuid()}`); @@ -685,7 +978,7 @@ declare module 'process' { * Android). * @since v0.1.28 */ - getuid(): number; + 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. @@ -693,7 +986,7 @@ declare module 'process' { * numeric ID. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getuid && process.setuid) { * console.log(`Current uid: ${process.getuid()}`); @@ -711,13 +1004,13 @@ declare module 'process' { * This feature is not available in `Worker` threads. * @since v0.1.28 */ - setuid(id: number | string): void; + setuid?: (id: number | string) => void; /** * The `process.geteuid()` method returns the numerical effective user identity of * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.geteuid) { * console.log(`Current uid: ${process.geteuid()}`); @@ -728,7 +1021,7 @@ declare module 'process' { * Android). * @since v2.0.0 */ - geteuid(): number; + 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 @@ -736,7 +1029,7 @@ declare module 'process' { * associated numeric ID. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.geteuid && process.seteuid) { * console.log(`Current uid: ${process.geteuid()}`); @@ -755,13 +1048,13 @@ declare module 'process' { * @since v2.0.0 * @param id A user name or ID */ - seteuid(id: number | string): void; + seteuid?: (id: number | string) => void; /** * The `process.getegid()` method returns the numerical effective group identity * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getegid) { * console.log(`Current gid: ${process.getegid()}`); @@ -772,7 +1065,7 @@ declare module 'process' { * Android). * @since v2.0.0 */ - getegid(): number; + 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 @@ -780,7 +1073,7 @@ declare module 'process' { * the associated a numeric ID. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getegid && process.setegid) { * console.log(`Current gid: ${process.getegid()}`); @@ -799,14 +1092,14 @@ declare module 'process' { * @since v2.0.0 * @param id A group name or ID */ - setegid(id: number | string): void; + setegid?: (id: number | string) => void; /** * The `process.getgroups()` method returns an array with the supplementary group * IDs. POSIX leaves it unspecified if the effective group ID is included but * Node.js ensures it always is. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getgroups) { * console.log(process.getgroups()); // [ 16, 21, 297 ] @@ -817,7 +1110,7 @@ declare module 'process' { * Android). * @since v0.9.4 */ - getgroups(): number[]; + 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 @@ -826,7 +1119,7 @@ declare module 'process' { * The `groups` array can contain numeric group IDs, group names, or both. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getgroups && process.setgroups) { * try { @@ -843,7 +1136,7 @@ declare module 'process' { * This feature is not available in `Worker` threads. * @since v0.9.4 */ - setgroups(groups: ReadonlyArray): void; + setgroups?: (groups: ReadonlyArray) => void; /** * The `process.setUncaughtExceptionCaptureCallback()` function sets a function * that will be invoked when an uncaught exception occurs, which will receive the @@ -855,7 +1148,7 @@ declare module 'process' { * 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 + * 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. * @@ -868,11 +1161,29 @@ declare module 'process' { * @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 'process'; + * import { version } from 'node:process'; * * console.log(`Version: ${version}`); * // Version: v14.8.0 @@ -889,7 +1200,7 @@ declare module 'process' { * to load modules that were compiled against a different module ABI version. * * ```js - * import { versions } from 'process'; + * import { versions } from 'node:process'; * * console.log(versions); * ``` @@ -897,30 +1208,39 @@ declare module 'process' { * Will generate an object similar to: * * ```console - * { node: '11.13.0', - * v8: '7.0.276.38-node.18', - * uv: '1.27.0', - * zlib: '1.2.11', - * brotli: '1.0.7', - * ares: '1.15.0', - * modules: '67', - * nghttp2: '1.34.0', - * napi: '4', - * llhttp: '1.1.1', - * openssl: '1.1.1b', - * cldr: '34.0', - * icu: '63.1', - * tz: '2018e', - * unicode: '11.0' } + * { 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 an `Object` containing the JavaScript - * representation of the configure options used to compile the current Node.js - * executable. This is the same as the `config.gypi` file that was produced when - * running the `./configure` script. + * 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: * @@ -942,7 +1262,6 @@ declare module 'process' { * node_shared_http_parser: 'false', * node_shared_libuv: 'false', * node_shared_zlib: 'false', - * node_use_dtrace: 'false', * node_use_openssl: 'true', * node_shared_openssl: 'false', * strict_aliasing: 'true', @@ -951,13 +1270,6 @@ declare module 'process' { * } * } * ``` - * - * The `process.config` property is **not** read-only and there are existing - * modules in the ecosystem that are known to extend, modify, or entirely replace - * the value of `process.config`. - * - * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made - * read-only in a future release. * @since v0.7.7 */ readonly config: ProcessConfig; @@ -976,7 +1288,7 @@ declare module 'process' { * other than kill the target process. * * ```js - * import process, { kill } from 'process'; + * import process, { kill } from 'node:process'; * * process.on('SIGHUP', () => { * console.log('Got SIGHUP signal.'); @@ -997,11 +1309,26 @@ declare module 'process' { * @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 'process'; + * import { pid } from 'node:process'; * * console.log(`This process is pid ${pid}`); * ``` @@ -1013,7 +1340,7 @@ declare module 'process' { * current process. * * ```js - * import { ppid } from 'process'; + * import { ppid } from 'node:process'; * * console.log(`The parent process is pid ${ppid}`); * ``` @@ -1028,8 +1355,8 @@ declare module 'process' { * 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) + * 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 @@ -1040,19 +1367,19 @@ declare module 'process' { title: string; /** * The operating system CPU architecture for which the Node.js binary was compiled. - * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. * * ```js - * import { arch } from 'process'; + * import { arch } from 'node:process'; * * console.log(`This processor architecture is ${arch}`); * ``` * @since v0.5.0 */ - readonly arch: string; + readonly arch: Architecture; /** * The `process.platform` property returns a string identifying the operating - * system platform on which the Node.js process is running. + * system platform for which the Node.js binary was compiled. * * Currently possible values are: * @@ -1065,7 +1392,7 @@ declare module 'process' { * * `'win32'` * * ```js - * import { platform } from 'process'; + * import { platform } from 'node:process'; * * console.log(`This platform is ${platform}`); * ``` @@ -1088,6 +1415,24 @@ declare module 'process' { */ 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, `0` 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; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v20.x/api/process.html#processavailablememory) for more information. + * @experimental + * @since v20.13.0 + */ + availableMemory(): number; /** * 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 @@ -1099,7 +1444,7 @@ declare module 'process' { * argument to the function, to get a diff reading. * * ```js - * import { cpuUsage } from 'process'; + * import { cpuUsage } from 'node:process'; * * const startUsage = cpuUsage(); * // { user: 38579, system: 6986 } @@ -1123,7 +1468,7 @@ declare module 'process' { * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. * * ```js - * import { nextTick } from 'process'; + * import { nextTick } from 'node:process'; * * console.log('start'); * nextTick(() => { @@ -1141,7 +1486,7 @@ declare module 'process' { * I/O has occurred: * * ```js - * import { nextTick } from 'process'; + * import { nextTick } from 'node:process'; * * function MyThing(options) { * this.setupOptions(options); @@ -1189,7 +1534,7 @@ declare module 'process' { * The following approach is much better: * * ```js - * import { nextTick } from 'process'; + * import { nextTick } from 'node:process'; * * function definitelyAsync(arg, cb) { * if (arg) { @@ -1204,6 +1549,14 @@ declare module 'process' { * @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 @@ -1214,14 +1567,14 @@ declare module 'process' { * ```js * { * name: 'node', - * lts: 'Erbium', - * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', - * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', - * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' + * 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 + * 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 */ @@ -1240,7 +1593,7 @@ declare module 'process' { * `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 * + * @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; @@ -1258,24 +1611,41 @@ declare module 'process' { */ 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`. + * 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: + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: */ send?( message: any, sendHandle?: any, options?: { - swallowErrors?: boolean | undefined; + keepOpen?: boolean | undefined; }, - callback?: (error: Error | null) => void + 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 @@ -1284,13 +1654,13 @@ declare module 'process' { * * 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`. + * 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. + * 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()`. @@ -1301,11 +1671,11 @@ declare module 'process' { * 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 + * `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 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`, @@ -1321,7 +1691,7 @@ declare module 'process' { * dashes: * * ```js - * import { allowedNodeEnvironmentFlags } from 'process'; + * import { allowedNodeEnvironmentFlags } from 'node:process'; * * allowedNodeEnvironmentFlags.forEach((flag) => { * // -r @@ -1340,14 +1710,14 @@ declare module 'process' { */ 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`. + * `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](https://nodejs.org/docs/latest-v20.x/api/report.html). * @since v11.8.0 */ - report?: ProcessReport | undefined; + report: ProcessReport; /** * ```js - * import { resourceUsage } from 'process'; + * import { resourceUsage } from 'node:process'; * * console.log(resourceUsage()); * /* @@ -1377,105 +1747,133 @@ declare module 'process' { */ resourceUsage(): ResourceUsage; /** - * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * 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: "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; + 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: "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: "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: "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: "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; + 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[]; + 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[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; } } } export = process; } -declare module 'node:process' { - import process = require('process'); +declare module "node:process" { + import process = require("process"); export = process; } diff --git a/node_modules/@types/node/ts4.8/punycode.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/punycode.d.ts old mode 100755 new mode 100644 similarity index 92% rename from node_modules/@types/node/ts4.8/punycode.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/punycode.d.ts index 345af53..137441d --- a/node_modules/@types/node/ts4.8/punycode.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/punycode.d.ts @@ -1,5 +1,5 @@ /** - * **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 + * **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`. @@ -15,8 +15,8 @@ * 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'`. + * 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. * @@ -24,9 +24,9 @@ * 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/v16.9.0/lib/punycode.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/punycode.js) */ -declare module 'punycode' { +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. @@ -101,7 +101,7 @@ declare module 'punycode' { * Users currently depending on the punycode module should switch to using * the userland-provided Punycode.js module instead. */ - encode(codePoints: ReadonlyArray): string; + encode(codePoints: readonly number[]): string; } /** * @deprecated since v7.0.0 @@ -112,6 +112,6 @@ declare module 'punycode' { */ const version: string; } -declare module 'node:punycode' { - export * from 'punycode'; +declare module "node:punycode" { + export * from "punycode"; } diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/querystring.d.ts old mode 100755 new mode 100644 similarity index 74% rename from node_modules/@types/node/querystring.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/querystring.d.ts index 892440b..bd494a6 --- a/node_modules/@types/node/querystring.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/querystring.d.ts @@ -1,31 +1,53 @@ /** - * The `querystring` module provides utilities for parsing and formatting URL + * The `node:querystring` module provides utilities for parsing and formatting URL * query strings. It can be accessed using: * * ```js - * const querystring = require('querystring'); + * const querystring = require('node:querystring'); * ``` * - * The `querystring` API is considered Legacy. While it is still maintained, - * new code should use the `URLSearchParams` API instead. - * @deprecated Legacy - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/querystring.js) + * `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.13.1/lib/querystring.js) */ -declare module 'querystring' { +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 | ReadonlyArray | ReadonlyArray | null> {} + 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) | + * 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) | @@ -44,7 +66,7 @@ declare module 'querystring' { * ``` * * 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: + * 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, @@ -64,14 +86,14 @@ declare module 'querystring' { * * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: * - * ```js + * ```json * { - * foo: 'bar', - * abc: ['xyz', '123'] + * "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()`, + * 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_. * @@ -88,7 +110,7 @@ declare module 'querystring' { * @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. + * @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; /** @@ -100,7 +122,7 @@ declare module 'querystring' { */ 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 + * 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 @@ -126,6 +148,6 @@ declare module 'querystring' { */ function unescape(str: string): string; } -declare module 'node:querystring' { - export * from 'querystring'; +declare module "node:querystring" { + export * from "querystring"; } diff --git a/node_modules/@types/node/ts4.8/readline.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/readline.d.ts old mode 100755 new mode 100644 similarity index 63% rename from node_modules/@types/node/ts4.8/readline.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/readline.d.ts index f1545fa..06e1705 --- a/node_modules/@types/node/ts4.8/readline.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/readline.d.ts @@ -1,36 +1,43 @@ /** - * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. It can be accessed - * using: + * 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 - * const readline = require('readline'); + * import * as readline from 'node:readline/promises'; * ``` * - * The following simple example illustrates the basic use of the `readline` module. + * To use the callback and sync APIs: * * ```js - * const readline = require('readline'); - * - * const rl = readline.createInterface({ - * input: process.stdin, - * output: process.stdout - * }); - * - * rl.question('What do you think of Node.js? ', (answer) => { - * // TODO: Log the answer in a database - * console.log(`Thank you for your valuable feedback: ${answer}`); - * - * rl.close(); - * }); + * import * as readline from 'node:readline'; * ``` * - * 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 + * 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/v16.9.0/lib/readline.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/readline.js) */ -declare module 'readline' { - import { Abortable, EventEmitter } from 'node:events'; - interface Key { +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; @@ -38,13 +45,13 @@ declare module 'readline' { shift?: boolean | undefined; } /** - * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a - * single `input` `Readable` stream and a single `output` `Writable` stream. + * 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 */ - class Interface extends EventEmitter { + export class Interface extends EventEmitter { readonly terminal: boolean; /** * The current input data being processed by node. @@ -67,7 +74,7 @@ declare module 'readline' { * const showResults = debounce(() => { * console.log( * '\n', - * values.filter((val) => val.startsWith(rl.line)).join(' ') + * values.filter((val) => val.startsWith(rl.line)).join(' '), * ); * }, 300); * process.stdin.on('keypress', (c, k) => { @@ -93,54 +100,61 @@ declare module 'readline' { * > Instances of the `readline.Interface` class are constructed using the * > `readline.createInterface()` method. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + * @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); + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); /** * NOTE: According to the documentation: * * > Instances of the `readline.Interface` class are constructed using the * > `readline.createInterface()` method. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + * @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 + * @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. + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. * @since v0.1.98 */ setPrompt(prompt: string): void; /** - * The `rl.prompt()` method writes the `readline.Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * 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 `readline.Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * 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. + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. * * When called, `rl.question()` will resume the `input` stream if it has been * paused. * - * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * 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 @@ -165,25 +179,6 @@ declare module 'readline' { * * setTimeout(() => ac.abort(), 10000); * ``` - * - * If this method is invoked as it's util.promisify()ed version, it returns a - * Promise that fulfills with the answer. If the question is canceled using - * an `AbortController` it will reject with an `AbortError`. - * - * ```js - * const util = require('util'); - * const question = util.promisify(rl.question).bind(rl); - * - * async function questionExample() { - * try { - * const answer = await question('What is you favorite food? '); - * console.log(`Oh, so your favorite food is ${answer}`); - * } catch (err) { - * console.error('Question rejected', err); - * } - * } - * questionExample(); - * ``` * @since v0.3.3 * @param query A statement or query to write to `output`, prepended to the prompt. * @param callback A callback function that is invoked with the user's input in response to the `query`. @@ -194,7 +189,7 @@ declare module 'readline' { * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed * later if necessary. * - * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `readline.Interface` instance. + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. * @since v0.3.4 */ pause(): this; @@ -204,12 +199,12 @@ declare module 'readline' { */ resume(): this; /** - * The `rl.close()` method closes the `readline.Interface` instance and + * 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 `readline.Interface` instance. + * from being emitted by the `Interface` instance. * @since v0.1.98 */ close(): void; @@ -224,7 +219,7 @@ declare module 'readline' { * When called, `rl.write()` will resume the `input` stream if it has been * paused. * - * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. * * ```js * rl.write('Delete this!'); @@ -232,7 +227,7 @@ declare module 'readline' { * 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_. + * 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; @@ -256,66 +251,69 @@ declare module 'readline' { * 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; + 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; + 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; + 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; + 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; + 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; + 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; } - type ReadLine = Interface; // type forwarded for backwards compatibility - type Completer = (line: string) => CompleterResult; - type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => void; - type CompleterResult = [string[], string]; - interface ReadLineOptions { + 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; @@ -341,13 +339,13 @@ declare module 'readline' { tabSize?: number | undefined; } /** - * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * The `readline.createInterface()` method creates a new `readline.Interface` instance. * * ```js - * const readline = require('readline'); + * const readline = require('node:readline'); * const rl = readline.createInterface({ * input: process.stdin, - * output: process.stdout + * output: process.stdout, * }); * ``` * @@ -366,18 +364,17 @@ declare module 'readline' { * (`process.stdout` does this automatically when it is a TTY). * * When creating a `readline.Interface` using `stdin` as input, the program - * will not terminate until it receives `EOF` (Ctrl+D on - * Linux/macOS, Ctrl+Z followed by Return on - * Windows). - * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: - * - * ```js - * process.stdin.unref(); - * ``` + * 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 */ - function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; - function createInterface(options: ReadLineOptions): Interface; + 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. * @@ -386,7 +383,7 @@ declare module 'readline' { * * 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 + * 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 @@ -394,41 +391,6 @@ declare module 'readline' { * if (process.stdin.isTTY) * process.stdin.setRawMode(true); * ``` - * @since v0.7.7 - */ - function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; - type Direction = -1 | 0 | 1; - interface CursorPos { - rows: number; - cols: number; - } - /** - * The `readline.clearLine()` method clears current line of given `TTY` stream - * in a specified direction identified by `dir`. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; - /** - * The `readline.clearScreenDown()` method clears the given `TTY` stream from - * the current position of the cursor down. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; - /** - * The `readline.cursorTo()` method moves cursor to the specified position in a - * given `TTY` `stream`. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; - /** - * The `readline.moveCursor()` method moves the cursor _relative_ to its current - * position in a given `TTY` `stream`. * * ## Example: Tiny CLI * @@ -436,11 +398,11 @@ declare module 'readline' { * implement a small command-line interface: * * ```js - * const readline = require('readline'); + * const readline = require('node:readline'); * const rl = readline.createInterface({ * input: process.stdin, * output: process.stdout, - * prompt: 'OHAI> ' + * prompt: 'OHAI> ', * }); * * rl.prompt(); @@ -468,15 +430,15 @@ declare module 'readline' { * well as a `for await...of` loop: * * ```js - * const fs = require('fs'); - * const readline = require('readline'); + * 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 + * 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. @@ -493,12 +455,12 @@ declare module 'readline' { * Alternatively, one could use the `'line'` event: * * ```js - * const fs = require('fs'); - * const readline = require('readline'); + * const fs = require('node:fs'); + * const readline = require('node:readline'); * * const rl = readline.createInterface({ * input: fs.createReadStream('sample.txt'), - * crlfDelay: Infinity + * crlfDelay: Infinity, * }); * * rl.on('line', (line) => { @@ -506,18 +468,18 @@ declare module 'readline' { * }); * ``` * - * 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: + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: * * ```js - * const { once } = require('events'); - * const { createReadStream } = require('fs'); - * const { createInterface } = require('readline'); + * 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 + * crlfDelay: Infinity, * }); * * rl.on('line', (line) => { @@ -533,11 +495,46 @@ declare module 'readline' { * })(); * ``` * @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`. */ - function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; + 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'; +declare module "node:readline" { + export * from "readline"; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/readline/promises.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..f2826bb --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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/.deno/@types+node@20.16.5/node_modules/@types/node/repl.d.ts old mode 100755 new mode 100644 similarity index 72% rename from node_modules/@types/node/repl.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/repl.d.ts index 04f64e1..f55ef66 --- a/node_modules/@types/node/repl.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/repl.d.ts @@ -1,17 +1,17 @@ /** - * The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that - * is available both as a standalone program or includible in other applications. - * It can be accessed using: + * 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('repl'); + * const repl = require('node:repl'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/repl.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/repl.js) */ -declare module 'repl' { - import { Interface, Completer, AsyncCompleter } from 'node:readline'; - import { Context } from 'node:vm'; - import { InspectOptions } from 'node:util'; +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. @@ -41,8 +41,8 @@ declare module 'repl' { * error with `repl.Recoverable` to indicate the input was incomplete and prompt for * additional lines. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + * @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; /** @@ -54,33 +54,33 @@ declare module 'repl' { * 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. + * @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`. + * @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`. + * @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`. + * @default a wrapper for `util.inspect` * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + * @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-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#readline_use_of_the_completer_function */ completer?: Completer | AsyncCompleter | undefined; /** @@ -95,11 +95,17 @@ declare module 'repl' { /** * 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`. + * @default false */ breakEvalOnSigint?: boolean | undefined; } - type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + 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, @@ -124,7 +130,7 @@ declare module 'repl' { * or directly using the JavaScript `new` keyword. * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * * const options = { useColors: true }; * @@ -162,33 +168,33 @@ declare module 'repl' { /** * A value indicating whether the REPL is currently in "editor mode". * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + * @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-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @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-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @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-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @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-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable */ readonly lastError: any; /** @@ -240,18 +246,18 @@ declare module 'repl' { * * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + * @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 + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following * properties: * * The following example shows two new commands added to the REPL instance: * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * * const replServer = repl.start({ prompt: '> ' }); * replServer.defineCommand('sayhello', { @@ -260,7 +266,7 @@ declare module 'repl' { * this.clearBufferedCommand(); * console.log(`Hello, ${name}!`); * this.displayPrompt(); - * } + * }, * }); * replServer.defineCommand('saybye', function saybye() { * console.log('Goodbye!'); @@ -277,13 +283,13 @@ declare module 'repl' { * Goodbye! * ``` * @since v0.3.0 - * @param keyword The command keyword (*without* a leading `.` character). + * @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. + * 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'. @@ -291,14 +297,14 @@ declare module 'repl' { * 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. + * 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. + * called from within the action function for commands registered using the `replServer.defineCommand()` method. * @since v9.0.0 */ clearBufferedCommand(): void; @@ -326,65 +332,65 @@ declare module 'repl' { * 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; + 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; + 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; + 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; + 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; + 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; + 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. @@ -401,7 +407,7 @@ declare module 'repl' { * If `options` is a string, then it specifies the input prompt: * * ```js - * const repl = require('repl'); + * const repl = require('node:repl'); * * // a Unix style prompt * repl.start('$ '); @@ -412,13 +418,13 @@ declare module 'repl' { /** * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + * @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'; +declare module "node:repl" { + export * from "repl"; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/sea.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000..6f1d1ea --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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/.deno/@types+node@20.16.5/node_modules/@types/node/stream.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..fbcd37d --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1707 @@ +/** + * 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](https://nodejs.org/docs/latest-v20.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v20.x/api/events.html#class-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.13.1/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. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + 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 {@link 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 {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v20.x/api/stream.html#event-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](https://nodejs.org/docs/latest-v20.x/api/stream.html#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}, {TypedArray}, {DataView} 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}, + * {TypedArray} or {DataView}. 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}, + * {TypedArray} or {DataView}. 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 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @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`](https://nodejs.org/docs/latest-v20.x/api/stream.html#streamfinishedstream-options). + * + * `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. + * @returns 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`](https://nodejs.org/docs/latest-v20.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `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/ts4.8/stream/consumers.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/stream/consumers.d.ts old mode 100755 new mode 100644 similarity index 51% rename from node_modules/@types/node/ts4.8/stream/consumers.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/stream/consumers.d.ts index 1667c24..5ad9cba --- a/node_modules/@types/node/ts4.8/stream/consumers.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/stream/consumers.d.ts @@ -1,12 +1,12 @@ -declare module 'stream/consumers' { - import { Readable } from 'node:stream'; +declare module "stream/consumers" { import { Blob as NodeBlob } from "node:buffer"; - function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; - function text(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; - function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; - function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; - function json(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + 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'; +declare module "node:stream/consumers" { + export * from "stream/consumers"; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/stream/promises.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..6eac5b7 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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/.deno/@types+node@20.16.5/node_modules/@types/node/stream/web.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..03938f3 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,521 @@ +type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ByteLengthQueuingStrategy; +type _CompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").CompressionStream; +type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").CountQueuingStrategy; +type _DecompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").DecompressionStream; +type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableByteStreamController; +type _ReadableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStream; +type _ReadableStreamBYOBReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBReader; +type _ReadableStreamBYOBRequest = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBRequest; +type _ReadableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultController; +type _ReadableStreamDefaultReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultReader; +type _TextDecoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextDecoderStream; +type _TextEncoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextEncoderStream; +type _TransformStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStream; +type _TransformStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStreamDefaultController; +type _WritableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStream; +type _WritableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultController; +type _WritableStreamDefaultWriter = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultWriter; + +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; + } + type ReadableStreamController = ReadableStreamDefaultController; + 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(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + 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; + }; + type ReadableStreamReaderMode = "byob"; + 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?: ReadableStreamReaderMode; + } + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + /** [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; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ + interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + readonly view: ArrayBufferView | 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: ArrayBufferView): void; + } + const ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + 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 writable: WritableStream; + readonly readable: ReadableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; + }; + + global { + interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {} + var ByteLengthQueuingStrategy: typeof globalThis extends { onmessage: any; ByteLengthQueuingStrategy: infer T } + ? T + : typeof import("stream/web").ByteLengthQueuingStrategy; + + interface CompressionStream extends _CompressionStream {} + var CompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + CompressionStream: infer T; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").CompressionStream; + + interface CountQueuingStrategy extends _CountQueuingStrategy {} + var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T + : typeof import("stream/web").CountQueuingStrategy; + + interface DecompressionStream extends _DecompressionStream {} + var DecompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + DecompressionStream: infer T; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").DecompressionStream; + + interface ReadableByteStreamController extends _ReadableByteStreamController {} + var ReadableByteStreamController: typeof globalThis extends + { onmessage: any; ReadableByteStreamController: infer T } ? T + : typeof import("stream/web").ReadableByteStreamController; + + interface ReadableStream extends _ReadableStream {} + var ReadableStream: typeof globalThis extends { onmessage: any; ReadableStream: infer T } ? T + : typeof import("stream/web").ReadableStream; + + interface ReadableStreamBYOBReader extends _ReadableStreamBYOBReader {} + var ReadableStreamBYOBReader: typeof globalThis extends { onmessage: any; ReadableStreamBYOBReader: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBReader; + + interface ReadableStreamBYOBRequest extends _ReadableStreamBYOBRequest {} + var ReadableStreamBYOBRequest: typeof globalThis extends { onmessage: any; ReadableStreamBYOBRequest: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBRequest; + + interface ReadableStreamDefaultController extends _ReadableStreamDefaultController {} + var ReadableStreamDefaultController: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultController: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultController; + + interface ReadableStreamDefaultReader extends _ReadableStreamDefaultReader {} + var ReadableStreamDefaultReader: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultReader: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultReader; + + interface TextDecoderStream extends _TextDecoderStream {} + var TextDecoderStream: typeof globalThis extends { onmessage: any; TextDecoderStream: infer T } ? T + : typeof import("stream/web").TextDecoderStream; + + interface TextEncoderStream extends _TextEncoderStream {} + var TextEncoderStream: typeof globalThis extends { onmessage: any; TextEncoderStream: infer T } ? T + : typeof import("stream/web").TextEncoderStream; + + interface TransformStream extends _TransformStream {} + var TransformStream: typeof globalThis extends { onmessage: any; TransformStream: infer T } ? T + : typeof import("stream/web").TransformStream; + + interface TransformStreamDefaultController extends _TransformStreamDefaultController {} + var TransformStreamDefaultController: typeof globalThis extends + { onmessage: any; TransformStreamDefaultController: infer T } ? T + : typeof import("stream/web").TransformStreamDefaultController; + + interface WritableStream extends _WritableStream {} + var WritableStream: typeof globalThis extends { onmessage: any; WritableStream: infer T } ? T + : typeof import("stream/web").WritableStream; + + interface WritableStreamDefaultController extends _WritableStreamDefaultController {} + var WritableStreamDefaultController: typeof globalThis extends + { onmessage: any; WritableStreamDefaultController: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultController; + + interface WritableStreamDefaultWriter extends _WritableStreamDefaultWriter {} + var WritableStreamDefaultWriter: typeof globalThis extends + { onmessage: any; WritableStreamDefaultWriter: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultWriter; + } +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/string_decoder.d.ts old mode 100755 new mode 100644 similarity index 61% rename from node_modules/@types/node/string_decoder.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/string_decoder.d.ts index 584e0c5..9c9d827 --- a/node_modules/@types/node/string_decoder.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/string_decoder.d.ts @@ -1,23 +1,23 @@ /** - * The `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 + * 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('string_decoder'); + * const { StringDecoder } = require('node:string_decoder'); * ``` * * The following example shows the basic use of the `StringDecoder` class. * * ```js - * const { StringDecoder } = require('string_decoder'); + * const { StringDecoder } = require('node:string_decoder'); * const decoder = new StringDecoder('utf8'); * * const cent = Buffer.from([0xC2, 0xA2]); - * console.log(decoder.write(cent)); + * console.log(decoder.write(cent)); // Prints: ¢ * * const euro = Buffer.from([0xE2, 0x82, 0xAC]); - * console.log(decoder.write(euro)); + * console.log(decoder.write(euro)); // Prints: € * ``` * * When a `Buffer` instance is written to the `StringDecoder` instance, an @@ -29,39 +29,39 @@ * symbol (`€`) are written over three separate operations: * * ```js - * const { StringDecoder } = require('string_decoder'); + * 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]))); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/string_decoder.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/string_decoder.js) */ -declare module 'string_decoder' { +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()`. + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. * @since v0.1.99 - * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + * @param buffer The bytes to decode. */ - write(buffer: Buffer): string; + 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. + * 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 A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + * @param buffer The bytes to decode. */ - end(buffer?: Buffer): string; + end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string; } } -declare module 'node:string_decoder' { - export * from 'string_decoder'; +declare module "node:string_decoder" { + export * from "string_decoder"; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/test.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..46736c9 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/test.d.ts @@ -0,0 +1,1874 @@ +/** + * 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.13.1/lib/test.js) + */ +declare module "node:test" { + import { Readable } from "node:stream"; + /** + * **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. + */ + 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 suite, 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 of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + 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, suite, test, todo }; + } + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + 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`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + 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`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.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; + } + /** + * Alias for {@link suite}. + * + * The `describe()` function is imported from the `node:test` module. + */ + 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. This is the same as calling {@link describe} with `options.skip` set to `true`. + * @since v18.15.0 + */ + 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`. This is the same as calling {@link describe} with `options.todo` set to `true`. + * @since v18.15.0 + */ + 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`. This is the same as calling {@link describe} with `options.only` set to `true`. + * @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; + } + /** + * Alias for {@link 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. This is the same as calling {@link it} with `options.skip` set to `true`. + */ + 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`. This is the same as calling {@link it} with `options.todo` set to `true`. + */ + 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`. This is the same as calling {@link it} with `options.only` set to `true`. + * @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. This is the same as calling {@link test} with `options.skip` set to `true`. + * @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`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @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`. This is the same as calling {@link test} with `options.only` set to `true`. + * @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 passed to {@link 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 suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` 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 test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v20.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | 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`. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + class TestsStream extends Readable implements NodeJS.ReadableStream { + addListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + addListener(event: "test:enqueue", listener: (data: TestEnqueue) => 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: "test:watch:drained", listener: () => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: TestCoverage): boolean; + emit(event: "test:complete", data: TestComplete): boolean; + emit(event: "test:dequeue", data: TestDequeue): boolean; + emit(event: "test:diagnostic", data: DiagnosticData): boolean; + emit(event: "test:enqueue", data: TestEnqueue): 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: "test:watch:drained"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: TestCoverage) => void): this; + on(event: "test:complete", listener: (data: TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + on(event: "test:enqueue", listener: (data: TestEnqueue) => 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: "test:watch:drained", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: TestCoverage) => void): this; + once(event: "test:complete", listener: (data: TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + once(event: "test:enqueue", listener: (data: TestEnqueue) => 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: "test:watch:drained", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependListener(event: "test:enqueue", listener: (data: TestEnqueue) => 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: "test:watch:drained", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: TestEnqueue) => 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: "test:watch:drained", listener: () => 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 { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * @since v20.15.0 + */ + readonly assert: TestContextAssert; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * 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 and each of its ancestors, separated by `>`. + * @since v20.16.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Used to set the number of assertions and subtests that are expected to run within the test. + * If the number of assertions and subtests that run does not match the expected count, the test will fail. + * + * To make sure assertions are tracked, the assert functions on `context.assert` must be used, + * instead of importing from the `node:assert` module. + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the correct number of assertions are run: + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * @since v20.15.0 + */ + plan(count: number): void; + /** + * 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. + * Defaults to 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. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert { + /** + * Identical to the `deepEqual` function from the `node:assert` module, but bound to the test context. + */ + deepEqual: typeof import("node:assert").deepEqual; + /** + * Identical to the `deepStrictEqual` function from the `node:assert` module, but bound to the test context. + */ + deepStrictEqual: typeof import("node:assert").deepStrictEqual; + /** + * Identical to the `doesNotMatch` function from the `node:assert` module, but bound to the test context. + */ + doesNotMatch: typeof import("node:assert").doesNotMatch; + /** + * Identical to the `doesNotReject` function from the `node:assert` module, but bound to the test context. + */ + doesNotReject: typeof import("node:assert").doesNotReject; + /** + * Identical to the `doesNotThrow` function from the `node:assert` module, but bound to the test context. + */ + doesNotThrow: typeof import("node:assert").doesNotThrow; + /** + * Identical to the `equal` function from the `node:assert` module, but bound to the test context. + */ + equal: typeof import("node:assert").equal; + /** + * Identical to the `fail` function from the `node:assert` module, but bound to the test context. + */ + fail: typeof import("node:assert").fail; + /** + * Identical to the `ifError` function from the `node:assert` module, but bound to the test context. + */ + ifError: typeof import("node:assert").ifError; + /** + * Identical to the `match` function from the `node:assert` module, but bound to the test context. + */ + match: typeof import("node:assert").match; + /** + * Identical to the `notDeepEqual` function from the `node:assert` module, but bound to the test context. + */ + notDeepEqual: typeof import("node:assert").notDeepEqual; + /** + * Identical to the `notDeepStrictEqual` function from the `node:assert` module, but bound to the test context. + */ + notDeepStrictEqual: typeof import("node:assert").notDeepStrictEqual; + /** + * Identical to the `notEqual` function from the `node:assert` module, but bound to the test context. + */ + notEqual: typeof import("node:assert").notEqual; + /** + * Identical to the `notStrictEqual` function from the `node:assert` module, but bound to the test context. + */ + notStrictEqual: typeof import("node:assert").notStrictEqual; + /** + * Identical to the `ok` function from the `node:assert` module, but bound to the test context. + */ + ok: typeof import("node:assert").ok; + /** + * Identical to the `rejects` function from the `node:assert` module, but bound to the test context. + */ + rejects: typeof import("node:assert").rejects; + /** + * Identical to the `strictEqual` function from the `node:assert` module, but bound to the test context. + */ + strictEqual: typeof import("node:assert").strictEqual; + /** + * Identical to the `throws` function from the `node:assert` module, but bound to the test context. + */ + throws: typeof import("node:assert").throws; + } + + /** + * 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; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v20.15.0 + */ + plan?: number | undefined; + } + /** + * This function creates a hook that runs before executing 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 The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing 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 The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in 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 The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```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 The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, 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 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. + * @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. + * @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: F): 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: F, 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 | undefined; + } + /** + * 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, + suite, + SuiteContext, + test, + test as default, + TestContext, + todo, + }; +} + +interface TestError extends Error { + cause: Error; +} +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 was run through the REPL. + */ + 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 TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestComplete extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: TestError; + /** + * The type of the test, used to denote whether this is a suite. + */ + 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 TestDequeue extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestEnqueue extends TestLocationInfo { + /** + * The test name. + */ + name: 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; + /** + * An error wrapping the error thrown by the test. + */ + error: TestError; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.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 { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; +} +interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; +} + +/** + * 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.13.1/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + + type TestEvent = + | { type: "test:coverage"; data: TestCoverage } + | { type: "test:complete"; data: TestComplete } + | { type: "test:dequeue"; data: TestDequeue } + | { type: "test:diagnostic"; data: DiagnosticData } + | { type: "test:enqueue"; data: TestEnqueue } + | { 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:watch:drained"; data: undefined }; + 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`. + * @since v20.0.0 + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: TestEventGenerator): AsyncGenerator; + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + class SpecReporter extends Transform { + constructor(); + } + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: TestEventGenerator): AsyncGenerator; + class LcovReporter extends Transform { + constructor(opts?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + const lcov: LcovReporter; + + export { dot, junit, lcov, SpecReporter as spec, tap, TestEvent }; +} diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/timers.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..5a73ca9 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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.13.1/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/.deno/@types+node@20.16.5/node_modules/@types/node/timers/promises.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..50cee98 --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/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/.deno/@types+node@20.16.5/node_modules/@types/node/tls.d.ts old mode 100755 new mode 100644 similarity index 71% rename from node_modules/@types/node/tls.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/tls.d.ts index b013b26..707549b --- a/node_modules/@types/node/tls.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/tls.d.ts @@ -1,16 +1,17 @@ /** - * The `tls` module provides an implementation of the Transport Layer Security + * 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('tls'); + * const tls = require('node:tls'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/tls.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/tls.js) */ -declare module 'tls' { - import { X509Certificate } from 'node:crypto'; - import * as net from 'node:net'; +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 { @@ -40,21 +41,100 @@ declare module 'tls' { CN: string; } interface PeerCertificate { - subject: Certificate; - issuer: Certificate; - subjectaltname: string; - infoAccess: NodeJS.Dict; - modulus: string; - exponent: string; - valid_from: string; - valid_to: string; - fingerprint: string; - fingerprint256: string; - ext_key_usage: string[]; - serialNumber: string; + /** + * `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 { @@ -132,7 +212,7 @@ declare module 'tls' { * * 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 + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the * connection is open. * @since v0.11.4 */ @@ -140,10 +220,10 @@ declare module 'tls' { /** * Construct a new tls.TLSSocket object from an existing TCP socket. */ - constructor(socket: net.Socket, options?: TLSSocketOptions); + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); /** - * Returns `true` if the peer certificate was signed by one of the CAs specified - * when creating the `tls.TLSSocket` instance, otherwise `false`. + * 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; @@ -179,13 +259,13 @@ declare module 'tls' { /** * Returns an object containing information on the negotiated cipher suite. * - * For example: + * For example, a TLSv1.2 protocol with AES256-SHA cipher: * * ```json * { - * "name": "AES128-SHA256", - * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", - * "version": "TLSv1.2" + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" * } * ``` * @@ -198,7 +278,7 @@ declare module 'tls' { * 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'`. + * 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 @@ -302,7 +382,7 @@ declare module 'tls' { * 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. + * 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. @@ -316,7 +396,7 @@ declare module 'tls' { rejectUnauthorized?: boolean | undefined; requestCert?: boolean | undefined; }, - callback: (err: Error | null) => void + callback: (err: Error | null) => void, ): undefined | boolean; /** * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. @@ -342,9 +422,9 @@ declare module 'tls' { * When enabled, TLS packet trace information is written to `stderr`. This can be * used to debug TLS connection problems. * - * Note: 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. + * 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; @@ -373,7 +453,7 @@ declare module 'tls' { * 128, * 'client finished'); * - * + * /* * Example return value of keyingMaterial: * 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; + 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; + 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; + 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; + 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; + 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; + 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 { /** @@ -481,7 +561,6 @@ declare module 'tls' { */ ticketKeys?: Buffer | undefined; /** - * * @param socket * @param identity identity parameter sent from the client. * @return pre-shared key that must either be @@ -516,7 +595,7 @@ declare module 'tls' { 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?: net.Socket | undefined; // Establish secure connection on a given socket rather than creating a new socket + 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; @@ -557,7 +636,8 @@ declare module 'tls' { * 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). + * @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; /** @@ -596,47 +676,118 @@ declare module 'tls' { * 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; + 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; + 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; + 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; + 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; + 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; + 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. @@ -645,8 +796,19 @@ declare module 'tls' { encrypted: TLSSocket; cleartext: TLSSocket; } - type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; + 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 @@ -688,12 +850,9 @@ declare module 'tls' { */ crl?: string | Buffer | Array | undefined; /** - * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use - * openssl dhparam to create the 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. If omitted or invalid, the parameters are - * silently discarded and DHE ciphers will not be available. + * `'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; /** @@ -722,7 +881,7 @@ declare module 'tls' { * 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; + key?: string | Buffer | Array | undefined; /** * Name of an OpenSSL engine to get private key from. Should be used * together with privateKeyIdentifier. @@ -813,13 +972,19 @@ declare module 'tls' { * 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 can be overwritten by providing alternative function as part of - * the `options.checkServerIdentity` option passed to `tls.connect()`. The + * 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. @@ -829,14 +994,14 @@ declare module 'tls' { * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is * automatically set as a listener for the `'secureConnection'` event. * - * The `ticketKeys` options is automatically shared between `cluster` module + * The `ticketKeys` options is automatically shared between `node:cluster` module * workers. * * The following illustrates a simple echo server: * * ```js - * const tls = require('tls'); - * const fs = require('fs'); + * const tls = require('node:tls'); + * const fs = require('node:fs'); * * const options = { * key: fs.readFileSync('server-key.pem'), @@ -846,7 +1011,7 @@ declare module 'tls' { * requestCert: true, * * // This is necessary only if the client uses a self-signed certificate. - * ca: [ fs.readFileSync('client-cert.pem') ] + * ca: [ fs.readFileSync('client-cert.pem') ], * }; * * const server = tls.createServer(options, (socket) => { @@ -881,8 +1046,8 @@ declare module 'tls' { * * ```js * // Assumes an echo server that is listening on port 8000. - * const tls = require('tls'); - * const fs = require('fs'); + * const tls = require('node:tls'); + * const fs = require('node:fs'); * * const options = { * // Necessary only if the server requires client certificate authentication. @@ -913,7 +1078,12 @@ declare module 'tls' { * @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, + 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 @@ -922,7 +1092,7 @@ declare module 'tls' { * 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. + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and `encrypted` stream properties. * * Using `cleartext` has the same API as {@link TLSSocket}. * @@ -948,29 +1118,44 @@ declare module 'tls' { * @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; + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; /** - * {@link createServer} sets the default value of the `honorCipherOrder` option + * `{@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 + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated * from `process.argv` as the default value of the `sessionIdContext` option, other * APIs that create secure contexts have no default value. * * The `tls.createSecureContext()` method creates a `SecureContext` object. It is - * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. + * 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. + * 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}. + * 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. @@ -983,37 +1168,50 @@ declare module 'tls' { function getCiphers(): string[]; /** * The default curve name to use for ECDH key agreement in a tls server. - * The default value is 'auto'. See tls.createSecureContext() for further + * 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 - * tls.createSecureContext(). It can be assigned any of the supported TLS - * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: - * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets - * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to - * 'TLSv1.3'. If multiple of the options are provided, the highest maximum - * is used. + * 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 tls.createSecureContext(). + * 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 + * `'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; /** - * An immutable array of strings representing the root certificates (in PEM - * format) used for verifying peer certificates. This is the default value - * of the ca option to tls.createSecureContext(). + * 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 */ - const rootCertificates: ReadonlyArray; + 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'; +declare module "node:tls" { + export * from "tls"; } diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/trace_events.d.ts old mode 100755 new mode 100644 similarity index 58% rename from node_modules/@types/node/trace_events.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/trace_events.d.ts index 2976eb6..b9d498e --- a/node_modules/@types/node/trace_events.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/trace_events.d.ts @@ -1,5 +1,5 @@ /** - * The `trace_events` module provides a mechanism to centralize tracing information + * 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 @@ -9,22 +9,29 @@ * The available categories are: * * * `node`: An empty placeholder. - * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. - * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.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.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.perf`: Enables capture of `Performance API` measurements. + * * `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 `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. - * * `v8`: The `V8` events are GC, compiling, and execution related. + * * `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. * @@ -32,8 +39,8 @@ * 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. + * 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 @@ -43,10 +50,10 @@ * node --trace-event-categories v8,node,node.async_hooks * ``` * - * Alternatively, trace events may be enabled using the `trace_events` module: + * Alternatively, trace events may be enabled using the `node:trace_events` module: * * ```js - * const trace_events = require('trace_events'); + * 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 * @@ -58,7 +65,7 @@ * 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 + * 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}`: * @@ -66,16 +73,26 @@ * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js * ``` * + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * * The tracing system uses the same time source * as the one used by `process.hrtime()`. * However the trace-event timestamps are expressed in microseconds, * unlike `process.hrtime()` which returns nanoseconds. * - * The features from this module are not available in `Worker` threads. + * 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/v16.9.0/lib/trace_events.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/trace_events.js) */ -declare module 'trace_events' { +declare module "trace_events" { /** * The `Tracing` object is used to enable or disable tracing for sets of * categories. Instances are created using the @@ -90,6 +107,7 @@ declare module 'trace_events' { /** * A comma-separated list of the trace event categories covered by this * `Tracing` object. + * @since v10.0.0 */ readonly categories: string; /** @@ -98,15 +116,34 @@ declare module 'trace_events' { * 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; } @@ -122,7 +159,7 @@ declare module 'trace_events' { * Creates and returns a `Tracing` object for the given set of `categories`. * * ```js - * const trace_events = require('trace_events'); + * const trace_events = require('node:trace_events'); * const categories = ['node.perf', 'node.async_hooks']; * const tracing = trace_events.createTracing({ categories }); * tracing.enable(); @@ -130,7 +167,6 @@ declare module 'trace_events' { * tracing.disable(); * ``` * @since v10.0.0 - * @return . */ function createTracing(options: CreateTracingOptions): Tracing; /** @@ -139,10 +175,10 @@ declare module 'trace_events' { * 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. + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. * * ```js - * const trace_events = require('trace_events'); + * const 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'] }); @@ -156,6 +192,6 @@ declare module 'trace_events' { */ function getEnabledCategories(): string | undefined; } -declare module 'node:trace_events' { - export * from 'trace_events'; +declare module "node:trace_events" { + export * from "trace_events"; } diff --git a/node_modules/@types/node/ts4.8/tty.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/tty.d.ts old mode 100755 new mode 100644 similarity index 84% rename from node_modules/@types/node/ts4.8/tty.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/tty.d.ts index 3bce2d3..099aef0 --- a/node_modules/@types/node/ts4.8/tty.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/tty.d.ts @@ -1,14 +1,13 @@ /** - * The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. - * In most cases, it will not be necessary or possible to use this module directly. - * However, it can be accessed using: + * 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('tty'); + * 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 + * 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`: @@ -21,11 +20,11 @@ * ``` * * 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/v16.9.0/lib/tty.js) + * manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/tty.js) */ -declare module 'tty' { - import * as net from 'node:net'; +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 @@ -43,7 +42,10 @@ declare module 'tty' { constructor(fd: number, options?: net.SocketConstructorOpts); /** * A `boolean` that is `true` if the TTY is currently configured to operate as a - * raw device. Defaults to `false`. + * 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; @@ -52,7 +54,9 @@ declare module 'tty' { * * 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. + * 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. @@ -72,24 +76,24 @@ declare module 'tty' { */ 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 + * 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; + addListener(event: "resize", listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; - emit(event: 'resize'): boolean; + emit(event: "resize"): boolean; on(event: string, listener: (...args: any[]) => void): this; - on(event: 'resize', listener: () => void): this; + on(event: "resize", listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; - once(event: 'resize', listener: () => void): this; + once(event: "resize", listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: 'resize', listener: () => void): this; + prependListener(event: "resize", listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: 'resize', listener: () => void): this; + prependOnceListener(event: "resize", listener: () => void): this; /** * `writeStream.clearLine()` clears the current line of this `WriteStream` in a * direction identified by `dir`. @@ -145,7 +149,7 @@ declare module 'tty' { * * 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. + * 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. */ @@ -175,7 +179,7 @@ declare module 'tty' { 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 + * 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 */ @@ -199,6 +203,6 @@ declare module 'tty' { isTTY: boolean; } } -declare module 'node:tty' { - export * from 'tty'; +declare module "node:tty" { + export * from "tty"; } diff --git a/node_modules/@types/node/ts4.8/url.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/url.d.ts old mode 100755 new mode 100644 similarity index 71% rename from node_modules/@types/node/ts4.8/url.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/url.d.ts index e6272b5..0a53528 --- a/node_modules/@types/node/ts4.8/url.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/url.d.ts @@ -1,16 +1,16 @@ /** - * The `url` module provides utilities for URL resolution and parsing. It can be - * accessed using: + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: * * ```js - * import url from 'url'; + * import url from 'node:url'; * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/url.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/url.js) */ -declare module 'url' { - import { Blob } from 'node:buffer'; - import { ClientRequestArgs } from 'node:http'; - import { ParsedUrlQuery, ParsedUrlQueryInput } from 'node:querystring'; +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; @@ -46,6 +46,14 @@ declare module 'url' { interface UrlWithStringQuery extends Url { query: string | null; } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions extends FileUrlToPathOptions {} /** * The `url.parse()` method takes a URL string, parses it, and returns a URL * object. @@ -54,17 +62,11 @@ declare module 'url' { * * A `URIError` is thrown if the `auth` property is present but cannot be decoded. * - * Use of the legacy `url.parse()` method is discouraged. Users should - * use the WHATWG `URL` API. Because the `url.parse()` method uses a - * lenient, non-standard algorithm for parsing URL strings, security - * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and - * incorrect handling of usernames and passwords have been identified. - * - * Deprecation of this API has been shelved for now primarily due to the the - * inability of the [WHATWG API to parse relative URLs](https://github.com/nodejs/node/issues/12682#issuecomment-1154492373). - * [Discussions are ongoing](https://github.com/whatwg/url/issues/531) for the best way to resolve this. - * + * `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. @@ -72,46 +74,26 @@ declare module 'url' { * 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: 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 object has both a `toString()` method and `href` property that return string serializations of the URL. - * These are not, however, customizable in any way. The `url.format(URL[, options])` method allows for basic - * customization of the output. - * Returns a customizable serialization of a URL `String` representation of a `WHATWG URL` object. + * The `url.format()` method returns a formatted URL string derived from `urlObject`. * * ```js - * import url from 'url'; - * const myURL = new URL('https://a:b@測試?abc#foo'); - * - * console.log(myURL.href); - * // Prints https://a:b@xn--g6w251d/?abc#foo - * - * console.log(myURL.toString()); - * // Prints https://a:b@xn--g6w251d/?abc#foo - * - * console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); - * // Prints 'https://測試/?abc' - * ``` - * @since v7.6.0 - * @param urlObject A `WHATWG URL` object - * @param options - */ - function format(urlObject: URL, options?: URLFormatOptions): string; - /** - * The `url.format()` method returns a formatted URL string derived from`urlObject`. - * - * ```js - * const url = require('url'); + * const url = require('node:url'); * url.format({ * protocol: 'https', * hostname: 'example.com', * pathname: '/some/path', * query: { * page: 1, - * format: 'json' - * } + * format: 'json', + * }, * }); * * // => 'https://example.com/some/path?page=1&format=json' @@ -126,55 +108,119 @@ declare module 'url' { * * 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`: + * * 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 `@`. + * * `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`: + * * 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`. + * * 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 + * * 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`. + * * 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 + * * 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 (`#`) + * * 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 - * @deprecated Legacy: Use the WHATWG URL API instead. + * @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 HREF. + * manner similar to that of a web browser resolving an anchor tag. * * ```js - * const url = require('url'); + * 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' * ``` * - * You can achieve the same result using the WHATWG URL API: + * To achieve the same result using the WHATWG URL API: * * ```js * function resolve(from, to) { @@ -192,9 +238,9 @@ declare module 'url' { * resolve('http://example.com/one', '/two'); // 'http://example.com/two' * ``` * @since v0.1.25 - * @deprecated Legacy: Use the WHATWG URL API instead. - * @param from The Base URL being resolved against. - * @param to The HREF URL being resolved. + * @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; /** @@ -203,10 +249,8 @@ declare module 'url' { * * It performs the inverse operation to {@link domainToUnicode}. * - * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. - * * ```js - * import url from 'url'; + * import url from 'node:url'; * * console.log(url.domainToASCII('español.com')); * // Prints xn--espaol-zwa.com @@ -224,10 +268,8 @@ declare module 'url' { * * It performs the inverse operation to {@link domainToASCII}. * - * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. - * * ```js - * import url from 'url'; + * import url from 'node:url'; * * console.log(url.domainToUnicode('xn--espaol-zwa.com')); * // Prints español.com @@ -244,7 +286,7 @@ declare module 'url' { * well as ensuring a cross-platform valid absolute path string. * * ```js - * import { fileURLToPath } from 'url'; + * import { fileURLToPath } from 'node:url'; * * const __filename = fileURLToPath(import.meta.url); * @@ -264,13 +306,13 @@ declare module 'url' { * @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; + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; /** * This function ensures that `path` is resolved absolutely, and that the URL * control characters are correctly encoded when converting into a File URL. * * ```js - * import { pathToFileURL } from 'url'; + * import { pathToFileURL } from 'node:url'; * * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) @@ -282,17 +324,17 @@ declare module 'url' { * @param path The path to convert to a File URL. * @return The file URL object. */ - function pathToFileURL(path: string): URL; + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; /** * This utility function converts a URL object into an ordinary options object as * expected by the `http.request()` and `https.request()` APIs. * * ```js - * import { urlToHttpOptions } from 'url'; + * import { urlToHttpOptions } from 'node:url'; * const myURL = new URL('https://a:b@測試?abc#foo'); * * console.log(urlToHttpOptions(myURL)); - * + * /* * { * protocol: 'https:', * hostname: 'xn--g6w251d', @@ -305,15 +347,32 @@ declare module 'url' { * } * * ``` - * @since v15.7.0 + * @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; } /** @@ -323,7 +382,7 @@ declare module 'url' { * * 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, + * 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 @@ -336,7 +395,7 @@ declare module 'url' { * const { * Blob, * resolveObjectURL, - * } = require('buffer'); + * } = require('node:buffer'); * * const blob = new Blob(['hello']); * const id = URL.createObjectURL(blob); @@ -347,7 +406,7 @@ declare module 'url' { * console.log(otherBlob.size); * ``` * - * The data stored by the registered `Blob` will be retained in memory until`URL.revokeObjectURL()` is called to remove it. + * 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 @@ -355,15 +414,30 @@ declare module 'url' { * @since v16.7.0 * @experimental */ - static createObjectURL(blob: Blob): string; + static createObjectURL(blob: NodeBlob): string; /** - * Removes the stored `Blob` identified by the given ID. + * 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(objectUrl: string): void; - constructor(input: string, base?: string | URL); + 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. * @@ -408,7 +482,7 @@ declare module 'url' { * // Prints example.org * * // Setting the hostname does not change the port - * myURL.hostname = 'example.com:82'; + * myURL.hostname = 'example.com'; * console.log(myURL.href); * // Prints https://example.com:81/foo * @@ -437,9 +511,9 @@ declare module 'url' { * 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. + * 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. + * If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. */ href: string; /** @@ -471,7 +545,7 @@ declare module 'url' { * * myURL.password = '123'; * console.log(myURL.href); - * // Prints https://abc:123@example.com + * // Prints https://abc:123@example.com/ * ``` * * Invalid URL characters included in the value assigned to the `password` property @@ -492,14 +566,14 @@ declare module 'url' { * // 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 + * 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 + * 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 (`''`). * @@ -598,7 +672,7 @@ declare module 'url' { * // 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 + * 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; @@ -615,14 +689,14 @@ declare module 'url' { * character, while `URLSearchParams` will always encode it: * * ```js - * const myUrl = new URL('https://example.org/abc?foo=~bar'); + * const myURL = new URL('https://example.org/abc?foo=~bar'); * - * console.log(myUrl.search); // prints ?foo=~bar + * console.log(myURL.search); // prints ?foo=~bar * * // Modify the URL via searchParams... - * myUrl.searchParams.sort(); + * myURL.searchParams.sort(); * - * console.log(myUrl.search); // prints ?foo=%7Ebar + * console.log(myURL.search); // prints ?foo=%7Ebar * ``` */ readonly searchParams: URLSearchParams; @@ -639,7 +713,7 @@ declare module 'url' { * // 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 + * 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; @@ -667,7 +741,7 @@ declare module 'url' { 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 + * 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. * @@ -711,18 +785,28 @@ declare module 'url' { * @since v7.5.0, v6.13.0 */ class URLSearchParams implements Iterable<[string, string]> { - constructor(init?: URLSearchParams | string | Record> | Iterable<[string, string]> | ReadonlyArray<[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; /** - * Remove all name-value pairs whose name is `name`. + * 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): void; + 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`. + * 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]()`. */ @@ -742,7 +826,10 @@ declare module 'url' { * @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(callback: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, thisArg?: TThis): void; + 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. @@ -755,9 +842,15 @@ declare module 'url' { */ getAll(name: string): string[]; /** - * Returns `true` if there is at least one name-value pair whose name is `name`. + * 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): boolean; + has(name: string, value?: string): boolean; /** * Returns an ES6 `Iterator` over the names of each name-value pair. * @@ -773,7 +866,7 @@ declare module 'url' { */ 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`, + * 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. * @@ -792,6 +885,11 @@ declare module 'url' { * ``` */ 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 @@ -819,8 +917,7 @@ declare module 'url' { values(): IterableIterator; [Symbol.iterator](): IterableIterator<[string, string]>; } - - import { URL as _URL, URLSearchParams as _URLSearchParams } from 'url'; + import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; global { interface URLSearchParams extends _URLSearchParams {} interface URL extends _URL {} @@ -833,23 +930,23 @@ declare module 'url' { * https://nodejs.org/api/url.html#the-whatwg-url-api * @since v10.0.0 */ - var URL: - // For compatibility with "dom" and "webworker" URL declarations - typeof globalThis extends { onmessage: any, URL: infer URL } - ? URL - : typeof _URL; + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; /** - * `URLSearchParams` class is a global reference for `require('url').URLSearchParams`. + * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` * https://nodejs.org/api/url.html#class-urlsearchparams * @since v10.0.0 */ - var URLSearchParams: - // For compatibility with "dom" and "webworker" URLSearchParams declarations - typeof globalThis extends { onmessage: any, URLSearchParams: infer URLSearchParams } - ? URLSearchParams - : typeof _URLSearchParams; + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; } } -declare module 'node:url' { - export * from 'url'; +declare module "node:url" { + export * from "url"; } diff --git a/node_modules/@types/node/ts4.8/util.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/util.d.ts old mode 100755 new mode 100644 similarity index 63% rename from node_modules/@types/node/ts4.8/util.d.ts rename to node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/util.d.ts index d0f4c17..3b21e3e --- a/node_modules/@types/node/ts4.8/util.d.ts +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/util.d.ts @@ -1,33 +1,49 @@ /** - * The `util` module supports the needs of Node.js internal APIs. Many of the + * 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('util'); + * const util = require('node:util'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/util.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/util.js) */ -declare module 'util' { - import * as types from 'node:util/types'; +declare module "util" { + import * as types from "node:util/types"; export interface InspectOptions { /** - * 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` + * 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 */ - getters?: 'get' | 'set' | boolean | undefined; 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 @@ -36,6 +52,12 @@ declare module 'util' { * @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 @@ -45,19 +67,50 @@ declare module 'util' { * `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` + * @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) => string; + 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 + * 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: * @@ -68,7 +121,7 @@ declare module 'util' { * // Returns: 'foo:%s' * ``` * - * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. + * 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 @@ -79,7 +132,7 @@ declare module 'util' { * // 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: + * 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); @@ -139,7 +192,7 @@ declare module 'util' { * console.error(name); // ENOENT * }); * ``` - * @since v16.0.0 + * @since v16.0.0, v14.17.0 */ export function getSystemErrorMap(): Map; /** @@ -147,7 +200,7 @@ declare module 'util' { * timestamp. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.log('Timestamped message.'); * ``` @@ -159,14 +212,60 @@ declare module 'util' { * 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 + * @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 + * 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 @@ -188,7 +287,7 @@ declare module 'util' { * Circular references point to their anchor by using a reference index: * * ```js - * const { inspect } = require('util'); + * const { inspect } = require('node:util'); * * const obj = {}; * obj.a = [obj]; @@ -206,7 +305,7 @@ declare module 'util' { * The following example inspects all properties of the `util` object: * * ```js - * const util = require('util'); + * const util = require('node:util'); * * console.log(util.inspect(util, { showHidden: true, depth: null })); * ``` @@ -214,7 +313,7 @@ declare module 'util' { * The following example highlights the effect of the `compact` option: * * ```js - * const util = require('util'); + * const util = require('node:util'); * * const o = { * a: [1, 2, [[ @@ -222,7 +321,7 @@ declare module 'util' { * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', * 'test', * 'foo']], 4], - * b: new Map([['za', 1], ['zb', 'test']]) + * b: new Map([['za', 1], ['zb', 'test']]), * }; * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); * @@ -271,7 +370,7 @@ declare module 'util' { * with no remaining strong references may be garbage collected at any time. * * ```js - * const { inspect } = require('util'); + * const { inspect } = require('node:util'); * * const obj = { a: 1 }; * const obj2 = { b: 2 }; @@ -285,13 +384,13 @@ declare module 'util' { * impact the result of `util.inspect()`. * * ```js - * const { inspect } = require('util'); - * const assert = require('assert'); + * 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]) + * 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 } } @@ -301,23 +400,44 @@ declare module 'util' { * const o2 = { * c: new Set([2, 1, 3]), * a: '`a` comes before `b`', - * b: [2, 3, 1] + * b: [2, 3, 1], * }; * assert.strict.equal( * inspect(o1, { sorted: true }), - * inspect(o2, { 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 MB. Inputs that result in longer output will + * 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 function inspect(object: any, options?: InspectOptions): string; export namespace inspect { let colors: NodeJS.Dict<[number, number]>; let styles: { @@ -339,7 +459,7 @@ declare module 'util' { * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isArray([]); * // Returns: true @@ -356,7 +476,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isRegExp(/some regexp/); * // Returns: true @@ -373,7 +493,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isDate(new Date()); * // Returns: true @@ -387,10 +507,10 @@ declare module 'util' { */ export function isDate(object: unknown): object is Date; /** - * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isError(new Error()); * // Returns: true @@ -401,10 +521,10 @@ declare module 'util' { * ``` * * This method relies on `Object.prototype.toString()` behavior. It is - * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * possible to obtain an incorrect result when the `object` argument manipulates `@@toStringTag`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * const obj = { name: 'Error', message: 'an error occurred' }; * * util.isError(obj); @@ -418,19 +538,19 @@ declare module 'util' { */ 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 + * 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`. + * prototype of `constructor` will be set to a new object created from `superConstructor`. * * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. * As an additional convenience, `superConstructor` will be accessible * through the `constructor.super_` property. * * ```js - * const util = require('util'); - * const EventEmitter = require('events'); + * const util = require('node:util'); + * const EventEmitter = require('node:events'); * * function MyStream() { * EventEmitter.call(this); @@ -456,7 +576,7 @@ declare module 'util' { * ES6 example using `class` and `extends`: * * ```js - * const EventEmitter = require('events'); + * const EventEmitter = require('node:events'); * * class MyStream extends EventEmitter { * write(data) { @@ -472,7 +592,7 @@ declare module 'util' { * stream.write('With ES6'); * ``` * @since v0.3.0 - * @deprecated Legacy: Use ES2015 class syntax and `extends` keyword instead. + * @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; @@ -485,7 +605,7 @@ declare module 'util' { * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. * * ```js - * const util = require('util'); + * const util = require('node:util'); * const debuglog = util.debuglog('foo'); * * debuglog('hello from foo [%d]', 123); @@ -504,7 +624,7 @@ declare module 'util' { * The `section` supports wildcard also: * * ```js - * const util = require('util'); + * const util = require('node:util'); * const debuglog = util.debuglog('foo-bar'); * * debuglog('hi there, it\'s foo-bar [%d]', 2333); @@ -524,7 +644,7 @@ declare module 'util' { * unnecessary wrapping. * * ```js - * const util = require('util'); + * 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 @@ -542,7 +662,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isBoolean(1); * // Returns: false @@ -559,7 +679,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isBuffer({ length: 0 }); * // Returns: false @@ -573,10 +693,10 @@ declare module 'util' { */ export function isBuffer(object: unknown): object is Buffer; /** - * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * function Foo() {} * const Bar = () => {}; @@ -596,7 +716,7 @@ declare module 'util' { * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isNull(0); * // Returns: false @@ -614,7 +734,7 @@ declare module 'util' { * returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isNullOrUndefined(0); * // Returns: false @@ -631,7 +751,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isNumber(false); * // Returns: false @@ -651,7 +771,7 @@ declare module 'util' { * Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isObject(5); * // Returns: false @@ -663,14 +783,14 @@ declare module 'util' { * // Returns: false * ``` * @since v0.11.5 - * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + * @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('util'); + * const util = require('node:util'); * * util.isPrimitive(5); * // Returns: true @@ -699,7 +819,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isString(''); * // Returns: true @@ -718,7 +838,7 @@ declare module 'util' { * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * util.isSymbol(5); * // Returns: false @@ -735,7 +855,7 @@ declare module 'util' { * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * const foo = undefined; * util.isUndefined(5); @@ -754,14 +874,14 @@ declare module 'util' { * such a way that it is marked as deprecated. * * ```js - * const util = require('util'); + * 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 + * 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. @@ -770,7 +890,7 @@ declare module 'util' { * the warning will be emitted only once for that `code`. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); @@ -787,10 +907,10 @@ declare module 'util' { * 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 + * 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`. + * 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. @@ -821,10 +941,10 @@ declare module 'util' { * 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. + * first argument will be the rejection reason (or `null` if the `Promise` resolved), and the second argument will be the resolved value. * * ```js - * const util = require('util'); + * const util = require('node:util'); * * async function fn() { * return 'hello world'; @@ -848,7 +968,7 @@ declare module 'util' { * * 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`. + * is wrapped in an `Error` with the original value stored in a field named `reason`. * * ```js * function fn() { @@ -859,56 +979,99 @@ declare module 'util' { * 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 && err.hasOwnProperty('reason') && err.reason === null; // true + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true * }); * ``` * @since v8.2.0 - * @param original An `async` function + * @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: () => 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 + 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 + 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; + 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 + 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; + 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; + 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; + 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; + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; /** * Takes a function following the common error-first callback style, i.e. taking * an `(err, value) => ...` callback as the last argument, and returns a version * that returns promises. * * ```js - * const util = require('util'); - * const fs = require('fs'); + * const util = require('node:util'); + * const fs = require('node:fs'); * * const stat = util.promisify(fs.stat); * stat('.').then((stats) => { @@ -921,8 +1084,8 @@ declare module 'util' { * Or, equivalently using `async function`s: * * ```js - * const util = require('util'); - * const fs = require('fs'); + * const util = require('node:util'); + * const fs = require('node:fs'); * * const stat = util.promisify(fs.stat); * @@ -930,12 +1093,14 @@ declare module 'util' { * 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`. + * 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 + * 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. * @@ -943,7 +1108,7 @@ declare module 'util' { * work as expected unless handled specially: * * ```js - * const util = require('util'); + * const util = require('node:util'); * * class Foo { * constructor() { @@ -969,23 +1134,37 @@ declare module 'util' { * @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, 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, 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, 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 + 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, 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 + 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 + 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 { @@ -994,17 +1173,122 @@ declare module 'util' { */ 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', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied is left to right so the following style + * might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * 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 or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: + | ForegroundColors + | BackgroundColors + | Modifiers + | Array, + text: string, + ): string; /** * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. * * ```js - * const decoder = new TextDecoder('shift_jis'); - * let string = ''; - * let buffer; - * while (buffer = getNextChunkSomehow()) { - * string += decoder.decode(buffer, { stream: true }); - * } - * string += decoder.decode(); // end-of-stream + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello * ``` * @since v8.3.0 */ @@ -1028,21 +1312,21 @@ declare module 'util' { 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. + * 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 { @@ -1056,6 +1340,8 @@ declare module 'util' { 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. @@ -1094,12 +1380,397 @@ declare module 'util' { */ 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; + /** + * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. + * @default false + * @since v20.16.0 + */ + allowNegative?: 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' { - export * from 'util/types'; -} -declare module 'util/types' { - import { KeyObject, webcrypto } from 'node:crypto'; +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. @@ -1365,7 +2036,10 @@ declare module 'util/types' { * ``` * @since v10.0.0 */ - function isMap(object: T | {}): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) : Map; + 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. * @@ -1391,12 +2065,40 @@ declare module 'util/types' { */ function isModuleNamespaceObject(value: unknown): boolean; /** - * Returns `true` if the value is an instance of a built-in `Error` type. + * Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). * * ```js - * util.types.isNativeError(new Error()); // Returns true - * util.types.isNativeError(new TypeError()); // Returns true - * util.types.isNativeError(new RangeError()); // Returns true + * 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 */ @@ -1451,7 +2153,9 @@ declare module 'util/types' { * ``` * @since v10.0.0 */ - function isSet(object: T | {}): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + 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. * @@ -1586,9 +2290,9 @@ declare module 'util/types' { */ function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; } -declare module 'node:util' { - export * from 'util'; +declare module "node:util" { + export * from "util"; } -declare module 'node:util/types' { - export * from 'util/types'; +declare module "node:util/types" { + export * from "util/types"; } diff --git a/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/v8.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..c1268ef --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/v8.d.ts @@ -0,0 +1,808 @@ +/** + * 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.13.1/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; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + * @experimental + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * 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/.deno/@types+node@20.16.5/node_modules/@types/node/vm.d.ts b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..1bdae9a --- /dev/null +++ b/node_modules/.deno/@types+node@20.16.5/node_modules/@types/node/vm.d.ts @@ -0,0 +1,924 @@ +/** + * 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.13.1/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](https://nodejs.org/docs/latest-v20.x/api/vm.html#what-does-it-mean-to-contextify-an-object) + * and return a reference to it so that it can be used in `{@link runInContext}` or + * [`script.runInContext()`](https://nodejs.org/docs/latest-v20.x/api/vm.html#scriptrunincontextcontextifiedobject-options). 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 `