diff options
277 files changed, 34093 insertions, 2464 deletions
diff --git a/.github/workflows/bun-types-release.yml b/.github/workflows/bun-types-release.yml new file mode 100644 index 000000000..ebbe08586 --- /dev/null +++ b/.github/workflows/bun-types-release.yml @@ -0,0 +1,137 @@ +name: Release +on: + workflow_dispatch: + +jobs: + test-build: + name: Test & Build + runs-on: ubuntu-latest + if: github.repository_owner == 'oven-sh' + defaults: + run: + working-directory: packages/bun-types + steps: + - uses: actions/checkout@v3 + + - name: Install bun + uses: xhyrom/setup-bun@v0.1.6 + with: + bun-version: latest + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Install node + uses: actions/setup-node@v3 + with: + node-version: latest + + - name: Install dependencies + run: bun install + + - name: ESLint + run: bun run lint + + - name: Build package + run: bun run build + + - name: Upload artifact + uses: actions/upload-artifact@v3 + with: + name: bun-types + path: packages/bun-types/dist/* + if-no-files-found: error + + publish-npm: + name: Publish on NPM + runs-on: ubuntu-latest + needs: [test-build] + if: github.repository_owner == 'oven-sh' + defaults: + run: + working-directory: packages/bun-types + + steps: + - uses: actions/checkout@v3 + - name: Install node + uses: actions/setup-node@v3 + with: + node-version: latest + registry-url: 'https://registry.npmjs.org' + + - name: Download all artifacts + uses: actions/download-artifact@v3 + with: + name: bun-types + path: packages/bun-types/dist + + - name: Publish on NPM + run: cd packages/bun-types/dist/ && npm publish --access public + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + publish-gpr: + name: Publish on GPR + runs-on: ubuntu-latest + needs: [test-build] + if: github.repository_owner == 'oven-sh' + defaults: + run: + working-directory: packages/bun-types + + steps: + - uses: actions/checkout@v3 + - name: Install node + uses: actions/setup-node@v3 + with: + node-version: latest + registry-url: 'https://npm.pkg.github.com/' + scope: '@oven-sh' + + - name: Install bun + uses: xhyrom/setup-bun@v0.1.6 + with: + bun-version: latest + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Download all artifacts + uses: actions/download-artifact@v3 + with: + name: bun-types + path: dist + + - name: Add scope to name + run: bun scripts/gpr.ts + + - name: Publish on GPR + run: cd dist/ && npm publish --access public + env: + NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + # no need for separate releases now + # create-release: + # name: Create Release + # runs-on: ubuntu-latest + # needs: [test-build] + # defaults: + # run: + # working-directory: packages/bun-types + # if: github.repository_owner == 'oven-sh' + + # steps: + # - name: Download all artifacts + # uses: actions/download-artifact@v3 + # with: + # name: bun-types + # path: packages/bun-types/dist + + # - name: Set version + # run: echo "version=$(jq --raw-output '.version' dist/package.json)" >> $GITHUB_ENV + + # - name: Create Release + # uses: softprops/action-gh-release@v0.1.14 + # with: + # tag_name: "v${{ env.version }}" + # body: "This is the release of bun-types that corresponds to the commit [${{ github.sha }}]" + # token: ${{ secrets.GITHUB_TOKEN }} + # files: | + # dist/* diff --git a/.github/workflows/bun-types-tests.yml b/.github/workflows/bun-types-tests.yml new file mode 100644 index 000000000..fad84a115 --- /dev/null +++ b/.github/workflows/bun-types-tests.yml @@ -0,0 +1,39 @@ +name: Tests +on: + push: + pull_request: + +jobs: + tests: + name: Tests + runs-on: ubuntu-latest + defaults: + run: + working-directory: packages/bun-types + + steps: + - name: Checkout repo + uses: actions/checkout@v2 + + - name: Install bun + uses: xhyrom/setup-bun@v0.1.6 + with: + bun-version: latest + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Install node + uses: actions/setup-node@v3 + with: + node-version: latest + + - name: Install dependencies + run: bun install + + - name: Generate package + run: bun run build + + - name: ESLint + run: bun run lint + + - name: Tests + run: bun run test
\ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..ebb14dfbd --- /dev/null +++ b/.prettierignore @@ -0,0 +1,9 @@ +src/fallback.html +# src/test +bench +test/bun.js/solid-dom-fixtures +test/bun.js/bundled +src/bun.js/builtins +# src/api/demo +test/snapshots +test/snapshots-no-hmr
\ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..495a80fd7 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,7 @@ +{ + "tabWidth": 2, + "useTabs": false, + "singleQuote": false, + "bracketSpacing": true, + "trailingComma": "all" +} diff --git a/.vscode/settings.json b/.vscode/settings.json index 0e0f09688..3dcd4ca35 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -31,7 +31,6 @@ }, "zig.beforeDebugCmd": "make build-unit ${file} ${filter} ${bin}", "zig.testCmd": "make test ${file} ${filter} ${bin}", - "lldb.verboseLogging": false, "files.exclude": { "**/.git": true, @@ -44,8 +43,6 @@ "**/*.xcscheme": true, "**/*.pem": true, "**/*.xcodeproj": true, - "packages/bun-types/*.d.ts": true, - "test/snapshots": true, "test/snapshots-no-hmr": true, "src/bun.js/WebKit": true, @@ -183,5 +180,8 @@ "queue": "cpp" }, "cmake.configureOnOpen": false, - "C_Cpp.errorSquiggles": "Enabled" -} + "C_Cpp.errorSquiggles": "Enabled", + "eslint.workingDirectories": [ + "packages/bun-types" + ] +}
\ No newline at end of file @@ -455,6 +455,8 @@ bun: npm-install: $(NPM_CLIENT) install +print-% : ; @echo $* = $($*) + @@ -497,11 +499,15 @@ generate-builtins: builtins .PHONY: vendor-without-check vendor-without-check: npm-install node-fallbacks runtime_js fallback_decoder bun_error mimalloc picohttp zlib boringssl libarchive libbacktrace lolhtml usockets uws tinycc oniguruma -BUN_TYPES_REPO_PATH ?= $(realpath ../bun-types) +BUN_TYPES_REPO_PATH ?= $(realpath packages/bun-types) + +ifeq ($(DEBUG),true) +BUN_RELEASE_BIN = bun +endif .PHONY: prepare-types prepare-types: - BUN_VERSION=$(PACKAGE_JSON_VERSION) $(BUN_RELEASE_BIN) $(BUN_TYPES_REPO_PATH)/bundle.ts $(BUN_TYPES_REPO_PATH)/dist + BUN_VERSION=$(PACKAGE_JSON_VERSION) $(BUN_RELEASE_BIN) $(BUN_TYPES_REPO_PATH)/scripts/bundle.ts $(BUN_TYPES_REPO_PATH)/dist echo "Generated types for $(PACKAGE_JSON_VERSION) in $(BUN_TYPES_REPO_PATH)/dist" cp $(BUN_TYPES_REPO_PATH)/dist/types.d.ts /tmp/bun-types.d.ts cd /tmp && $(PACKAGE_DIR)/../../node_modules/.bin/tsc /tmp/bun-types.d.ts @@ -509,12 +515,13 @@ prepare-types: release-types: # can be removed when/if "bun publish" is implemented @npm --version >/dev/null 2>&1 || (echo -e "ERROR: npm is required."; exit 1) - cd $(BUN_TYPES_REPO_PATH)/dist && npm publish + cd $(BUN_TYPES_REPO_PATH)/dist && npm publish --dry-run .PHONY: format format: ## to format the code - $(PRETTIER) --write test/bun.js/*.js - $(PRETTIER) --write test/bun.js/solid-dom-fixtures/**/*.js + -$(PRETTIER) --write 'test/bun.js/*.{js,jsx,ts,tsx}' + -$(PRETTIER) --write 'test/bun.js/solid-dom-fixtures/**/*.{js,jsx,ts,tsx}' + .PHONY: lolhtml lolhtml: @@ -197,7 +197,7 @@ bun.js focuses on performance, developer experience and compatibility with the J export default { port: 3000, fetch(request: Request) { - return new Response("Hello World"); + return new Response('Hello World'); }, }; @@ -237,8 +237,8 @@ The runtime uses JavaScriptCore, the JavaScript engine powering WebKit and Safar ```js // cat.js -import { resolve } from "path"; -import { write, stdout, file, argv } from "bun"; +import {resolve} from 'path'; +import {write, stdout, file, argv} from 'bun'; const path = resolve(argv.at(-1)); @@ -257,7 +257,7 @@ Server-side render React: ```js // requires Bun v0.1.0 or later // react-ssr.tsx -import { renderToReadableStream } from "react-dom/server"; +import {renderToReadableStream} from 'react-dom/server'; const dt = new Intl.DateTimeFormat(); @@ -289,7 +289,7 @@ PRs adding more examples are very welcome! ### Types for bun.js (editor autocomplete) -The best docs right now are the TypeScript types in the [`bun-types`](https://github.com/oven-sh/bun-types) npm package. A docs site is coming soon. +The best docs right now are the TypeScript types in the [`bun-types`](https://github.com/oven-sh/bun/tree/main/packages/bun-types) npm package. A docs site is coming soon. To get autocomplete for bun.js types in your editor, @@ -328,8 +328,8 @@ bun.js has fast paths for common use cases that make Web APIs live up to the per When you pass a file blob to `Bun.write`, Bun automatically uses a faster system call: ```js -const blob = Bun.file("input.txt"); -await Bun.write("output.txt", blob); +const blob = Bun.file('input.txt'); +await Bun.write('output.txt', blob); ``` On Linux, this uses the [`copy_file_range`](https://man7.org/linux/man-pages/man2/copy_file_range.2.html) syscall and on macOS, this becomes `clonefile` (or [`fcopyfile`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/copyfile.3.html)). @@ -338,7 +338,7 @@ On Linux, this uses the [`copy_file_range`](https://man7.org/linux/man-pages/man ```js // Eventually, this will stream the response to disk but today it buffers -await Bun.write("index.html", await fetch("https://example.com")); +await Bun.write('index.html', await fetch('https://example.com')); ``` ## Using bun as a package manager @@ -714,15 +714,15 @@ When importing CSS in JavaScript-like loaders, CSS is treated special. By default, bun will transform a statement like this: ```js -import "../styles/global.css"; +import '../styles/global.css'; ``` ##### When `platform` is `browser` ```js globalThis.document?.dispatchEvent( - new CustomEvent("onimportcss", { - detail: "http://localhost:3000/styles/globals.css", + new CustomEvent('onimportcss', { + detail: 'http://localhost:3000/styles/globals.css', }) ); ``` @@ -742,9 +742,9 @@ Additionally, bun exposes an API for SSR/SSG that returns a flat list of URLs to // This API needs to be changed somewhat to work more generally with Bun.js // Initially, you could only use bun.js through `bun dev` // and this API was created at that time -addEventListener("fetch", async (event: FetchEvent) => { +addEventListener('fetch', async (event: FetchEvent) => { let route = Bun.match(event); - const App = await import("pages/_app"); + const App = await import('pages/_app'); // This returns all .css files that were imported in the line above. // It’s recursive, so any file that imports a CSS file will be included. @@ -763,9 +763,9 @@ bun bundles `.css` files imported via `@import` into a single file. It doesn’t This input: ```css -@import url("./hi.css"); -@import url("./hello.css"); -@import url("./yo.css"); +@import url('./hi.css'); +@import url('./hello.css'); +@import url('./yo.css'); ``` Becomes: @@ -881,7 +881,7 @@ type Framework = Environment & { // If the framework does routing, you may want to handle CSS manually // "facade" removes CSS imports from JavaScript files, // and replaces an imported object with a proxy that mimics CSS module support without doing any class renaming. - css?: "onimportcss" | "facade"; + css?: 'onimportcss' | 'facade'; // bun’s filesystem router router?: Router; @@ -893,7 +893,7 @@ type Define = { // When "*", all environment variables will be automatically injected into the JavaScript loader // When a string like "NEXT_PUBLIC_", only environment variables starting with that prefix will be injected - ".env": string | "*"; + '.env': string | '*'; // These environment variables will be injected into the JavaScript loader // These are the equivalent of Webpack’s resolve.alias and esbuild’s --define. @@ -1117,7 +1117,7 @@ export interface Install { globalBinDir: string; cache: Cache; lockfile: Lockfile; - logLevel: "debug" | "error" | "warn"; + logLevel: 'debug' | 'error' | 'warn'; } type Registry = @@ -1138,7 +1138,7 @@ export interface Cache { } export interface Lockfile { - print?: "yarn"; + print?: 'yarn'; path: string; savePath: string; save: boolean; @@ -1371,7 +1371,7 @@ globalThis.reloadCount = reloadCount + 1; export default { fetch(req: Request) { return new Response(`Code reloaded ${reloadCount} times`, { - headers: { "content-type": "text/plain" }, + headers: {'content-type': 'text/plain'}, }); }, }; @@ -1413,7 +1413,7 @@ const reloadServer = (globalThis.reloadServer ||= (() => { const handler = { fetch(req: Request) { return new Response(`Code reloaded ${reloadCount} times`, { - headers: { "content-type": "text/plain" }, + headers: {'content-type': 'text/plain'}, }); }, }; @@ -1825,18 +1825,18 @@ This is an `"object"` loader. `object` loaders let you return a JS object that B Plugin implementation (`my-yaml-plugin.js`) ```js -import { plugin } from "bun"; +import {plugin} from 'bun'; plugin({ - name: "YAML", + name: 'YAML', setup(builder) { - const { load } = require("js-yaml"); - const { readFileSync } = require("fs"); + const {load} = require('js-yaml'); + const {readFileSync} = require('fs'); // Run this function on any import that ends with .yaml or .yml - builder.onLoad({ filter: /\.(yaml|yml)$/ }, (args) => { + builder.onLoad({filter: /\.(yaml|yml)$/}, (args) => { // Read the YAML file from disk - const text = readFileSync(args.path, "utf8"); + const text = readFileSync(args.path, 'utf8'); // parse the YAML file with js-yaml const exports = load(text); @@ -1846,7 +1846,7 @@ plugin({ exports, // we're returning an object - loader: "object", + loader: 'object', }; }); }, @@ -1856,8 +1856,8 @@ plugin({ Plugin usage: ```js -import "./my-yaml-plugin.js"; -import { hello } from "./myfile.yaml"; +import './my-yaml-plugin.js'; +import {hello} from './myfile.yaml'; console.log(hello); // "world" ``` @@ -1869,25 +1869,25 @@ This is a `"js"` loader, which lets you return a JS string or `ArrayBufferView` Plugin implementation (`myplugin.js`) ```js -import { plugin } from "bun"; +import {plugin} from 'bun'; await plugin({ - name: "svelte loader", + name: 'svelte loader', async setup(builder) { - const { compile } = await import("svelte/compiler"); - const { readFileSync } = await import("fs"); + const {compile} = await import('svelte/compiler'); + const {readFileSync} = await import('fs'); // Register a loader for .svelte files - builder.onLoad({ filter: /\.svelte$/ }, ({ path }) => ({ + builder.onLoad({filter: /\.svelte$/}, ({path}) => ({ // Run the Svelte compiler on the import path - contents: compile(readFileSync(path, "utf8"), { + contents: compile(readFileSync(path, 'utf8'), { filename: path, - generate: "ssr", + generate: 'ssr', }).js.code, // Set the loader to "js" // This runs it through Bun's transpiler - loader: "js", + loader: 'js', })); }, }); @@ -1898,8 +1898,8 @@ Note: in a production implementation, you'd want to cache the compiled output an Plugin usage: ```js -import "./myplugin.js"; -import MySvelteComponent from "./component.svelte"; +import './myplugin.js'; +import MySvelteComponent from './component.svelte'; console.log(mySvelteComponent.render()); ``` @@ -1911,15 +1911,15 @@ Bun's loader API interface is loosely based on [esbuild](https://esbuild.github. MDX: ```jsx -import { plugin } from "bun"; -import { renderToStaticMarkup } from "react-dom/server"; +import {plugin} from 'bun'; +import {renderToStaticMarkup} from 'react-dom/server'; // it's the esbuild plugin, but it works using Bun's transpiler. -import mdx from "@mdx-js/esbuild"; +import mdx from '@mdx-js/esbuild'; plugin(mdx()); -import Foo from "./bar.mdx"; +import Foo from './bar.mdx'; console.log(renderToStaticMarkup(<Foo />)); ``` @@ -1932,11 +1932,11 @@ At the top-level, a `plugin` function exported from `"bun"` expects a `"name"` s For plugins to automatically activate, the `plugin` function must be from an import statement like this: ```js -import { plugin } from "bun"; +import {plugin} from 'bun'; // This automatically activates on import plugin({ - name: "my plugin", + name: 'my plugin', setup(builder) {}, }); @@ -2007,8 +2007,8 @@ Bun.serve({ Node: ```ts -require("http") - .createServer((req, res) => res.end("bun!")) +require('http') + .createServer((req, res) => res.end('bun!')) .listen(8080); ``` @@ -2028,7 +2028,7 @@ If the file used to start bun has a default export with a `fetch` function, it w // hi.js export default { fetch(req) { - return new Response("HI!"); + return new Response('HI!'); }, }; @@ -2042,7 +2042,7 @@ export default { ```ts Bun.serve({ fetch(req) { - return new Response("HI!"); + return new Response('HI!'); }, }); ``` @@ -2062,10 +2062,10 @@ It will hopefully make it easier to debug issues with bun until bun gets debugge ```js Bun.serve({ fetch(req) { - throw new Error("woops!"); + throw new Error('woops!'); }, error(error: Error) { - return new Response("Uh oh!!\n" + error.toString(), { status: 500 }); + return new Response('Uh oh!!\n' + error.toString(), {status: 500}); }, }); ``` @@ -2077,7 +2077,7 @@ To stop the server, call `server.stop()`: ```ts const server = Bun.serve({ fetch() { - return new Response("HI!"); + return new Response('HI!'); }, }); @@ -2093,20 +2093,20 @@ Example: ```ts Bun.serve({ fetch(req) { - return new Response("Hello!!!"); + return new Response('Hello!!!'); }, /** * File path to a TLS key * * To enable TLS, this option is required. */ - keyFile: "./key.pem", + keyFile: './key.pem', /** * File path to a TLS certificate * * To enable TLS, this option is required. */ - certFile: "./cert.pem", + certFile: './cert.pem', /** * Optional SSL options @@ -2153,7 +2153,7 @@ Bun.serve({ // When upgrading, we return undefined since we don't want to send a Response return; - return new Response("Regular HTTP response"); + return new Response('Regular HTTP response'); }, }); ``` @@ -2167,45 +2167,45 @@ type User = { Bun.serve<User>({ fetch(req, server) { - if (req.url === "/chat") { + if (req.url === '/chat') { if ( server.upgrade(req, { // This User object becomes ws.data data: { - name: new URL(req.url).searchParams.get("name") || "Friend", + name: new URL(req.url).searchParams.get('name') || 'Friend', }, // Pass along some headers to the client headers: { - "Set-Cookie": "name=" + new URL(req.url).searchParams.get("name"), + 'Set-Cookie': 'name=' + new URL(req.url).searchParams.get('name'), }, }) ) return; } - return new Response("Expected a websocket connection", { status: 400 }); + return new Response('Expected a websocket connection', {status: 400}); }, websocket: { open(ws) { - console.log("WebSocket opened"); + console.log('WebSocket opened'); // subscribe to "the-group-chat" topic - ws.subscribe("the-group-chat"); + ws.subscribe('the-group-chat'); }, message(ws, message) { // In a group chat, we want to broadcast to everyone // so we use publish() - ws.publish("the-group-chat", `${ws.data.name}: ${message}`); + ws.publish('the-group-chat', `${ws.data.name}: ${message}`); }, close(ws, code, reason) { - ws.publish("the-group-chat", `${ws.data.name} left the chat`); + ws.publish('the-group-chat', `${ws.data.name} left the chat`); }, drain(ws) { - console.log("Please send me data. I am ready to receive it."); + console.log('Please send me data. I am ready to receive it.'); }, // enable compression @@ -2277,9 +2277,7 @@ For server websocket connections, Bun exposes a `ServerWebSocket` class which is ```ts Bun.serve({ fetch(req, server) { - if ( - server.upgrade(req, { headers: { "Set-Cookie": "name=HiThereMyNameIs" } }) - ) + if (server.upgrade(req, {headers: {'Set-Cookie': 'name=HiThereMyNameIs'}})) return; }, websocket: { @@ -2297,7 +2295,7 @@ The web-standard `WebSocket` API does not let you specify headers. `ServerWebSocket` has `publish()`, `subscribe()`, and `unsubscribe` methods which let you broadcast the same message to all clients connected to a topic in one line of code. ```ts -ws.publish("stock-prices/GOOG", `${price}`); +ws.publish('stock-prices/GOOG', `${price}`); ``` ##### Backpressure @@ -2314,7 +2312,7 @@ You can also enable/disable compression per message with the `compress` option: ```ts // this will compress -ws.send("Hello".repeat(1000), true); +ws.send('Hello'.repeat(1000), true); ``` `WebSocket.send` returns `undefined` and does not indicate backpressure, which can cause issues if you are sending a lot of data. @@ -2348,11 +2346,11 @@ The HTTP server and server-side websockets are based on [uWebSockets](https://gi `Bun.spawn` lets you quickly spawn a process. Available as of Bun v0.2.0. ```ts -import { spawn } from "bun"; +import {spawn} from 'bun'; -const { stdout } = spawn(["esbuild"], { +const {stdout} = spawn(['esbuild'], { stdin: await fetch( - "https://raw.githubusercontent.com/oven-sh/bun/main/examples/hashing.js" + 'https://raw.githubusercontent.com/oven-sh/bun/main/examples/hashing.js' ), }); @@ -2383,9 +2381,9 @@ spawnSync echo hi 1.47 ms/iter (1.14 ms … 2.64 ms) 1.57 ms 2.37 ms Synchronous example: ```ts -import { spawnSync } from "bun"; +import {spawnSync} from 'bun'; -const { stdout } = spawnSync(["echo", "hi"]); +const {stdout} = spawnSync(['echo', 'hi']); // When using spawnSync, stdout is a Buffer // this lets you read from it synchronously @@ -2397,24 +2395,24 @@ console.log(text); // "hi\n" You can pass an object as the second argument to customize the process: ```ts -import { spawn } from "bun"; +import {spawn} from 'bun'; -const { stdout } = spawn(["printenv", "FOO"], { - cwd: "/tmp", +const {stdout} = spawn(['printenv', 'FOO'], { + cwd: '/tmp', env: { ...process.env, - FOO: "bar", + FOO: 'bar', }, // Disable stdin stdin: null, // Allow us to read from stdout - stdout: "pipe", + stdout: 'pipe', // Point stderr to write to "/tmp/stderr.log" - stderr: Bun.file("/tmp/stderr.log"), + stderr: Bun.file('/tmp/stderr.log'), }); const text = await new Response(stdout).text(); @@ -2424,12 +2422,12 @@ console.log(text); // "bar\n" You can also pass a `Bun.file` for `stdin`: ```ts -import { spawn, file, write } from "bun"; +import {spawn, file, write} from 'bun'; -await write("/tmp/foo.txt", "hi"); -const { stdout } = spawn(["cat"], { +await write('/tmp/foo.txt', 'hi'); +const {stdout} = spawn(['cat'], { // Set /tmp/foo.txt as stdin - stdin: file("/tmp/foo.txt"), + stdin: file('/tmp/foo.txt'), }); const text = await new Response(stdout).text(); @@ -2439,11 +2437,11 @@ console.log(text); // "hi\n" `stdin` also accepts a TypedArray: ```ts -import { spawn } from "bun"; +import {spawn} from 'bun'; -const { stdout } = spawn(["cat"], { - stdin: new TextEncoder().encode("hi"), - stdout: "pipe", +const {stdout} = spawn(['cat'], { + stdin: new TextEncoder().encode('hi'), + stdout: 'pipe', }); const text = await new Response(stdout).text(); @@ -2455,16 +2453,16 @@ console.log(text); // "hi\n" > :warning: **This API is a little buggy right now** ```ts -import { spawn } from "bun"; +import {spawn} from 'bun'; -const { stdin, stdout } = spawn(["cat"], { - stdin: "pipe", - stdout: "pipe", +const {stdin, stdout} = spawn(['cat'], { + stdin: 'pipe', + stdout: 'pipe', }); // You can pass it strings or TypedArrays // Write "hi" to stdin -stdin.write("hi"); +stdin.write('hi'); // By default, stdin is buffered so you need to call flush() to send it stdin.flush(true); @@ -2551,15 +2549,15 @@ interface Subprocess { Find the path to an executable, similar to typing `which` in your terminal. ```ts -const ls = Bun.which("ls"); +const ls = Bun.which('ls'); console.log(ls); // "/usr/bin/ls" ``` `Bun.which` defaults the `PATH` to the current `PATH` environment variable, but you can customize it ```ts -const ls = Bun.which("ls", { - PATH: "/usr/local/bin:/usr/bin:/bin", +const ls = Bun.which('ls', { + PATH: '/usr/local/bin:/usr/bin:/bin', }); console.log(ls); // "/usr/bin/ls" ``` @@ -2567,9 +2565,9 @@ console.log(ls); // "/usr/bin/ls" `Bun.which` also accepts a `cwd` option to search for the binary in a specific directory. ```ts -const ls = Bun.which("ls", { - cwd: "/tmp", - PATH: "", +const ls = Bun.which('ls', { + cwd: '/tmp', + PATH: '', }); console.log(ls); // null @@ -2584,20 +2582,20 @@ Start a TCP server with `Bun.listen`: ```ts // The server Bun.listen({ - hostname: "localhost", + hostname: 'localhost', port: 8080, socket: { open(socket) { - socket.write("hello world"); + socket.write('hello world'); }, data(socket, data) { console.log(data instanceof Uint8Array); // true }, drain(socket) { - console.log("gimme more data"); + console.log('gimme more data'); }, close(socket) { - console.log("goodbye!"); + console.log('goodbye!'); }, }, // This is a TLS socket @@ -2611,7 +2609,7 @@ Bun.listen({ ```ts // The client Bun.connect({ - hostname: "localhost", + hostname: 'localhost', port: 8080, socket: { @@ -2619,21 +2617,21 @@ Bun.connect({ socket.write("hello server, i'm the client!"); }, data(socket, message) { - socket.write("thanks for the message! Sincerely, " + socket.data.name); + socket.write('thanks for the message! Sincerely, ' + socket.data.name); }, drain(socket) { - console.log("my socket is ready for more data"); + console.log('my socket is ready for more data'); }, close(socket) { - console.log(""); + console.log(''); }, timeout(socket) { - console.log("socket timed out"); + console.log('socket timed out'); }, }, data: { - name: "Clienty McClientface", + name: 'Clienty McClientface', }, }); ``` @@ -2655,7 +2653,7 @@ Bun.listen({ close(socket) {}, error(socket, error) {}, }, - hostname: "localhost", + hostname: 'localhost', port: 8080, }); ``` @@ -2667,7 +2665,7 @@ How do you pass per-socket data to each socket object? `**data**` is a property on the `TCPSocket` & `TLSSocket` object that you can use to store per-socket data. ```ts -socket.data = { name: "Clienty McClientface" }; +socket.data = {name: 'Clienty McClientface'}; ``` You can assign a default value to `data` in the `connect` or `listen` options. @@ -2680,7 +2678,7 @@ Bun.listen({ }, }, data: { - name: "Servery McServerface", + name: 'Servery McServerface', }, }); ``` @@ -2691,16 +2689,16 @@ Bun.listen({ ```ts const socket = Bun.connect({ - hostname: "localhost", + hostname: 'localhost', port: 8080, socket: { data(socket, msg) { - console.log("wow i got a message!"); + console.log('wow i got a message!'); // this will be called the next time the server sends a message socket.reload({ data(socket) { - console.log("okay, not so surprising this time"); + console.log('okay, not so surprising this time'); }, }); }, @@ -2717,29 +2715,29 @@ Your TCP client/server will have abysmal performance if you don't consider buffe For example, this: ```ts -socket.write("h"); -socket.write("e"); -socket.write("l"); -socket.write("l"); -socket.write("o"); +socket.write('h'); +socket.write('e'); +socket.write('l'); +socket.write('l'); +socket.write('o'); ``` Performs significantly worse than: ```ts -socket.write("hello"); +socket.write('hello'); ``` To simplify this for now, consider using `ArrayBufferSink` with the `{stream: true}` option: ```ts -const sink = new ArrayBufferSink({ stream: true, highWaterMark: 1024 }); +const sink = new ArrayBufferSink({stream: true, highWaterMark: 1024}); -sink.write("h"); -sink.write("e"); -sink.write("l"); -sink.write("l"); -sink.write("o"); +sink.write('h'); +sink.write('e'); +sink.write('l'); +sink.write('l'); +sink.write('o'); queueMicrotask(() => { var data = sink.flush(); @@ -2759,9 +2757,9 @@ Builtin buffering is planned in a future version of Bun. This function was added in Bun v0.2.2. ```ts -import { peek } from "bun"; +import {peek} from 'bun'; -const promise = Promise.resolve("hi"); +const promise = Promise.resolve('hi'); // no await! const result = peek(promise); @@ -2772,10 +2770,10 @@ console.log(result); // "hi" `Bun.peek` is useful for performance-sensitive code that wants to reduce the number of extra microticks. It's an advanced API and you probably shouldn't use it unless you know what you're doing. ```ts -import { peek } from "bun"; -import { expect, test } from "bun:test"; +import {peek} from 'bun'; +import {expect, test} from 'bun:test'; -test("peek", () => { +test('peek', () => { const promise = Promise.resolve(true); // no await necessary! @@ -2797,27 +2795,27 @@ test("peek", () => { // - returns the error // - does not mark the promise as handled const rejected = Promise.reject( - new Error("Succesfully tested promise rejection") + new Error('Succesfully tested promise rejection') ); - expect(peek(rejected).message).toBe("Succesfully tested promise rejection"); + expect(peek(rejected).message).toBe('Succesfully tested promise rejection'); }); ``` `peek.status` lets you read the status of a promise without resolving it. ```ts -import { peek } from "bun"; -import { expect, test } from "bun:test"; +import {peek} from 'bun'; +import {expect, test} from 'bun:test'; -test("peek.status", () => { +test('peek.status', () => { const promise = Promise.resolve(true); - expect(peek.status(promise)).toBe("fulfilled"); + expect(peek.status(promise)).toBe('fulfilled'); const pending = new Promise(() => {}); - expect(peek.status(pending)).toBe("pending"); + expect(peek.status(pending)).toBe('pending'); - const rejected = Promise.reject(new Error("oh nooo")); - expect(peek.status(rejected)).toBe("rejected"); + const rejected = Promise.reject(new Error('oh nooo')); + expect(peek.status(rejected)).toBe('rejected'); }); ``` @@ -2851,24 +2849,24 @@ All this complexity is handled by a single function. ```ts // Write "Hello World" to output.txt -await Bun.write("output.txt", "Hello World"); +await Bun.write('output.txt', 'Hello World'); ``` ```ts // log a file to stdout -await Bun.write(Bun.stdout, Bun.file("input.txt")); +await Bun.write(Bun.stdout, Bun.file('input.txt')); ``` ```ts // write the HTTP response body to disk -await Bun.write("index.html", await fetch("http://example.com")); +await Bun.write('index.html', await fetch('http://example.com')); // this does the same thing -await Bun.write(Bun.file("index.html"), await fetch("http://example.com")); +await Bun.write(Bun.file('index.html'), await fetch('http://example.com')); ``` ```ts // copy input.txt to output.txt -await Bun.write("output.txt", Bun.file("input.txt")); +await Bun.write('output.txt', Bun.file('input.txt')); ``` ## bun:sqlite (SQLite3 module) @@ -2892,35 +2890,35 @@ Installation: Example: ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; -const db = new Database("mydb.sqlite"); +const db = new Database('mydb.sqlite'); db.run( - "CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)" + 'CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)' ); -db.run("INSERT INTO foo (greeting) VALUES (?)", "Welcome to bun!"); -db.run("INSERT INTO foo (greeting) VALUES (?)", "Hello World!"); +db.run('INSERT INTO foo (greeting) VALUES (?)', 'Welcome to bun!'); +db.run('INSERT INTO foo (greeting) VALUES (?)', 'Hello World!'); // get the first row -db.query("SELECT * FROM foo").get(); +db.query('SELECT * FROM foo').get(); // { id: 1, greeting: "Welcome to bun!" } // get all rows -db.query("SELECT * FROM foo").all(); +db.query('SELECT * FROM foo').all(); // [ // { id: 1, greeting: "Welcome to bun!" }, // { id: 2, greeting: "Hello World!" }, // ] // get all rows matching a condition -db.query("SELECT * FROM foo WHERE greeting = ?").all("Welcome to bun!"); +db.query('SELECT * FROM foo WHERE greeting = ?').all('Welcome to bun!'); // [ // { id: 1, greeting: "Welcome to bun!" }, // ] // get first row matching a named condition -db.query("SELECT * FROM foo WHERE greeting = $greeting").get({ - $greeting: "Welcome to bun!", +db.query('SELECT * FROM foo WHERE greeting = $greeting').get({ + $greeting: 'Welcome to bun!', }); // [ // { id: 1, greeting: "Welcome to bun!" }, @@ -3007,52 +3005,52 @@ constructor( To open or create a SQLite3 database: ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; -const db = new Database("mydb.sqlite"); +const db = new Database('mydb.sqlite'); ``` Open an in-memory database: ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // all of these do the same thing -let db = new Database(":memory:"); +let db = new Database(':memory:'); let db = new Database(); -let db = new Database(""); +let db = new Database(''); ``` Open read-write and throw if the database doesn't exist: ```ts -import { Database } from "bun:sqlite"; -const db = new Database("mydb.sqlite", { readwrite: true }); +import {Database} from 'bun:sqlite'; +const db = new Database('mydb.sqlite', {readwrite: true}); ``` Open read-only and throw if the database doesn't exist: ```ts -import { Database } from "bun:sqlite"; -const db = new Database("mydb.sqlite", { readonly: true }); +import {Database} from 'bun:sqlite'; +const db = new Database('mydb.sqlite', {readonly: true}); ``` Open read-write, don't throw if new file: ```ts -import { Database } from "bun:sqlite"; -const db = new Database("mydb.sqlite", { readonly: true, create: true }); +import {Database} from 'bun:sqlite'; +const db = new Database('mydb.sqlite', {readonly: true, create: true}); ``` Open a database from a `Uint8Array`: ```ts -import { Database } from "bun:sqlite"; -import { readFileSync } from "fs"; +import {Database} from 'bun:sqlite'; +import {readFileSync} from 'fs'; // unlike passing a filepath, this will not persist any changes to disk // it will be read-write but not persistent -const db = new Database(readFileSync("mydb.sqlite")); +const db = new Database(readFileSync('mydb.sqlite')); ``` Close a database: @@ -3086,24 +3084,24 @@ This intended to make it easier for `bun:sqlite` to be fast by default. Calling You can bind parameters on any call to a statement. ```js -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // generate some data let db = new Database(); db.run( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)' ); -db.run("INSERT INTO foo (greeting) VALUES ($greeting)", { - $greeting: "Welcome to bun", +db.run('INSERT INTO foo (greeting) VALUES ($greeting)', { + $greeting: 'Welcome to bun', }); // get the query -const stmt = db.query("SELECT * FROM foo WHERE greeting = ?"); +const stmt = db.query('SELECT * FROM foo WHERE greeting = ?'); // run the query -stmt.all("Welcome to bun!"); -stmt.get("Welcome to bun!"); -stmt.run("Welcome to bun!"); +stmt.all('Welcome to bun!'); +stmt.get('Welcome to bun!'); +stmt.run('Welcome to bun!'); ``` #### Database.prototype.prepare @@ -3113,19 +3111,19 @@ stmt.run("Welcome to bun!"); Unlike `query()`, this does not cache the compiled query. ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // generate some data let db = new Database(); db.run( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)' ); // compile the prepared statement -const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?"); +const stmt = db.prepare('SELECT * FROM foo WHERE bar = ?'); // run the prepared statement -stmt.all("baz"); +stmt.all('baz'); ``` Internally, this calls [`sqlite3_prepare_v3`](https://www.sqlite.org/c3ref/prepare.html). @@ -3148,27 +3146,27 @@ This is useful for things like Creating a table: ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; let db = new Database(); db.exec( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)' ); ``` Inserting one row: ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; let db = new Database(); db.exec( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)' ); // insert one row -db.exec("INSERT INTO foo (greeting) VALUES ($greeting)", { - $greeting: "Welcome to bun", +db.exec('INSERT INTO foo (greeting) VALUES ($greeting)', { + $greeting: 'Welcome to bun', }); ``` @@ -3182,21 +3180,21 @@ Creates a function that always runs inside a transaction. When the function is i ```ts // setup -import { Database } from "bun:sqlite"; -const db = Database.open(":memory:"); +import {Database} from 'bun:sqlite'; +const db = Database.open(':memory:'); db.exec( - "CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)" + 'CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)' ); -const insert = db.prepare("INSERT INTO cats (name, age) VALUES ($name, $age)"); +const insert = db.prepare('INSERT INTO cats (name, age) VALUES ($name, $age)'); const insertMany = db.transaction((cats) => { for (const cat of cats) insert.run(cat); }); insertMany([ - { $name: "Joey", $age: 2 }, - { $name: "Sally", $age: 4 }, - { $name: "Junior", $age: 1 }, + {$name: 'Joey', $age: 2}, + {$name: 'Sally', $age: 4}, + {$name: 'Junior', $age: 1}, ]); ``` @@ -3204,31 +3202,31 @@ Transaction functions can be called from inside other transaction functions. Whe ```ts // setup -import { Database } from "bun:sqlite"; -const db = Database.open(":memory:"); +import {Database} from 'bun:sqlite'; +const db = Database.open(':memory:'); db.exec( - "CREATE TABLE expenses (id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT, dollars INTEGER);" + 'CREATE TABLE expenses (id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT, dollars INTEGER);' ); db.exec( - "CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)" + 'CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)' ); const newExpense = db.prepare( - "INSERT INTO expenses (note, dollars) VALUES (?, ?)" + 'INSERT INTO expenses (note, dollars) VALUES (?, ?)' ); -const insert = db.prepare("INSERT INTO cats (name, age) VALUES ($name, $age)"); +const insert = db.prepare('INSERT INTO cats (name, age) VALUES ($name, $age)'); const insertMany = db.transaction((cats) => { for (const cat of cats) insert.run(cat); }); const adopt = db.transaction((cats) => { - newExpense.run("adoption fees", 20); + newExpense.run('adoption fees', 20); insertMany(cats); // nested transaction }); adopt([ - { $name: "Joey", $age: 2 }, - { $name: "Sally", $age: 4 }, - { $name: "Junior", $age: 1 }, + {$name: 'Joey', $age: 2}, + {$name: 'Sally', $age: 4}, + {$name: 'Junior', $age: 1}, ]); ``` @@ -3256,16 +3254,16 @@ let db = new Database(); // write some data db.run( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)' ); -db.run("INSERT INTO foo VALUES (?)", "Welcome to bun!"); -db.run("INSERT INTO foo VALUES (?)", "Hello World!"); +db.run('INSERT INTO foo VALUES (?)', 'Welcome to bun!'); +db.run('INSERT INTO foo VALUES (?)', 'Hello World!'); const copy = db.serialize(); // => Uint8Array const db2 = new Database(copy); -db2.query("SELECT * FROM foo").all(); +db2.query('SELECT * FROM foo').all(); // => [ // { id: 1, greeting: "Welcome to bun!" }, // { id: 2, greeting: "Hello World!" }, @@ -3283,26 +3281,26 @@ Internally, it calls [`sqlite3_serialize`](https://www.sqlite.org/c3ref/serializ To load a SQLite extension, call `Database.prototype.loadExtension(name)`: ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; let db = new Database(); -db.loadExtension("myext"); +db.loadExtension('myext'); ``` If you're on macOS, you will need to first use a custom SQLite install (you can install with homebrew). By default, bun uses Apple's proprietary build of SQLite because it benchmarks about 50% faster. However, they disabled extension support, so you will need to have a custom build of SQLite to use extensions on macOS. ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // on macOS, this must be run before any other calls to `Database` // if called on linux, it will return true and do nothing // on linux it will still check that a string was passed -Database.setCustomSQLite("/path/to/sqlite.dylib"); +Database.setCustomSQLite('/path/to/sqlite.dylib'); let db = new Database(); -db.loadExtension("myext"); +db.loadExtension('myext'); ``` To install sqlite with homebrew: @@ -3329,18 +3327,18 @@ TLDR: You can bind parameters on any call to a statement. Named parameters and positional parameters are supported. Bound parameters are remembered between calls and reset the next time you pass parameters to bind. ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // setup let db = new Database(); db.run( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)' ); -db.run("INSERT INTO foo VALUES (?)", "Welcome to bun!"); -db.run("INSERT INTO foo VALUES (?)", "Hello World!"); +db.run('INSERT INTO foo VALUES (?)', 'Welcome to bun!'); +db.run('INSERT INTO foo VALUES (?)', 'Hello World!'); // Statement object -let statement = db.query("SELECT * FROM foo"); +let statement = db.query('SELECT * FROM foo'); // returns all the rows statement.all(); @@ -3357,23 +3355,23 @@ statement.run(); Calling `all()` on a `Statement` instance runs the query and returns the rows as an array of objects. ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // setup let db = new Database(); db.run( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)' ); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Welcome to bun!', 2); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Hello World!', 0); db.run( - "INSERT INTO foo (greeting, count) VALUES (?, ?)", - "Welcome to bun!!!!", + 'INSERT INTO foo (greeting, count) VALUES (?, ?)', + 'Welcome to bun!!!!', 2 ); // Statement object -let statement = db.query("SELECT * FROM foo WHERE count = ?"); +let statement = db.query('SELECT * FROM foo WHERE count = ?'); // return all the query results, binding 2 to the count parameter statement.all(2); @@ -3390,23 +3388,23 @@ Internally, this calls [`sqlite3_reset`](https://www.sqlite.org/capi3ref.html#sq Calling `values()` on a `Statement` instance runs the query and returns the rows as an array of arrays. ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // setup let db = new Database(); db.run( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)' ); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Welcome to bun!', 2); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Hello World!', 0); db.run( - "INSERT INTO foo (greeting, count) VALUES (?, ?)", - "Welcome to bun!!!!", + 'INSERT INTO foo (greeting, count) VALUES (?, ?)', + 'Welcome to bun!!!!', 2 ); // Statement object -let statement = db.query("SELECT * FROM foo WHERE count = ?"); +let statement = db.query('SELECT * FROM foo WHERE count = ?'); // return all the query results as an array of arrays, binding 2 to "count" statement.values(2); @@ -3416,10 +3414,10 @@ statement.values(2); // ] // Statement object, but with named parameters -let statement = db.query("SELECT * FROM foo WHERE count = $count"); +let statement = db.query('SELECT * FROM foo WHERE count = $count'); // return all the query results as an array of arrays, binding 2 to "count" -statement.values({ $count: 2 }); +statement.values({$count: 2}); // => [ // [ 1, "Welcome to bun!", 2 ], // [ 3, "Welcome to bun!!!!", 2 ], @@ -3433,33 +3431,33 @@ Internally, this calls [`sqlite3_reset`](https://www.sqlite.org/capi3ref.html#sq Calling `get()` on a `Statement` instance runs the query and returns the first result as an object. ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // setup let db = new Database(); db.run( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)' ); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Welcome to bun!', 2); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Hello World!', 0); db.run( - "INSERT INTO foo (greeting, count) VALUES (?, ?)", - "Welcome to bun!!!!", + 'INSERT INTO foo (greeting, count) VALUES (?, ?)', + 'Welcome to bun!!!!', 2 ); // Statement object -let statement = db.query("SELECT * FROM foo WHERE count = ?"); +let statement = db.query('SELECT * FROM foo WHERE count = ?'); // return the first row as an object, binding 2 to the count parameter statement.get(2); // => { id: 1, greeting: "Welcome to bun!", count: 2 } // Statement object, but with named parameters -let statement = db.query("SELECT * FROM foo WHERE count = $count"); +let statement = db.query('SELECT * FROM foo WHERE count = $count'); // return the first row as an object, binding 2 to the count parameter -statement.get({ $count: 2 }); +statement.get({$count: 2}); // => { id: 1, greeting: "Welcome to bun!", count: 2 } ``` @@ -3472,23 +3470,23 @@ Calling `run()` on a `Statement` instance runs the query and returns nothing. This is useful if you want to repeatedly run a query, but don't care about the results. ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // setup let db = new Database(); db.run( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)' ); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Welcome to bun!', 2); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Hello World!', 0); db.run( - "INSERT INTO foo (greeting, count) VALUES (?, ?)", - "Welcome to bun!!!!", + 'INSERT INTO foo (greeting, count) VALUES (?, ?)', + 'Welcome to bun!!!!', 2 ); // Statement object (TODO: use a better example query) -let statement = db.query("SELECT * FROM foo"); +let statement = db.query('SELECT * FROM foo'); // run the query, returning nothing statement.run(); @@ -3505,23 +3503,23 @@ After a statement has been finalized, it cannot be used for any further queries. It is a good idea to finalize a statement when you are done with it, but the garbage collector will do it for you if you don't. ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // setup let db = new Database(); db.run( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)' ); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Welcome to bun!', 2); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Hello World!', 0); db.run( - "INSERT INTO foo (greeting, count) VALUES (?, ?)", - "Welcome to bun!!!!", + 'INSERT INTO foo (greeting, count) VALUES (?, ?)', + 'Welcome to bun!!!!', 2 ); // Statement object -let statement = db.query("SELECT * FROM foo WHERE count = ?"); +let statement = db.query('SELECT * FROM foo WHERE count = ?'); statement.finalize(); @@ -3534,23 +3532,23 @@ statement.run(); Calling `toString()` on a `Statement` instance prints the expanded SQL query. This is useful for debugging. ```ts -import { Database } from "bun:sqlite"; +import {Database} from 'bun:sqlite'; // setup let db = new Database(); db.run( - "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)" + 'CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)' ); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2); -db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Welcome to bun!', 2); +db.run('INSERT INTO foo (greeting, count) VALUES (?, ?)', 'Hello World!', 0); db.run( - "INSERT INTO foo (greeting, count) VALUES (?, ?)", - "Welcome to bun!!!!", + 'INSERT INTO foo (greeting, count) VALUES (?, ?)', + 'Welcome to bun!!!!', 2 ); // Statement object -const statement = db.query("SELECT * FROM foo WHERE count = ?"); +const statement = db.query('SELECT * FROM foo WHERE count = ?'); console.log(statement.toString()); // => "SELECT * FROM foo WHERE count = NULL" @@ -3582,7 +3580,7 @@ Internally, this calls [`sqlite3_expanded_sql`](https://www.sqlite.org/capi3ref. This snippet prints sqlite3's version number: ```ts -import { dlopen, FFIType, suffix } from "bun:ffi"; +import {dlopen, FFIType, suffix} from 'bun:ffi'; // `suffix` is either "dylib", "so", or "dll" depending on the platform // you don't have to use "suffix", it's just there for convenience @@ -3651,7 +3649,7 @@ zig build-lib add.zig -dynamic -OReleaseFast Pass `dlopen` the path to the shared library and the list of symbols you want to import. ```ts -import { dlopen, FFIType, suffix } from "bun:ffi"; +import {dlopen, FFIType, suffix} from 'bun:ffi'; const path = `libadd.${suffix}`; @@ -3793,7 +3791,7 @@ getVersion(); If you have multiple function pointers, you can define them all at once with `linkSymbols`: ```ts -import { linkSymbols } from "bun:ffi"; +import {linkSymbols} from 'bun:ffi'; // getVersionPtrs defined elsewhere const [majorPtr, minorPtr, patchPtr] = getVersionPtrs(); @@ -3801,7 +3799,7 @@ const [majorPtr, minorPtr, patchPtr] = getVersionPtrs(); const lib = linkSymbols({ // Unlike with dlopen(), the names here can be whatever you want getMajor: { - returns: "cstring", + returns: 'cstring', args: [], // Since this doesn't use dlsym(), you have to provide a valid ptr @@ -3810,12 +3808,12 @@ const lib = linkSymbols({ ptr: majorPtr, }, getMinor: { - returns: "cstring", + returns: 'cstring', args: [], ptr: minorPtr, }, getPatch: { - returns: "cstring", + returns: 'cstring', args: [], ptr: patchPtr, }, @@ -3833,27 +3831,27 @@ const [major, minor, patch] = [ Bun v0.2.3 added `JSCallback` which lets you create JavaScript callback functions that you can pass to C/FFI functions. The C/FFI function can call into the JavaScript/TypeScript code. This is useful for asynchronous code or otherwise when you want to call into JavaScript code from C. ```ts -import { dlopen, JSCallback, ptr, CString } from "bun:ffi"; +import {dlopen, JSCallback, ptr, CString} from 'bun:ffi'; const { - symbols: { search }, + symbols: {search}, close, -} = dlopen("libmylib", { +} = dlopen('libmylib', { search: { - returns: "usize", - args: ["cstring", "callback"], + returns: 'usize', + args: ['cstring', 'callback'], }, }); const searchIterator = new JSCallback( (ptr, length) => /hello/.test(new CString(ptr, length)), { - returns: "bool", - args: ["ptr", "usize"], + returns: 'bool', + args: ['ptr', 'usize'], } ); -const str = Buffer.from("wwutwutwutwutwutwutwutwutwutwutut\0", "utf8"); +const str = Buffer.from('wwutwutwutwutwutwutwutwutwutwutut\0', 'utf8'); if (search(ptr(str), searchIterator)) { // found a match! } @@ -3871,12 +3869,12 @@ For a slight performance boost, directly pass `JSCallback.prototype.ptr` instead ```ts const onResolve = new JSCallback((arg) => arg === 42, { - returns: "bool", - args: ["i32"], + returns: 'bool', + args: ['i32'], }); const setOnResolve = new CFunction({ - returns: "bool", - args: ["function"], + returns: 'bool', + args: ['function'], ptr: myNativeLibrarySetOnResolve, }); @@ -3910,7 +3908,7 @@ If you pass a `BigInt` to a function, it will be converted to a `number` **To convert from a TypedArray to a pointer**: ```ts -import { ptr } from "bun:ffi"; +import {ptr} from 'bun:ffi'; let myTypedArray = new Uint8Array(32); const myPtr = ptr(myTypedArray); ``` @@ -3918,7 +3916,7 @@ const myPtr = ptr(myTypedArray); **To convert from a pointer to an ArrayBuffer**: ```ts -import { ptr, toArrayBuffer } from "bun:ffi"; +import {ptr, toArrayBuffer} from 'bun:ffi'; let myTypedArray = new Uint8Array(32); const myPtr = ptr(myTypedArray); @@ -3934,7 +3932,7 @@ You have two options. For long-lived pointers, a `DataView` is the fastest option: ```ts -import { toArrayBuffer } from "bun:ffi"; +import {toArrayBuffer} from 'bun:ffi'; let myDataView = new DataView(toArrayBuffer(myPtr, 0, 32)); console.log( @@ -3950,7 +3948,7 @@ For short-lived pointers, `read` is the fastest option: _Available in Bun v0.1.12+_ ```ts -import { read } from "bun:ffi"; +import {read} from 'bun:ffi'; console.log( // ptr, byteOffset @@ -3998,7 +3996,7 @@ typedef void (*JSTypedArrayBytesDeallocator)(void *bytes, void *deallocatorConte ``` ```ts -import { toArrayBuffer } from "bun:ffi"; +import {toArrayBuffer} from 'bun:ffi'; // with a deallocatorContext: toArrayBuffer( @@ -4045,14 +4043,14 @@ Where FFI functions expect a pointer, pass a TypedArray of equivalent size Easymode: ```ts -import { dlopen, FFIType } from "bun:ffi"; +import {dlopen, FFIType} from 'bun:ffi'; const { - symbols: { encode_png }, + symbols: {encode_png}, } = dlopen(myLibraryPath, { encode_png: { // FFIType's can be specified as strings too - args: ["ptr", "u32", "u32"], + args: ['ptr', 'u32', 'u32'], returns: FFIType.ptr, }, }); @@ -4079,14 +4077,14 @@ The [auto-generated wrapper](https://github.com/oven-sh/bun/blob/6a65631cbdcae75 If you don't want the automatic conversion or you want a pointer to a specific byte offset within the TypedArray, you can also directly get the pointer to the TypedArray: ```ts -import { dlopen, FFIType, ptr } from "bun:ffi"; +import {dlopen, FFIType, ptr} from 'bun:ffi'; const { - symbols: { encode_png }, + symbols: {encode_png}, } = dlopen(myLibraryPath, { encode_png: { // FFIType's can be specified as strings too - args: ["ptr", "u32", "u32"], + args: ['ptr', 'u32', 'u32'], returns: FFIType.ptr, }, }); @@ -4124,7 +4122,7 @@ const out = encode_png( let png = new Uint8Array(toArrayBuffer(out)); // save it to disk: -await Bun.write("out.png", png); +await Bun.write('out.png', png); ``` ##### Not implemented yet @@ -4143,14 +4141,14 @@ You can see the status of [this here](https://github.com/oven-sh/bun/issues/158) Loading Node-API modules in Bun.js works the same as in Node.js: ```js -const napi = require("./my-node-module.node"); +const napi = require('./my-node-module.node'); ``` You can also use `process.dlopen`: ```js -let mod = { exports: {} }; -process.dlopen(mod, "./my-node-module.node"); +let mod = {exports: {}}; +process.dlopen(mod, './my-node-module.node'); ``` As part of that work, Bun.js also polyfills the [`detect-libc`](https://npmjs.com/package/detect-libc) package, which is used by many Node-API modules to detect which `.node` binding to `require`. @@ -4163,10 +4161,10 @@ When requiring a `*.node` module, Bun's JavaScript transpiler transforms the `re ```js // this is the input -require("./my-node-module.node"); +require('./my-node-module.node'); // this is the output -import.meta.require("./my-node-module.node"); +import.meta.require('./my-node-module.node'); ``` Bun doesn't currently support dynamic requires, but `import.meta.require` is an escape hatch for that. It uses a [JavaScriptCore built-in function](https://github.com/oven-sh/bun/blob/aa87d40f4b7fdfb52575f44d151906ddba6a82d0/src/javascript/jsc/bindings/builtins/js/JSZigGlobalObject.js#L26). @@ -4258,19 +4256,19 @@ This lets you transpile JavaScript, TypeScript, TSX, and JSX using Bun's transpi It is synchronous and runs in the same thread as other JavaScript code. ```js -const transpiler = new Bun.Transpiler({ loader: "jsx" }); -transpiler.transformSync("<div>hi!</div>"); +const transpiler = new Bun.Transpiler({loader: 'jsx'}); +transpiler.transformSync('<div>hi!</div>'); ``` ```js -import { __require as require } from "bun:wrap"; -import * as JSX from "react/jsx-dev-runtime"; +import {__require as require} from 'bun:wrap'; +import * as JSX from 'react/jsx-dev-runtime'; var jsx = require(JSX).jsxDEV; export default jsx( - "div", + 'div', { - children: "hi!", + children: 'hi!', }, undefined, false, @@ -4292,19 +4290,19 @@ If code uses a macro, it will potentially spawn a new copy of Bun.js' JavaScript Unless you're transpiling _many_ large files, you should probably use `Bun.Transpiler.transformSync`. The cost of the threadpool will often take longer than actually transpiling code. ```js -const transpiler = new Bun.Transpiler({ loader: "jsx" }); -await transpiler.transform("<div>hi!</div>"); +const transpiler = new Bun.Transpiler({loader: 'jsx'}); +await transpiler.transform('<div>hi!</div>'); ``` ```js -import { __require as require } from "bun:wrap"; -import * as JSX from "react/jsx-dev-runtime"; +import {__require as require} from 'bun:wrap'; +import * as JSX from 'react/jsx-dev-runtime'; var jsx = require(JSX).jsxDEV; export default jsx( - "div", + 'div', { - children: "hi!", + children: 'hi!', }, undefined, false, @@ -4316,7 +4314,7 @@ export default jsx( You can also pass a `Loader` as a string ```js -await transpiler.transform("<div>hi!</div>", "tsx"); +await transpiler.transform('<div>hi!</div>', 'tsx'); ``` #### `Bun.Transpiler.scan` @@ -4326,7 +4324,7 @@ This is a fast way to get a list of imports & exports used in a JavaScript/jsx o This function is synchronous. ```ts -const transpiler = new Bun.Transpiler({ loader: "ts" }); +const transpiler = new Bun.Transpiler({loader: 'ts'}); transpiler.scan(` import React from 'react'; @@ -4367,7 +4365,7 @@ This is a fast path for getting a list of imports used in a JavaScript/jsx or Ty This function is synchronous. ```ts -const transpiler = new Bun.Transpiler({ loader: "ts" }); +const transpiler = new Bun.Transpiler({loader: 'ts'}); transpiler.scanImports(` import React from 'react'; diff --git a/bench/bun.lockb b/bench/bun.lockb Binary files differnew file mode 100755 index 000000000..14530a5ec --- /dev/null +++ b/bench/bun.lockb diff --git a/bench/ffi/src/bun.lockb b/bench/ffi/src/bun.lockb Binary files differindex 184cb439c..28144fc51 100755 --- a/bench/ffi/src/bun.lockb +++ b/bench/ffi/src/bun.lockb diff --git a/bench/hot-module-reloading/css-stress-test/bun.lockb b/bench/hot-module-reloading/css-stress-test/bun.lockb Binary files differnew file mode 100755 index 000000000..9cad009bb --- /dev/null +++ b/bench/hot-module-reloading/css-stress-test/bun.lockb diff --git a/bench/hot-module-reloading/css-stress-test/pages/_app.tsx b/bench/hot-module-reloading/css-stress-test/pages/_app.tsx index 43d6a776a..c330a0155 100644 --- a/bench/hot-module-reloading/css-stress-test/pages/_app.tsx +++ b/bench/hot-module-reloading/css-stress-test/pages/_app.tsx @@ -1,3 +1,4 @@ +// @ts-nocheck import "../src/index.css"; import App from "next/app"; diff --git a/bench/hot-module-reloading/css-stress-test/pages/index.tsx b/bench/hot-module-reloading/css-stress-test/pages/index.tsx index 3ef84ffe5..afdaaae25 100644 --- a/bench/hot-module-reloading/css-stress-test/pages/index.tsx +++ b/bench/hot-module-reloading/css-stress-test/pages/index.tsx @@ -3,6 +3,7 @@ export function IndexPage() { return ( <Main productName={ + // @ts-ignore typeof location !== "undefined" ? location.search.substring(1) : "" } /> diff --git a/bench/hot-module-reloading/css-stress-test/src/main.tsx b/bench/hot-module-reloading/css-stress-test/src/main.tsx index 3b67cd111..2093d924f 100644 --- a/bench/hot-module-reloading/css-stress-test/src/main.tsx +++ b/bench/hot-module-reloading/css-stress-test/src/main.tsx @@ -1,11 +1,11 @@ -export const Main = ({ productName, cssInJS }) => { +export const Main = (props: { productName: string; cssInJS?: string }) => { return ( <> <header> <div className="Title">CSS HMR Stress Test!</div> <p className="Description"> This page visually tests how quickly a bundler can update{" "} - {cssInJS ? "CSS-in-JS" : "CSS"} over Hot Module Reloading. + {props.cssInJS ? "CSS-in-JS" : "CSS"} over Hot Module Reloading. </p> </header> <main className="main"> @@ -53,9 +53,9 @@ export const Main = ({ productName, cssInJS }) => { </div> <div className="Bundler-container"> - <div className="Bundler">{productName}</div> + <div className="Bundler">{props.productName}</div> <div className="Bundler-updateRate"> - {cssInJS ? "CSS-in-JS framework: " + cssInJS : ""} + {props.cssInJS ? "CSS-in-JS framework: " + props.cssInJS : ""} </div> </div> </footer> diff --git a/bench/hot-module-reloading/css-stress-test/tsconfig.json b/bench/hot-module-reloading/css-stress-test/tsconfig.json index 19d4ac2e6..289c8f710 100644 --- a/bench/hot-module-reloading/css-stress-test/tsconfig.json +++ b/bench/hot-module-reloading/css-stress-test/tsconfig.json @@ -1,6 +1,8 @@ { + "extends": "../../../tsconfig.base.json", "compilerOptions": { "baseUrl": ".", + "jsx": "react-jsx", "paths": {} } -} +}
\ No newline at end of file diff --git a/bench/scanner/bun.lockb b/bench/scanner/bun.lockb Binary files differindex 90bb78996..24eec21f4 100755 --- a/bench/scanner/bun.lockb +++ b/bench/scanner/bun.lockb diff --git a/bench/websocket-server/bun.lockb b/bench/websocket-server/bun.lockb Binary files differnew file mode 100755 index 000000000..8bf2ac8e6 --- /dev/null +++ b/bench/websocket-server/bun.lockb diff --git a/bench/websocket-server/package.json b/bench/websocket-server/package.json index 4f1dfa334..543047705 100644 --- a/bench/websocket-server/package.json +++ b/bench/websocket-server/package.json @@ -2,9 +2,6 @@ "name": "websocket-server", "module": "index.ts", "type": "module", - "devDependencies": { - "bun-types": "^0.2.0" - }, "dependencies": { "bufferutil": "^4.0.7", "utf-8-validate": "^5.0.10", diff --git a/bench/websocket-server/tsconfig.json b/bench/websocket-server/tsconfig.json index feee4b584..78465cc23 100644 --- a/bench/websocket-server/tsconfig.json +++ b/bench/websocket-server/tsconfig.json @@ -1,14 +1,4 @@ { - "compilerOptions": { - "lib": ["ESNext"], - "module": "esnext", - "target": "esnext", - "moduleResolution": "node", - - // so that if your project isn't using TypeScript, it still has autocomplete - "allowJs": true, - - // "bun-types" is the important part - "types": ["bun-types"] - } -} + "extends": "../../tsconfig.base.json", + "compilerOptions": {} +}
\ No newline at end of file Binary files differdiff --git a/examples/bun-hot-websockets.js b/examples/bun-hot-websockets.js index 1656d2eb5..7cdaf0f02 100644 --- a/examples/bun-hot-websockets.js +++ b/examples/bun-hot-websockets.js @@ -83,7 +83,7 @@ export default { headers: { "Content-Type": "text/html; charset=utf-8", }, - } + }, ); }, }; diff --git a/examples/cat.ts b/examples/cat.ts index a7d60b347..01a059ad0 100644 --- a/examples/cat.ts +++ b/examples/cat.ts @@ -1,6 +1,6 @@ import { resolve } from "path"; const { write, stdout, file } = Bun; -const { argv } = process; +import { argv } from "process"; -const path = resolve(argv.at(-1)); +const path = resolve(argv.at(-1)!); await write(stdout, file(path)); diff --git a/examples/html-rewriter.ts b/examples/html-rewriter.ts index a2a9d03fa..877b957b7 100644 --- a/examples/html-rewriter.ts +++ b/examples/html-rewriter.ts @@ -1,4 +1,5 @@ // Start a fast HTTP server from a function + Bun.serve({ async fetch(req) { const { pathname } = new URL(req.url); @@ -9,21 +10,21 @@ Bun.serve({ "Enter a path that starts with https:// or http://\n", { status: 400, - } + }, ); } const response = await fetch( req.url.substring("http://localhost:3000/".length), - req.clone() + req.clone(), ); return new HTMLRewriter() .on("a[href]", { - element(element: Element) { + element(element) { element.setAttribute( "href", - "https://www.youtube.com/watch?v=dQw4w9WgXcQ" + "https://www.youtube.com/watch?v=dQw4w9WgXcQ", ); }, }) diff --git a/examples/http-file.ts b/examples/http-file.ts index 130104534..fdf47f949 100644 --- a/examples/http-file.ts +++ b/examples/http-file.ts @@ -1,4 +1,4 @@ -import { file } from "bun"; +import { file, serve } from "bun"; serve({ fetch(req: Request) { diff --git a/examples/http-request-body.ts b/examples/http-request-body.ts index 6ce356ce0..b9a454889 100644 --- a/examples/http-request-body.ts +++ b/examples/http-request-body.ts @@ -6,11 +6,12 @@ serve({ const body = req.body; const writer = Bun.file(`upload.${Date.now()}.txt`).writer(); - for await (const chunk of body) { + for await (const chunk of body!) { writer.write(chunk); } const wrote = await writer.end(); + // @ts-ignore return Response.json({ wrote, type: req.headers.get("Content-Type") }); }, }); diff --git a/examples/lambda.ts b/examples/lambda.ts index ab2d5bb2b..da1a7d9ee 100644 --- a/examples/lambda.ts +++ b/examples/lambda.ts @@ -35,7 +35,7 @@ var Handler; try { Handler = await import(sourcefile); -} catch (e) { +} catch (e: any) { console.error("Error loading sourcefile:", e); try { await fetch( @@ -51,7 +51,7 @@ try { errorType: e.name, stackTrace: e?.stack?.split("\n") ?? [], }), - } + }, ); } catch (e2) { console.error("Error sending error to runtime:", e2); @@ -92,7 +92,7 @@ export default { errorType: e.name, stackTrace: e?.stack?.split("\n") ?? [], }), - } + }, ); } catch (e2) { console.error("Error sending error to runtime:", e2); @@ -109,7 +109,7 @@ if ("baseURI" in Handler.default) { var baseURL; try { baseURL = new URL(baseURLString); -} catch (e) { +} catch (e: any) { console.error("Error parsing baseURI:", e); try { await fetch( @@ -125,7 +125,7 @@ try { errorType: e.name, stackTrace: e?.stack?.split("\n") || [], }), - } + }, ); } catch (e2) { console.error("Error sending error to runtime:", e2); @@ -147,7 +147,7 @@ async function runHandler(response: Response) { }); // we are done with the Response object here // allow it to be GC'd - response = undefined; + (response as any) = undefined; var result: Response; try { @@ -155,10 +155,10 @@ async function runHandler(response: Response) { console.time(`[${traceID}] Run ${request.url}`); } result = handlerFunction(request, {}); - if (result && result.then) { + if (result && (result as any).then) { await result; } - } catch (e1) { + } catch (e1: any) { if (typeof process.env.VERBOSE !== "undefined") { console.error(`[${traceID}] Error running handler:`, e1); } @@ -172,7 +172,7 @@ async function runHandler(response: Response) { errorType: e1.name, stackTrace: e1?.stack?.split("\n") ?? [], }), - } + }, ).finally(noop); return; } finally { @@ -191,7 +191,7 @@ async function runHandler(response: Response) { errorType: "ExpectedResponseObject", stackTrace: [], }), - } + }, ); return; } @@ -202,9 +202,9 @@ async function runHandler(response: Response) { method: "POST", headers: result.headers, body: await result.blob(), - } + }, ); - result = undefined; + (result as any) = undefined; } while (true) { diff --git a/examples/macros/bun.lockb b/examples/macros/bun.lockb Binary files differnew file mode 100755 index 000000000..2e6de7391 --- /dev/null +++ b/examples/macros/bun.lockb diff --git a/examples/macros/components/covid19.tsx b/examples/macros/components/covid19.tsx index 52fee2ff3..330661c82 100644 --- a/examples/macros/components/covid19.tsx +++ b/examples/macros/components/covid19.tsx @@ -6,7 +6,7 @@ export const Covid19 = () => { { last: 100, columns: ["New_cases", "Date_reported", "Country"], - } + }, ); return ( diff --git a/examples/macros/components/example.jsx b/examples/macros/components/example.jsx index ad80ce9e1..84d2d92e9 100644 --- a/examples/macros/components/example.jsx +++ b/examples/macros/components/example.jsx @@ -10,7 +10,7 @@ export const IPAddresses = () => ( <div className="Line" key={index}> {ipAddress} </div> - ) + ), )} </div> </div> diff --git a/examples/macros/mystery-box.ts b/examples/macros/mystery-box.ts index 4dff5d003..6583c9868 100644 --- a/examples/macros/mystery-box.ts +++ b/examples/macros/mystery-box.ts @@ -1,13 +1,16 @@ export function mysteryBox(callExpression) { console.log(callExpression.log); // get arguments - const [ countNode ] = callExpression.arguments; + const [countNode] = callExpression.arguments; const countString: string = countNode.get(); const count: number = parseInt(countString, 10); // validate - if(!(count >= 1 && count <= 1000)) return new Error(`Argument ${countString} is expected to be between 1 and 1000`); + if (!(count >= 1 && count <= 1000)) + return new Error( + `Argument ${countString} is expected to be between 1 and 1000`, + ); // return a value - return (Math.random() * count)|0; + return (Math.random() * count) | 0; } diff --git a/examples/react-fast-refresh-test/bun.lockb b/examples/react-fast-refresh-test/bun.lockb Binary files differnew file mode 100755 index 000000000..a3cf88405 --- /dev/null +++ b/examples/react-fast-refresh-test/bun.lockb diff --git a/examples/react-fast-refresh-test/tsconfig.json b/examples/react-fast-refresh-test/tsconfig.json index 401ede344..d543b6472 100644 --- a/examples/react-fast-refresh-test/tsconfig.json +++ b/examples/react-fast-refresh-test/tsconfig.json @@ -1,7 +1,11 @@ { "compilerOptions": { "target": "esnext", - "lib": ["dom", "dom.iterable", "esnext"], + "lib": [ + "dom", + "dom.iterable", + "esnext" + ], "allowJs": true, "skipLibCheck": true, "strict": false, @@ -14,6 +18,12 @@ "isolatedModules": true, "jsx": "preserve" }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], - "exclude": ["node_modules"] -} + "include": [ + "next-env.d.ts", + "**/*.ts", + "**/*.tsx" + ], + "exclude": [ + "node_modules" + ] +}
\ No newline at end of file diff --git a/examples/spawn.ts b/examples/spawn.ts index a590a94f3..d72a118b9 100644 --- a/examples/spawn.ts +++ b/examples/spawn.ts @@ -8,7 +8,7 @@ const target = basename(repo) + "-main"; console.log("Downloading", repo, "to", "/tmp/" + target); const archive = await fetch( - `https://github.com/${repo}/archive/refs/heads/main.tar.gz` + `https://github.com/${repo}/archive/refs/heads/main.tar.gz`, ); // remove the directory if it already exists locally @@ -29,14 +29,11 @@ await tar.exited; if (!which("vercel")) { console.log("Installing vercel..."); - const installer = spawn( - { cmd: ["bun", "install", "-g", "vercel"] }, - { - stderr: "inherit", - stdout: "inherit", - stdin: "inherit", - } - ); + const installer = spawn(["bun", "install", "-g", "vercel"], { + stderr: "inherit", + stdout: "inherit", + stdin: "inherit", + }); await installer.exited; if (!which("vercel")) { diff --git a/examples/tsconfig.json b/examples/tsconfig.json deleted file mode 100644 index 404c353e6..000000000 --- a/examples/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "compilerOptions": { - "lib": ["ESNext"], - "module": "esnext", - "target": "esnext", - "typeRoots": ["../types"] - } -} diff --git a/misctools/gen-unicode-table.js b/misctools/gen-unicode-table.js index cd46ac31c..ad38a0ec5 100644 --- a/misctools/gen-unicode-table.js +++ b/misctools/gen-unicode-table.js @@ -19,7 +19,7 @@ const idStartES5 = [] require("@unicode/unicode-3.0.0/General_Category/Lowercase_Letter/code-points"), require("@unicode/unicode-3.0.0/General_Category/Titlecase_Letter/code-points"), require("@unicode/unicode-3.0.0/General_Category/Modifier_Letter/code-points"), - require("@unicode/unicode-3.0.0/General_Category/Other_Letter/code-points") + require("@unicode/unicode-3.0.0/General_Category/Other_Letter/code-points"), // The "letter number" category is not included because old versions of Safari // had a bug where they didn't include it. This means it does not match ES5. @@ -38,7 +38,7 @@ const idContinueES5 = idStartES5 require("@unicode/unicode-3.0.0/General_Category/Nonspacing_Mark/code-points"), require("@unicode/unicode-3.0.0/General_Category/Spacing_Mark/code-points"), require("@unicode/unicode-3.0.0/General_Category/Decimal_Number/code-points"), - require("@unicode/unicode-3.0.0/General_Category/Connector_Punctuation/code-points") + require("@unicode/unicode-3.0.0/General_Category/Connector_Punctuation/code-points"), ) .sort((a, b) => a - b); @@ -60,12 +60,12 @@ const idContinueESNextSet = new Set(idContinueESNext); // These identifiers are valid in both ES5 and ES6+ (i.e. an intersection of both) const idStartES5AndESNext = idStartES5.filter((n) => idStartESNextSet.has(n)); const idContinueES5AndESNext = idContinueES5.filter((n) => - idContinueESNextSet.has(n) + idContinueESNextSet.has(n), ); // These identifiers are valid in either ES5 or ES6+ (i.e. a union of both) const idStartES5OrESNext = [...new Set(idStartES5.concat(idStartESNext))].sort( - (a, b) => a - b + (a, b) => a - b, ); const idContinueES5OrESNext = [ ...new Set(idContinueES5.concat(idContinueESNext)), @@ -166,7 +166,7 @@ function generateBigSwitchStatement(codePoints) { fs.writeFileSync( path.join(__dirname, "..", "src", "js_lexer", "unicode.zig"), `// This file was automatically generated by ${path.basename( - __filename + __filename, )}. Do not edit. const RangeTable = @import("./range_table.zig"); @@ -190,5 +190,5 @@ pub fn isIdentifierContinue(comptime Codepoint: type, codepoint: Codepoint) bool } -` +`, ); diff --git a/misctools/headers-cleaner.js b/misctools/headers-cleaner.js index 10824d916..850cc3196 100644 --- a/misctools/headers-cleaner.js +++ b/misctools/headers-cleaner.js @@ -5,7 +5,7 @@ var { join } = require("path"); const destination = join(__dirname, "../src/bun.js/bindings/headers.zig"); const replacements = join( __dirname, - "../src/bun.js/bindings/headers-replacements.zig" + "../src/bun.js/bindings/headers-replacements.zig", ); console.log("Writing to", destination); @@ -24,7 +24,7 @@ const keep = ( (a) => /const (JSC|WTF|Web)_/gi.test(a) && !a.includes("JSValue") && - !a.includes("CatchScope") + !a.includes("CatchScope"), ) .join("\n") .trim(); @@ -36,7 +36,7 @@ input = input.replaceAll("[*c] JSC__", "[*c]bindings."); input = input.replaceAll("[*c] const JSC__", "[*c]const bindings."); input = input.replaceAll( "[*c]Inspector__ScriptArguments", - "[*c]bindings.ScriptArguments" + "[*c]bindings.ScriptArguments", ); input = input @@ -98,5 +98,5 @@ writeFileSync( readFileSync(replacements, "utf8").trim() + "\n" + input.trim() + - "\n" + "\n", ); diff --git a/misctools/mime.js b/misctools/mime.js index 74f9773e7..6f46a711f 100644 --- a/misctools/mime.js +++ b/misctools/mime.js @@ -10,7 +10,7 @@ json["application/javascript"].extensions.push( `cts`, `cjs`, `mjs`, - `js` + `js`, ); delete json["application/node"]; diff --git a/misctools/publish-examples.js b/misctools/publish-examples.js index d84466e15..4124d0785 100644 --- a/misctools/publish-examples.js +++ b/misctools/publish-examples.js @@ -16,7 +16,7 @@ var count = 0; const examplesFolderEntries = fs.readdirSync( path.join(process.cwd(), "examples"), - { withFileTypes: true } + { withFileTypes: true }, ); const packageNames = []; @@ -30,7 +30,7 @@ for (let folder of examplesFolderEntries) { try { packageJSONText = fs.readFileSync( path.join(absolute, "package.json"), - "utf8" + "utf8", ); } catch { continue; @@ -72,7 +72,7 @@ for (let folder of examplesFolderEntries) { try { fs.copyFileSync( path.join(absolute, ".gitignore"), - path.join(absolute, "gitignore") + path.join(absolute, "gitignore"), ); } catch (exception) {} @@ -87,7 +87,7 @@ for (let folder of examplesFolderEntries) { fs.writeFileSync( path.join(absolute, "package.json"), - JSON.stringify(packageJSON, null, 2) + JSON.stringify(packageJSON, null, 2), ); try { exec(`npm version patch --force --no-commit-hooks --no-git-tag-version`, { @@ -95,7 +95,7 @@ for (let folder of examplesFolderEntries) { }); packageJSON = JSON.parse( - fs.readFileSync(path.join(absolute, "package.json"), "utf8") + fs.readFileSync(path.join(absolute, "package.json"), "utf8"), ); version = packageJSON.version; } catch (e) { @@ -109,7 +109,7 @@ for (let folder of examplesFolderEntries) { `npm publish ${ DRY_RUN ? "--dry-run" : "" } --access public --registry https://registry.npmjs.org/`, - { cwd: absolute } + { cwd: absolute }, ); packageNames.push([ packageJSON.name, @@ -149,13 +149,13 @@ if (packageNames.length > 0) { } catch (exception) {} fs.writeFileSync( path.join(dir, "package.json"), - JSON.stringify(packageJSON, null, 2) + JSON.stringify(packageJSON, null, 2), ); exec( `npm publish ${ DRY_RUN ? "--dry-run" : "" } --access public --registry https://registry.npmjs.org/`, - { cwd: dir } + { cwd: dir }, ); } diff --git a/package.json b/package.json index 59a6b16cc..12d3e822f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,5 @@ { "dependencies": { - "bun-types": "latest", "express": "^4.18.2", "mitata": "^0.1.3", "peechy": "0.4.32", @@ -10,14 +9,23 @@ "private": true, "scripts": { "build-runtime": "esbuild --target=esnext --bundle src/runtime/index.ts --format=iife --platform=browser --global-name=BUN_RUNTIME > src/runtime.out.js; cat src/runtime.footer.js >> src/runtime.out.js", - "build-fallback": "esbuild --target=esnext --bundle src/fallback.ts --format=iife --platform=browser --minify > src/fallback.out.js" + "build-fallback": "esbuild --target=esnext --bundle src/fallback.ts --format=iife --platform=browser --minify > src/fallback.out.js", + "typecheck": "tsc", + "fmt": "prettier --write './**/*.{ts,tsx,js,jsx}'", + "lint": "eslint './**/*.d.ts'", + "lint:fix": "eslint './**/*.d.ts' --fix" }, "devDependencies": { + "@types/react": "^18.0.25", + "@typescript-eslint/eslint-plugin": "^5.31.0", + "@typescript-eslint/parser": "^5.31.0", + "eslint": "^8.20.0", + "eslint-config-prettier": "^8.5.0", "he": "^1.2.0", "html-entities": "^2.3.3", "prettier": "^2.4.1", - "svelte": "^3.50.0", - "typescript": "4.6.3" + "svelte": "^3.52.0", + "typescript": "latest" }, "version": "0.0.0" -}
\ No newline at end of file +} diff --git a/packages/bun-error/index.tsx b/packages/bun-error/index.tsx index cf0aaaf68..5c64fe807 100644 --- a/packages/bun-error/index.tsx +++ b/packages/bun-error/index.tsx @@ -16,11 +16,7 @@ import { problemsToMarkdown, withBunInfo, } from "./markdown"; -import { - fetchAllMappings, - remapPosition, - sourceMappings, -} from "./sourcemap"; +import { fetchAllMappings, remapPosition, sourceMappings } from "./sourcemap"; export enum StackFrameScope { Eval = 1, @@ -140,7 +136,7 @@ function hasColumnOrLine(filename: string) { function appendLineColumnIfNeeded( base: string, line?: number, - column?: number + column?: number, ) { if (hasColumnOrLine(base)) return base; @@ -162,7 +158,7 @@ function appendLineColumn(base: string, line?: number, column?: number) { const blobFileURL = ( filename: string, line?: number, - column?: number + column?: number, ): string => { var base = `/blob:${filename}`; @@ -174,7 +170,7 @@ const blobFileURL = ( const maybeBlobFileURL = ( filename: string, line?: number, - column?: number + column?: number, ): string => { if (filename.includes(".bun")) { return blobFileURL(filename, line, column); @@ -187,7 +183,9 @@ const maybeBlobFileURL = ( return srcFileURL(filename, line, column); }; -const openWithoutFlashOfNewTab: React.MouseEventHandler<HTMLAnchorElement> = (event) => { +const openWithoutFlashOfNewTab: React.MouseEventHandler<HTMLAnchorElement> = ( + event, +) => { const target = event.currentTarget; const href = target.getAttribute("href"); if (!href || event.button !== 0) { @@ -218,7 +216,7 @@ const openWithoutFlashOfNewTab: React.MouseEventHandler<HTMLAnchorElement> = (ev }) .then( () => {}, - (er) => {} + (er) => {}, ); return false; }; @@ -226,7 +224,7 @@ const openWithoutFlashOfNewTab: React.MouseEventHandler<HTMLAnchorElement> = (ev const srcFileURL = ( filename: string, line?: number, - column?: number + column?: number, ): string => { if (filename.startsWith("http://") || filename.startsWith("https://")) return appendLineColumnIfNeeded(filename); @@ -255,7 +253,7 @@ class FancyTypeError { constructor(exception: JSException) { this.runtimeType = exception.runtime_type || 0; this.runtimeTypeName = RuntimeType[this.runtimeType] || "undefined"; - this.message = exception.message || ''; + this.message = exception.message || ""; this.explain = ""; this.normalize(exception); @@ -276,7 +274,7 @@ class FancyTypeError { this.runtimeTypeName = nextWord[0]; this.runtimeTypeName = this.runtimeTypeName.substring( 0, - this.runtimeTypeName.length - 1 + this.runtimeTypeName.length - 1, ); switch (this.runtimeTypeName.toLowerCase()) { case "undefined": { @@ -316,7 +314,7 @@ class FancyTypeError { this.message = exception.message.substring(0, i); this.message = this.message.substring( 0, - this.message.lastIndexOf("(In ") + this.message.lastIndexOf("(In "), ); } } @@ -380,11 +378,11 @@ const AsyncSourceLines = ({ const lines = text.split("\n"); const startLineNumber = Math.max( Math.min(Math.max(highlight - 4, 0), lines.length - 1), - 0 + 0, ); const endLineNumber = Math.min(startLineNumber + 8, lines.length); const sourceLines: SourceLine[] = new Array( - endLineNumber - startLineNumber + endLineNumber - startLineNumber, ); var index = 0; for (let i = startLineNumber; i < endLineNumber; i++) { @@ -399,7 +397,7 @@ const AsyncSourceLines = ({ setSourceLines( index !== sourceLines.length ? sourceLines.slice(0, index) - : sourceLines + : sourceLines, ); setLoadState(LoadState.loaded); }) @@ -524,7 +522,7 @@ const SourceLines = ({ title={`Open line ${line} in editor`} href={buildURL( line, - classes.highlight ? highlightColumnStart : dedent + classes.highlight ? highlightColumnStart : dedent, )} onClickCapture={openWithoutFlashOfNewTab} key={"highlight-number-" + line} @@ -572,7 +570,7 @@ const BuildErrorSourceLines = ({ const sourceLines: SourceLine[] = [{ line, text: line_text }]; const buildURL = React.useCallback( (line, column) => srcFileURL(filename, line, column), - [srcFileURL, filename] + [srcFileURL, filename], ); return ( <SourceLines @@ -664,7 +662,7 @@ const NativeStackFrame = ({ }: { frame: StackFrame; maxLength: number; - urlBuilder: typeof maybeBlobFileURL + urlBuilder: typeof maybeBlobFileURL; }) => { const { cwd } = useContext(ErrorGroupContext); const { @@ -718,7 +716,7 @@ const NativeStackFrames = ({ frames, urlBuilder }) => { for (let i = 0; i < frames.length; i++) { maxLength = Math.max( getNativeStackFrameIdentifier(frames[i]).length, - maxLength + maxLength, ); } @@ -760,7 +758,7 @@ const NativeStackTrace = ({ const ref = React.useRef<HTMLDivElement>(null); const buildURL = React.useCallback( (line, column) => urlBuilder(file, line, column), - [file, urlBuilder] + [file, urlBuilder], ); return ( @@ -825,7 +823,7 @@ const JSException = ({ }) => { const tag = isClient ? ErrorTagType.client : ErrorTagType.server; const [sourceLines, _setSourceLines] = React.useState( - value?.stack?.source_lines ?? [] + value?.stack?.source_lines ?? [], ); var message = value.message || ""; var name = value.name || ""; @@ -1054,7 +1052,9 @@ const OverlayMessageContainer = ({ reason, isClient = false, }: FallbackMessageContainer & { isClient: boolean }) => { - const errorCount = problems ? problems.exceptions.length + problems.build.errors : 0; + const errorCount = problems + ? problems.exceptions.length + problems.build.errors + : 0; return ( <div id="BunErrorOverlay-container"> <div className="BunError-content"> @@ -1149,7 +1149,7 @@ function renderWithFunc(func) { reactRoot.id = BUN_ERROR_CONTAINER_ID; const fallbackStyleSheet = document.querySelector( - "style[data-has-bun-fallback-style]" + "style[data-has-bun-fallback-style]", ); if (!fallbackStyleSheet) { reactRoot.style.visibility = "hidden"; @@ -1309,9 +1309,9 @@ export function renderRuntimeError(error: Error) { // and don't fetch them again const framePromises = fetchAllMappings( exception.stack.frames.map((frame) => - normalizedFilename(frame.file, thisCwd) + normalizedFilename(frame.file, thisCwd), ), - signal + signal, ) .map((frame, i) => { if (stopThis.stopped) return null; @@ -1393,7 +1393,7 @@ export function dismissError() { export const renderBuildFailure = ( failure: WebsocketMessageBuildFailure, - cwd: string + cwd: string, ) => { thisCwd = cwd; renderWithFunc(() => ( diff --git a/packages/bun-error/markdown.ts b/packages/bun-error/markdown.ts index 8b27fc8cb..d6bbbf30c 100644 --- a/packages/bun-error/markdown.ts +++ b/packages/bun-error/markdown.ts @@ -123,7 +123,7 @@ function exceptionToMarkdown(exception: JSException): string { // but it may not be var prefix = "".padStart( lineText.length - lineText.trimStart().length, - " " + " ", ); prefix += @@ -159,7 +159,7 @@ function exceptionToMarkdown(exception: JSException): string { scope, functionName: function_name, markdown: true, - }).length + }).length, ); } @@ -268,7 +268,7 @@ export const withBunInfo = (text) => { const markdown = bunInfoToMarkdown(info).trim(); return trimmed + "\n" + markdown + "\n"; }, - () => trimmed + "\n" + () => trimmed + "\n", ); } diff --git a/packages/bun-error/runtime-error.ts b/packages/bun-error/runtime-error.ts index 713bfb7c0..5341e0bc8 100644 --- a/packages/bun-error/runtime-error.ts +++ b/packages/bun-error/runtime-error.ts @@ -107,7 +107,7 @@ export default class RuntimeError { var tokens = sanitizedLine.split(/\s+/).slice(1); // if a location was matched, pass it to extractLocation() otherwise pop the last token var locationParts = this.extractLocation( - location ? location[1] : tokens.pop() + location ? location[1] : tokens.pop(), ); var functionName = tokens.join(" ") || undefined; var fileName = @@ -135,7 +135,7 @@ export default class RuntimeError { if (line.indexOf(" > eval") > -1) { line = line.replace( / line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, - ":$1" + ":$1", ); } @@ -149,7 +149,7 @@ export default class RuntimeError { var matches = line.match(functionNameRegex); var functionName = matches && matches[1] ? matches[1] : undefined; var locationParts = this.extractLocation( - line.replace(functionNameRegex, "") + line.replace(functionNameRegex, ""), ); return new StackFrame({ diff --git a/packages/bun-error/sourcemap.ts b/packages/bun-error/sourcemap.ts index bee83f559..115ff69f1 100644 --- a/packages/bun-error/sourcemap.ts +++ b/packages/bun-error/sourcemap.ts @@ -214,7 +214,7 @@ export function decodeMappings(mappings, sourcesCount) { export function remapPosition( decodedMappings: Int32Array, line: number, - column: number + column: number, ) { if (!(decodedMappings instanceof Int32Array)) { throw new Error("decodedMappings must be an Int32Array"); diff --git a/packages/bun-error/tsconfig.json b/packages/bun-error/tsconfig.json index c125976f1..ddf84fcae 100644 --- a/packages/bun-error/tsconfig.json +++ b/packages/bun-error/tsconfig.json @@ -1,10 +1,13 @@ { "compilerOptions": { "jsx": "react", - "lib": ["ESNext", "DOM"], + "lib": [ + "ESNext", + "DOM" + ], "module": "esnext", "target": "esnext", "moduleResolution": "node", "allowSyntheticDefaultImports": true, } -} +}
\ No newline at end of file diff --git a/packages/bun-framework-next/bun.lockb b/packages/bun-framework-next/bun.lockb Binary files differnew file mode 100755 index 000000000..df7b3ae94 --- /dev/null +++ b/packages/bun-framework-next/bun.lockb diff --git a/packages/bun-framework-next/client.development.tsx b/packages/bun-framework-next/client.development.tsx index 4b51966c9..470dd2085 100644 --- a/packages/bun-framework-next/client.development.tsx +++ b/packages/bun-framework-next/client.development.tsx @@ -64,7 +64,7 @@ function nextDataFromBunData() { for (let i = 0; i < paramsList.keys.length; i++) { paramsMap.set( decodeURIComponent(paramsList.keys[i]), - decodeURIComponent(paramsList.values[i]) + decodeURIComponent(paramsList.values[i]), ); } @@ -134,31 +134,31 @@ setConfig({ }); let asPath: string = getURL(); -const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || '' +const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ""; function pathNoQueryHash(path: string) { - const queryIndex = path.indexOf('?') - const hashIndex = path.indexOf('#') + const queryIndex = path.indexOf("?"); + const hashIndex = path.indexOf("#"); if (queryIndex > -1 || hashIndex > -1) { - path = path.substring(0, queryIndex > -1 ? queryIndex : hashIndex) + path = path.substring(0, queryIndex > -1 ? queryIndex : hashIndex); } - return path + return path; } function hasBasePath(path: string): boolean { - path = pathNoQueryHash(path) - return path === prefix || path.startsWith(prefix + '/') + path = pathNoQueryHash(path); + return path === prefix || path.startsWith(prefix + "/"); } function delBasePath(path: string): string { - path = path.slice(basePath.length) - if (!path.startsWith('/')) path = `/${path}` - return path + path = path.slice(basePath.length); + if (!path.startsWith("/")) path = `/${path}`; + return path; } // make sure not to attempt stripping basePath for 404s -if (hasBasePath(asPath)) { +if (hasBasePath(asPath)) { asPath = delBasePath(asPath); } @@ -214,8 +214,8 @@ class Container extends React.Component<{ String( assign( urlQueryToSearchParams(router.query), - new URLSearchParams(location.search) - ) + new URLSearchParams(location.search), + ), ), asPath, { @@ -229,7 +229,7 @@ class Container extends React.Component<{ // Other pages (strictly updating query) happens shallowly, as data // requirements would already be present. shallow: !isFallback, - } + }, ); } } @@ -326,7 +326,7 @@ export async function _boot(EntryPointNamespace, isError) { console.assert( AppModule.default, - appSrc + " must have a default export'd React component" + appSrc + " must have a default export'd React component", ); if ("default" in AppModule) { @@ -355,7 +355,7 @@ export async function _boot(EntryPointNamespace, isError) { Component: info.Component || CachedComponent, App, scroll, - }) + }), ); }, locale, @@ -431,7 +431,7 @@ export function render(props) { } else { ReactDOM.render( <TopLevelRender {...props} />, - document.getElementById("__next") + document.getElementById("__next"), ); } } diff --git a/packages/bun-framework-next/fallback.development.tsx b/packages/bun-framework-next/fallback.development.tsx index 4db94e5d5..6e3ff00ff 100644 --- a/packages/bun-framework-next/fallback.development.tsx +++ b/packages/bun-framework-next/fallback.development.tsx @@ -12,7 +12,7 @@ function insertGlobalStyleSheet({ detail: url }) { link.onabort = reject; link.onerror = reject; document.head.appendChild(link); - }) + }), ); } @@ -27,7 +27,7 @@ function insertNextHeadCount() { if (!once) { document.head.insertAdjacentHTML( "beforeend", - `<meta name="next-head-count" content="0">` + `<meta name="next-head-count" content="0">`, ); once = true; } @@ -43,7 +43,7 @@ globalThis.__BUN_APP_STYLES = [...globalThis["__BUN"].allImportedStyles].map( } return style; - } + }, ); import { _boot, pageLoader } from "./client.development"; @@ -96,7 +96,7 @@ export default function render(props: FallbackMessageContainer) { Promise.all(pageLoader.cssQueue).finally(() => { renderFallbackError(props); }); - } + }, ); }); } diff --git a/packages/bun-framework-next/page-loader.ts b/packages/bun-framework-next/page-loader.ts index 08919cb39..c74b22fbf 100644 --- a/packages/bun-framework-next/page-loader.ts +++ b/packages/bun-framework-next/page-loader.ts @@ -76,8 +76,8 @@ export default class PageLoader extends NextPageLoader { this.cssQueue.push( insertStyleSheet(event.detail).then( () => {}, - () => {} - ) + () => {}, + ), ); }; diff --git a/packages/bun-framework-next/renderDocument.tsx b/packages/bun-framework-next/renderDocument.tsx index 3dac37562..5eae9ebf1 100644 --- a/packages/bun-framework-next/renderDocument.tsx +++ b/packages/bun-framework-next/renderDocument.tsx @@ -41,18 +41,18 @@ function appendNextBody(documentHTML: string, pageContent: string) { documentHTML.substring(0, bodyRenderIdx) + pageContent + documentHTML.substring( - bodyRenderIdx + NEXT_12_0_BODY_RENDER_TARGET.length + bodyRenderIdx + NEXT_12_0_BODY_RENDER_TARGET.length, ) ); } else { var [renderTargetPrefix, renderTargetSuffix] = documentHTML.split( - "<next-js-internal-body-render-target></next-js-internal-body-render-target>" + "<next-js-internal-body-render-target></next-js-internal-body-render-target>", ); if (!renderTargetPrefix || !renderTargetSuffix) { throw new Error( "Can't find where your <App /> starts or where the <Document /> ends. \nThis is probably a version incompatibility. Please mention this error in Bun's discord\n\n" + - documentHTML + documentHTML, ); } @@ -114,7 +114,7 @@ function getScripts(files: DocumentFiles) { type="module" /> ); - } + }, ); // if (entryPointIndex > 0) { // const entry = scripts.splice(entryPointIndex, 1); @@ -200,7 +200,7 @@ function renderDocument( scriptLoader: any; isPreview?: boolean; autoExport?: boolean; - } + }, ): string { const htmlProps = { __NEXT_DATA__: { @@ -259,7 +259,7 @@ function renderDocument( {/* @ts-expect-error */} <Document {...htmlProps} {...docProps}></Document> </HtmlContext.Provider> - </AmpStateContext.Provider> + </AmpStateContext.Provider>, ); } @@ -291,18 +291,18 @@ class ServerRouter implements NextRouter { defaultLocale?: string, domainLocales?: DomainLocale[], isPreview?: boolean, - isLocaleDomain?: boolean + isLocaleDomain?: boolean, ) { this.route = pathname.replace(/\/$/, "") || "/"; this.pathname = new URL( pathname || "/", - Bun.origin || "http://localhost:3000" + Bun.origin || "http://localhost:3000", ).href; this.query = query; this.asPath = new URL( as || "/", - Bun.origin || "http://localhost:3000" + Bun.origin || "http://localhost:3000", ).href; this.isFallback = isFallback; this.basePath = basePath; @@ -344,7 +344,7 @@ function noRouter() { function enhanceComponents( options: ComponentsEnhancer, App: AppType, - Component: NextComponentType + Component: NextComponentType, ): { App: AppType; Component: NextComponentType; @@ -374,13 +374,13 @@ Object.defineProperty(NextDocument.Head.prototype, "getScripts", scriptsGetter); Object.defineProperty( NextDocument.NextScript.prototype, "getScripts", - scriptsGetter + scriptsGetter, ); try { Object.defineProperty( NextDocument.default.prototype, "getScripts", - scriptsGetter + scriptsGetter, ); } catch {} try { @@ -475,19 +475,19 @@ export async function render({ throw new Error( `\"export default\" missing in ${ route.filePath - }.\nTry exporting one of ${reactComponents.join(", ")}\n` + }.\nTry exporting one of ${reactComponents.join(", ")}\n`, ); } else if (reactComponents.length === 2) { throw new Error( - `\"export default\" missing in ${route.filePath}.\n\nTry exporting <${reactComponents[0]} /> or <${reactComponents[1]} />\n` + `\"export default\" missing in ${route.filePath}.\n\nTry exporting <${reactComponents[0]} /> or <${reactComponents[1]} />\n`, ); } else if (reactComponents.length == 1) { throw new Error( - `\"export default\" missing in ${route.filePath}. Try adding this to the bottom of the file:\n\n export default ${reactComponents[0]};\n` + `\"export default\" missing in ${route.filePath}. Try adding this to the bottom of the file:\n\n export default ${reactComponents[0]};\n`, ); } else if (reactComponents.length == 0) { throw new Error( - `\"export default\" missing in ${route.filePath}. Try exporting a React component.\n` + `\"export default\" missing in ${route.filePath}. Try exporting a React component.\n`, ); } } @@ -572,7 +572,7 @@ export async function render({ null, //renderOpts.defaultLocale, [], // renderOpts.domainLocales, false, - false + false, ); const ctx = { @@ -593,7 +593,7 @@ export async function render({ ); }, defaultGetInitialProps: async ( - docCtx: NextDocument.DocumentContext + docCtx: NextDocument.DocumentContext, ): Promise<DocumentInitialProps> => { const enhanceApp = (AppComp: any) => { return (props: any) => <AppComp {...props} />; @@ -643,7 +643,7 @@ export async function render({ has(target, name) { return request.headers.has(name as string); }, - } + }, ), }, res: { @@ -715,7 +715,7 @@ export async function render({ props.pageProps = pageProps; const renderPage: RenderPage = ( - options: ComponentsEnhancer = {} + options: ComponentsEnhancer = {}, ): RenderPageResult | Promise<RenderPageResult> => { if (ctx.err && ErrorDebug) { const htmlOrPromise = renderToString(<ErrorDebug error={ctx.err} />); @@ -724,7 +724,7 @@ export async function render({ if (dev && (props.router || props.Component)) { throw new Error( - `'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props` + `'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props`, ); } @@ -741,7 +741,7 @@ export async function render({ {...props} pageProps={pageProps} /> - </AppContainer> + </AppContainer>, ); return { html: htmlOrPromise, head }; @@ -750,12 +750,12 @@ export async function render({ const documentCtx = { ...ctx, renderPage }; const docProps: DocumentInitialProps = await loadGetInitialProps( Document, - documentCtx + documentCtx, ); if (!docProps || typeof docProps.html !== "string") { const message = `"${getDisplayName( - Document + Document, )}.getInitialProps()" should resolve to an object with a "html" prop set with a valid html string`; throw new Error(message); } @@ -829,7 +829,7 @@ export async function render({ export function useMaybeDeferContent( _name: string, - contentFn: () => JSX.Element + contentFn: () => JSX.Element, ): [boolean, JSX.Element] { return [false, contentFn()]; } diff --git a/packages/bun-framework-next/server.development.tsx b/packages/bun-framework-next/server.development.tsx index d59e4cbfc..a19ffd149 100644 --- a/packages/bun-framework-next/server.development.tsx +++ b/packages/bun-framework-next/server.development.tsx @@ -7,7 +7,7 @@ if (!version.startsWith("12.2")) { console.warn( "Possibly incompatible Next.js version: ", version, - ". Please upgrade to Next.js 12.2.0+.\n" + ". Please upgrade to Next.js 12.2.0+.\n", ); } @@ -29,7 +29,7 @@ import(Bun.routesDir + "_document").then( } else { console.error(err); } - } + }, ); addEventListener("fetch", async (event: FetchEvent) => { diff --git a/packages/bun-framework-next/tsconfig.json b/packages/bun-framework-next/tsconfig.json index 09f55d73c..96e13d1eb 100644 --- a/packages/bun-framework-next/tsconfig.json +++ b/packages/bun-framework-next/tsconfig.json @@ -1,21 +1,28 @@ { + "extends": "../../tsconfig.base.json", "compilerOptions": { "target": "esnext", - "lib": ["dom", "dom.iterable", "esnext", "WebWorker"], - "allowJs": true, - "skipLibCheck": true, + "lib": [ + "dom", + "dom.iterable", + "esnext", + "WebWorker" + ], "strict": false, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "Node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", - "baseUrl": ".", - "paths": {} }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "empty.js"], - "exclude": ["node_modules"] -} + "include": [ + "next-env.d.ts", + "**/*.ts", + "**/*.tsx", + "empty.js" + ], + "exclude": [ + "node_modules" + ], +}
\ No newline at end of file diff --git a/packages/bun-landing/bun.lockb b/packages/bun-landing/bun.lockb Binary files differindex c6b3744c9..5bcc1309d 100755 --- a/packages/bun-landing/bun.lockb +++ b/packages/bun-landing/bun.lockb diff --git a/packages/bun-landing/components/CodeBlock.tsx b/packages/bun-landing/components/CodeBlock.tsx index 43618f2a0..7f16dc066 100644 --- a/packages/bun-landing/components/CodeBlock.tsx +++ b/packages/bun-landing/components/CodeBlock.tsx @@ -12,4 +12,4 @@ export default function CodeBlock({ children, lang = "js" }) { return ( <div className="CodeBlock" dangerouslySetInnerHTML={{ __html: html }} /> ); -};
\ No newline at end of file +} diff --git a/packages/bun-landing/components/dataURI.ts b/packages/bun-landing/components/dataURI.ts index 8bfc93714..559a9a89b 100644 --- a/packages/bun-landing/components/dataURI.ts +++ b/packages/bun-landing/components/dataURI.ts @@ -10,7 +10,7 @@ export function dataURI(expr) { const data = readFileSync(toLoad); return `data:${Bun.file(toLoad).type};base64, ${btoa( - String.fromCharCode(...new Uint8Array(data.buffer)) + String.fromCharCode(...new Uint8Array(data.buffer)), )}`; } catch (e) { console.error(e); diff --git a/packages/bun-landing/next.config.js b/packages/bun-landing/next.config.js index 5a8ff89b2..7cd57f439 100644 --- a/packages/bun-landing/next.config.js +++ b/packages/bun-landing/next.config.js @@ -5,7 +5,7 @@ module.exports = { }, webpack: (config) => { // support shiki top level await - config.experiments = { ...config.experiments, ...{ topLevelAwait: true }}; + config.experiments = { ...config.experiments, ...{ topLevelAwait: true } }; return config; }, }; diff --git a/packages/bun-landing/pages/_app.tsx b/packages/bun-landing/pages/_app.tsx index 416778949..2896467a5 100644 --- a/packages/bun-landing/pages/_app.tsx +++ b/packages/bun-landing/pages/_app.tsx @@ -2,5 +2,9 @@ import Layout from "../components/Layout"; import "../styles/global.css"; export default function MyApp({ Component, pageProps }) { - return <Layout><Component {...pageProps} /></Layout>; -}
\ No newline at end of file + return ( + <Layout> + <Component {...pageProps} /> + </Layout> + ); +} diff --git a/packages/bun-landing/pages/index.tsx b/packages/bun-landing/pages/index.tsx index 6e1434c31..096b32cb8 100644 --- a/packages/bun-landing/pages/index.tsx +++ b/packages/bun-landing/pages/index.tsx @@ -52,7 +52,7 @@ const BarGraphItem = ({ type, amount = 0, label, max = 0 }) => ( style={{ "--amount": amount, "--max": max }} > <div className="visually-hidden">{`${type}: ${fmt.format( - amount + amount, )} ${label}`}</div> <div style={{ "--amount": amount, "--max": max }} @@ -171,7 +171,9 @@ const InstallBox = ({ desktop = false }) => ( </div> </div> <div className="InstallBox-code-box"> - <div className="InstallBox-curl">curl -fsSL https://bun.sh/install | bash</div> + <div className="InstallBox-curl"> + curl -fsSL https://bun.sh/install | bash + </div> <button className="InstallBox-copy" aria-label="Copy installation script"> copy </button> @@ -369,7 +371,7 @@ export default function LandingPage() { amount={(1000 / 14.22).toFixed(2)} label="queries per second" max={Math.ceil( - Math.max(1000 / 14.22, 1000 / 42.96, 1000 / 27.37) * 1.25 + Math.max(1000 / 14.22, 1000 / 42.96, 1000 / 27.37) * 1.25, )} /> <BarGraphItem @@ -377,7 +379,7 @@ export default function LandingPage() { amount={(1000 / 27.37).toFixed(2)} label="queries per second" max={Math.ceil( - Math.max(1000 / 14.22, 1000 / 42.96, 1000 / 27.37) * 1.25 + Math.max(1000 / 14.22, 1000 / 42.96, 1000 / 27.37) * 1.25, )} /> <BarGraphItem @@ -385,7 +387,7 @@ export default function LandingPage() { amount={(1000 / 42.96).toFixed(2)} label="queries per second" max={Math.ceil( - Math.max(1000 / 14.22, 1000 / 42.96, 1000 / 27.37) * 1.25 + Math.max(1000 / 14.22, 1000 / 42.96, 1000 / 27.37) * 1.25, )} /> </ul> diff --git a/packages/bun-landing/tsconfig.json b/packages/bun-landing/tsconfig.json index 54b36a1e7..c1e94dd70 100644 --- a/packages/bun-landing/tsconfig.json +++ b/packages/bun-landing/tsconfig.json @@ -1,7 +1,11 @@ { "compilerOptions": { "target": "es5", - "lib": ["dom", "dom.iterable", "esnext"], + "lib": [ + "dom", + "dom.iterable", + "esnext" + ], "allowJs": true, "skipLibCheck": true, "strict": true, @@ -15,6 +19,12 @@ "jsx": "preserve", "incremental": true }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], - "exclude": ["node_modules"] + "include": [ + "next-env.d.ts", + "**/*.ts", + "**/*.tsx" + ], + "exclude": [ + "node_modules" + ] }
\ No newline at end of file diff --git a/packages/bun-macro-relay/bun-macro-relay.tsx b/packages/bun-macro-relay/bun-macro-relay.tsx index b2ae22225..f7899698d 100644 --- a/packages/bun-macro-relay/bun-macro-relay.tsx +++ b/packages/bun-macro-relay/bun-macro-relay.tsx @@ -50,7 +50,7 @@ export function graphql(node) { definition.kind !== "OperationDefinition" ) { throw new Error( - `BunMacroRelay: Expected a fragment, mutation, query, or subscription, got "${definition.kind}"` + `BunMacroRelay: Expected a fragment, mutation, query, or subscription, got "${definition.kind}"`, ); } diff --git a/packages/bun-macro-relay/bun.lockb b/packages/bun-macro-relay/bun.lockb Binary files differnew file mode 100755 index 000000000..2f64dc319 --- /dev/null +++ b/packages/bun-macro-relay/bun.lockb diff --git a/packages/bun-types/.eslintignore b/packages/bun-types/.eslintignore new file mode 100644 index 000000000..9bb944385 --- /dev/null +++ b/packages/bun-types/.eslintignore @@ -0,0 +1,5 @@ +*.cjs +dist/** +tests/** +scripts/** +docs/**
\ No newline at end of file diff --git a/packages/bun-types/.eslintrc.cjs b/packages/bun-types/.eslintrc.cjs new file mode 100644 index 000000000..d38b920f4 --- /dev/null +++ b/packages/bun-types/.eslintrc.cjs @@ -0,0 +1,23 @@ +module.exports = { + root: true, + parser: "@typescript-eslint/parser", + parserOptions: { + tsconfigRootDir: __dirname, + project: ["./tsconfig.json"], + }, + plugins: ["@typescript-eslint"], + extends: [ + "eslint:recommended", + "plugin:@typescript-eslint/recommended", + "plugin:@typescript-eslint/recommended-requiring-type-checking", + "prettier", + ], + rules: { + "no-var": "off", // global variables + "@typescript-eslint/ban-types": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/no-non-null-assertion": "off", + }, +}; diff --git a/packages/bun-types/.gitignore b/packages/bun-types/.gitignore new file mode 100644 index 000000000..04c01ba7b --- /dev/null +++ b/packages/bun-types/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +dist/
\ No newline at end of file diff --git a/packages/bun-types/.prettierignore b/packages/bun-types/.prettierignore new file mode 100644 index 000000000..849ddff3b --- /dev/null +++ b/packages/bun-types/.prettierignore @@ -0,0 +1 @@ +dist/ diff --git a/packages/bun-types/README.md b/packages/bun-types/README.md new file mode 100644 index 000000000..7985ccd98 --- /dev/null +++ b/packages/bun-types/README.md @@ -0,0 +1,55 @@ +# Bun TypeScript type definitions + +<p align="center"> + <a href="https://bun.sh"><img src="https://bun.sh/logo@2x.png" alt="Logo"></a> +</p> + +These are the type definitions for Bun's JavaScript runtime APIs. + +# Installation + +Install the `bun-types` npm package: + +```bash +# yarn/npm/pnpm work too, "bun-types" is an ordinary npm package +bun add bun-types +``` + +# Usage + +Add this to your `tsconfig.json` or `jsconfig.json`: + +```jsonc +{ + "compilerOptions": { + "lib": ["esnext"], + "module": "esnext", + "target": "esnext", + "moduleResolution": "node", + // "bun-types" is the important part + "types": ["bun-types"] + } +} +``` + +# Contributing + +`bun-types` is generated via [./bundle.ts](./scripts/bundle.ts). + +## Adding a new file + +1. Add it to [./index.d.ts](./index.d.ts) + +## How to generate types.d.ts + +[`./bundle.ts`](./bundle.ts) merges the types in this folder into a single file. + +To run it: + +```bash +bun build +``` + +# Generated docs + +**[📚 See here for docs](https://oven-sh.github.io/bun-types/)** diff --git a/packages/bun-types/assert.d.ts b/packages/bun-types/assert.d.ts new file mode 100644 index 000000000..ae3b54ff2 --- /dev/null +++ b/packages/bun-types/assert.d.ts @@ -0,0 +1,968 @@ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/assert.js) + */ +declare module "assert" { + /** + * An alias of {@link ok}. + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `assert` module + * will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + code: "ERR_ASSERTION"; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // tslint:disable-next-line:ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is currently experimental and behavior might still change. + * @experimental + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @param [fn='A no-op function'] + * @param [exact=1] + * @return that wraps `fn`. + */ + calls(exact?: number): () => void; + calls<Func extends (...args: any[]) => any>( + fn?: Func, + exact?: number, + ): Func; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * tracker.report(); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @return of objects containing information about the wrapper functions returned by `calls`. + */ + report(): CallTrackerReportInformation[]; + /** + * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + */ + verify(): void; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = + | RegExp + | (new () => object) + | ((thrown: unknown) => boolean) + | object + | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // tslint:disable-next-line:ban-types + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + */ + function equal( + actual: unknown, + expected: unknown, + message?: string | Error, + ): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error + * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + */ + function notEqual( + actual: unknown, + expected: unknown, + message?: string | Error, + ): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + */ + function deepEqual( + actual: unknown, + expected: unknown, + message?: string | Error, + ): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(obj1); + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default + * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + */ + function notDeepEqual( + actual: unknown, + expected: unknown, + message?: string | Error, + ): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + */ + function strictEqual<T>( + actual: unknown, + expected: T, + message?: string | Error, + ): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + */ + function notStrictEqual( + actual: unknown, + expected: unknown, + message?: string | Error, + ): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + */ + function deepStrictEqual<T>( + actual: unknown, + expected: T, + message?: string | Error, + ): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + */ + function notDeepStrictEqual( + actual: unknown, + expected: unknown, + message?: string | Error, + ): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text' + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text' + * } + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * } + * ); + * + * // Using regular expressions to validate error properties: + * throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text' + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i + * } + * ); + * + * // Fails due to the different `message` and `name` properties: + * throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/ + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error' + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws( + block: () => unknown, + error: AssertPredicate, + message?: string | Error, + ): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. + * + * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops' + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow( + block: () => unknown, + error: AssertPredicate, + message?: string | Error, + ): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error + * handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and`name` properties. + * + * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second + * argument gets considered. + */ + function rejects( + block: (() => Promise<unknown>) | Promise<unknown>, + message?: string | Error, + ): Promise<void>; + function rejects( + block: (() => Promise<unknown>) | Promise<unknown>, + error: AssertPredicate, + message?: string | Error, + ): Promise<void>; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + */ + function doesNotReject( + block: (() => Promise<unknown>) | Promise<unknown>, + message?: string | Error, + ): Promise<void>; + function doesNotReject( + block: (() => Promise<unknown>) | Promise<unknown>, + error: AssertPredicate, + message?: string | Error, + ): Promise<void>; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + */ + function match( + value: string, + regExp: RegExp, + message?: string | Error, + ): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + */ + // FIXME: assert.doesNotMatch is typed, but not in the browserify polyfill? + // function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + + const strict: Omit< + typeof assert, + | "equal" + | "notEqual" + | "deepEqual" + | "notDeepEqual" + | "ok" + | "strictEqual" + | "deepStrictEqual" + | "ifError" + | "strict" + > & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/packages/bun-types/buffer.d.ts b/packages/bun-types/buffer.d.ts new file mode 100644 index 000000000..a7de0cfe4 --- /dev/null +++ b/packages/bun-types/buffer.d.ts @@ -0,0 +1,2089 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/buffer.js) + */ +declare module "buffer" { + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf16le" + | "ucs2" + | "latin1" + | "binary"; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new (size: number): Buffer; + prototype: Buffer; + }; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + global { + // Buffer class + type WithImplicitCoercion<T> = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new (str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new (arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: ReadonlyArray<any>): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new (buffer: Buffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * 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. + */ + from( + arrayBuffer: WithImplicitCoercion<ArrayBuffer | SharedArrayBuffer>, + 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<number>): Buffer; + from( + data: WithImplicitCoercion<Uint8Array | ReadonlyArray<number> | string>, + ): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion<string> + | { + [Symbol.toPrimitive](hint: "string"): string; + }, + encoding?: BufferEncoding, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: <Buffer 00 00 00 00 ...> + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @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<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)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: <Buffer 00 00 00 00 00> + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: <Buffer 61 61 61 61 61> + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc( + size: number, + fill?: string | Buffer | 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. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32> + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00> + * ``` + * + * 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). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. A zero-length `Buffer` is created + * if `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and_may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write( + string: string, + offset: number, + length: number, + encoding?: BufferEncoding, + ): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: <Buffer 01 02 03 04 05> + * ``` + * + * Note: as of Bun v0.1.2, this is not implemented yet. + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy( + target: Uint8Array, + targetStart?: number, + sourceStart?: number, + sourceEnd?: number, + ): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: <Buffer 01 02 03 04 05 06 07 08> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: <Buffer 08 07 06 05 04 03 02 01> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: <Buffer de ca fa fe ca ce fa de> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: <Buffer de fa ce ca fe fa ca de> + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: <Buffer ab 90 78 56 34 12> + * ``` + * + * Note: as of Bun v0.1.2, this is not implemented yet. + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: <Buffer 12 34 56 78 90 ab> + * ``` + * + * Note: as of Bun v0.1.2, this is not implemented yet. + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: <Buffer ab 90 78 56 34 12> + * ``` + * + * Note: as of Bun v0.1.2, this is not implemented yet. + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: <Buffer 12 34 56 78 90 ab> + * ``` + * + * Note: as of Bun v0.1.2, this is not implemented yet. + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * + * Note: as of Bun v0.1.2, this is not implemented yet. + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * + * Note: as of Bun v0.1.2, this is not implemented yet. + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * + * Note: as of Bun v0.1.2, this is not implemented yet. + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * + * Note: as of Bun v0.1.2, this is not implemented yet. + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: <Buffer 01 02 03 04 05 06 07 08> + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: <Buffer 02 01 04 03 06 05 08 07> + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: <Buffer 01 02 03 04 05 06 07 08> + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: <Buffer 04 03 02 01 08 07 06 05> + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: <Buffer 01 02 03 04 05 06 07 08> + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: <Buffer 08 07 06 05 04 03 02 01> + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: <Buffer 03 04 23 42> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: <Buffer ad de ef be> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: <Buffer de ad be ef> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: <Buffer ce fa ed fe> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: <Buffer fe ed fa ce> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: <Buffer 02 fe> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: <Buffer 04 03> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: <Buffer 01 02> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: <Buffer 08 07 06 05> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: <Buffer 01 02 03 04> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: <Buffer bb fe 4a 4f> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: <Buffer 4f 4a fe bb> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: <Buffer 77 be 9f 1a 2f dd 5e 40> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: <Buffer 40 5e dd 2f 1a 9f be 77> + * ``` + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: <Buffer c8 a2 c8 a2 c8> + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: <Buffer 61 61 61 61 61> + * console.log(buf.fill('aazz', 'hex')); + * // Prints: <Buffer aa aa aa aa aa> + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @param value The value with which to fill `buf`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill( + value: string | Uint8Array | number, + offset?: number, + end?: number, + encoding?: BufferEncoding, + ): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf( + value: string | number | Uint8Array, + byteOffset?: number, + encoding?: BufferEncoding, + ): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf( + value: string | number | Uint8Array, + byteOffset?: number, + encoding?: BufferEncoding, + ): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from '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] + * ``` + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes( + value: string | number | Buffer, + byteOffset?: number, + encoding?: BufferEncoding, + ): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + */ + keys(): IterableIterator<number>; + /** + * 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 + * ``` + */ + values(): IterableIterator<number>; + } + var Buffer: BufferConstructor; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/packages/bun-types/bun-test.d.ts b/packages/bun-types/bun-test.d.ts new file mode 100644 index 000000000..1ec84492a --- /dev/null +++ b/packages/bun-types/bun-test.d.ts @@ -0,0 +1,44 @@ +/** + * + * This isn't really designed for third-party usage yet. + * You can try it if you want though! + * + * To run the tests, run `bun wiptest` + * + * @example + * + * ```bash + * $ bun wiptest + * ``` + * + * @example + * ```bash + * $ bun wiptest file-name + * ``` + */ + +declare module "bun:test" { + export function describe(label: string, body: () => void): any; + export function it(label: string, test: () => void | Promise<any>): any; + export function test( + label: string, + test: (done: () => void) => void | Promise<any>, + ): any; + + export function expect(value: any): Expect; + export function afterAll(fn: () => void): void; + export function beforeAll(fn: () => void): void; + + export function afterEach(fn: () => void): void; + export function beforeEach(fn: () => void): void; + + interface Expect { + toBe(value: any): void; + toContain(value: any): void; + } +} + +declare module "test" { + import BunTestModule = require("bun:test"); + export = BunTestModule; +} diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts new file mode 100644 index 000000000..8611ccb30 --- /dev/null +++ b/packages/bun-types/bun.d.ts @@ -0,0 +1,2768 @@ +interface VoidFunction { + (): void; +} + +/** + * + * Bun.js runtime APIs + * + * @example + * + * ```js + * import {file} from 'bun'; + * + * // Log the file to the console + * const input = await file('/path/to/file.txt').text(); + * console.log(input); + * ``` + * + * This module aliases `globalThis.Bun`. + * + */ +declare module "bun" { + /** + * The environment variables of the process + * + * Defaults to `process.env` as it was when the current Bun process launched. + * + * Changes to `process.env` at runtime won't automatically be reflected in the default value. For that, you can pass `process.env` explicitly. + * + */ + export const env: Record<string, string>; + export const origin: string; + + /** + * Find the path to an executable, similar to typing which in your terminal. Reads the `PATH` environment variable unless overridden with `options.PATH`. + * + * @param {string} command The name of the executable or script + * @param {string} options.PATH Overrides the PATH environment variable + * @param {string} options.cwd Limits the search to a particular directory in which to searc + * + */ + export function which( + command: string, + options?: { PATH?: string; cwd?: string }, + ): string; + + /** + * Start a fast HTTP server. + * + * @param options Server options (port defaults to $PORT || 8080) + * + * ----- + * + * @example + * + * ```ts + * Bun.serve({ + * fetch(req: Request): Response | Promise<Response> { + * return new Response("Hello World!"); + * }, + * + * // Optional port number - the default value is 3000 + * port: process.env.PORT || 3000, + * }); + * ``` + * ----- + * + * @example + * + * Send a file + * + * ```ts + * Bun.serve({ + * fetch(req: Request): Response | Promise<Response> { + * return new Response(Bun.file("./package.json")); + * }, + * + * // Optional port number - the default value is 3000 + * port: process.env.PORT || 3000, + * }); + * ``` + */ + export function serve<ServeOoptions extends Serve<any>>( + options: ServeOoptions, + ): Server; + + /** + * Synchronously resolve a `moduleId` as though it were imported from `parent` + * + * On failure, throws a `ResolveError` + */ + // tslint:disable-next-line:unified-signatures + export function resolveSync(moduleId: string, parent: string): string; + + /** + * Resolve a `moduleId` as though it were imported from `parent` + * + * On failure, throws a `ResolveError` + * + * For now, use the sync version. There is zero performance benefit to using this async version. It exists for future-proofing. + */ + // tslint:disable-next-line:unified-signatures + export function resolve(moduleId: string, parent: string): Promise<string>; + + /** + * + * Use the fastest syscalls available to copy from `input` into `destination`. + * + * If `destination` exists, it must be a regular file or symlink to a file. + * + * @param destination The file or file path to write to + * @param input The data to copy into `destination`. + * @returns A promise that resolves with the number of bytes written. + */ + // tslint:disable-next-line:unified-signatures + export function write( + destination: FileBlob | PathLike, + input: Blob | TypedArray | ArrayBufferLike | string | BlobPart[], + ): Promise<number>; + + /** + * + * Persist a {@link Response} body to disk. + * + * @param destination The file to write to. If the file doesn't exist, + * it will be created and if the file does exist, it will be + * overwritten. If `input`'s size is less than `destination`'s size, + * `destination` will be truncated. + * @param input - `Response` object + * @returns A promise that resolves with the number of bytes written. + */ + export function write( + destination: FileBlob, + input: Response, + ): Promise<number>; + + /** + * + * Persist a {@link Response} body to disk. + * + * @param destinationPath The file path to write to. If the file doesn't + * exist, it will be created and if the file does exist, it will be + * overwritten. If `input`'s size is less than `destination`'s size, + * `destination` will be truncated. + * @param input - `Response` object + * @returns A promise that resolves with the number of bytes written. + */ + // tslint:disable-next-line:unified-signatures + export function write( + destinationPath: PathLike, + input: Response, + ): Promise<number>; + + /** + * + * Use the fastest syscalls available to copy from `input` into `destination`. + * + * If `destination` exists, it must be a regular file or symlink to a file. + * + * On Linux, this uses `copy_file_range`. + * + * On macOS, when the destination doesn't already exist, this uses + * [`clonefile()`](https://www.manpagez.com/man/2/clonefile/) and falls + * back to [`fcopyfile()`](https://www.manpagez.com/man/2/fcopyfile/) + * + * @param destination The file to write to. If the file doesn't exist, + * it will be created and if the file does exist, it will be + * overwritten. If `input`'s size is less than `destination`'s size, + * `destination` will be truncated. + * @param input The file to copy from. + * @returns A promise that resolves with the number of bytes written. + */ + // tslint:disable-next-line:unified-signatures + export function write( + destination: FileBlob, + input: FileBlob, + ): Promise<number>; + + /** + * + * Use the fastest syscalls available to copy from `input` into `destination`. + * + * If `destination` exists, it must be a regular file or symlink to a file. + * + * On Linux, this uses `copy_file_range`. + * + * On macOS, when the destination doesn't already exist, this uses + * [`clonefile()`](https://www.manpagez.com/man/2/clonefile/) and falls + * back to [`fcopyfile()`](https://www.manpagez.com/man/2/fcopyfile/) + * + * @param destinationPath The file path to write to. If the file doesn't + * exist, it will be created and if the file does exist, it will be + * overwritten. If `input`'s size is less than `destination`'s size, + * `destination` will be truncated. + * @param input The file to copy from. + * @returns A promise that resolves with the number of bytes written. + */ + // tslint:disable-next-line:unified-signatures + export function write( + destinationPath: PathLike, + input: FileBlob, + ): Promise<number>; + + export interface SystemError extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + /** + * Concatenate an array of typed arrays into a single `ArrayBuffer`. This is a fast path. + * + * You can do this manually if you'd like, but this function will generally + * be a little faster. + * + * If you want a `Uint8Array` instead, consider `Buffer.concat`. + * + * @param buffers An array of typed arrays to concatenate. + * @returns An `ArrayBuffer` with the data from all the buffers. + * + * Here is similar code to do it manually, except about 30% slower: + * ```js + * var chunks = [...]; + * var size = 0; + * for (const chunk of chunks) { + * size += chunk.byteLength; + * } + * var buffer = new ArrayBuffer(size); + * var view = new Uint8Array(buffer); + * var offset = 0; + * for (const chunk of chunks) { + * view.set(chunk, offset); + * offset += chunk.byteLength; + * } + * return buffer; + * ``` + * + * This function is faster because it uses uninitialized memory when copying. Since the entire + * length of the buffer is known, it is safe to use uninitialized memory. + */ + export function concatArrayBuffers( + buffers: Array<ArrayBufferView | ArrayBufferLike>, + ): ArrayBuffer; + + /** + * Consume all data from a {@link ReadableStream} until it closes or errors. + * + * Concatenate the chunks into a single {@link ArrayBuffer}. + * + * Each chunk must be a TypedArray or an ArrayBuffer. If you need to support + * chunks of different types, consider {@link readableStreamToBlob} + * + * @param stream The stream to consume. + * @returns A promise that resolves with the concatenated chunks or the concatenated chunks as an `ArrayBuffer`. + */ + export function readableStreamToArrayBuffer( + stream: ReadableStream, + ): Promise<ArrayBuffer> | ArrayBuffer; + + /** + * Consume all data from a {@link ReadableStream} until it closes or errors. + * + * Concatenate the chunks into a single {@link Blob}. + * + * @param stream The stream to consume. + * @returns A promise that resolves with the concatenated chunks as a {@link Blob}. + */ + export function readableStreamToBlob(stream: ReadableStream): Promise<Blob>; + + /** + * Consume all data from a {@link ReadableStream} until it closes or errors. + * + * Concatenate the chunks into a single string. Chunks must be a TypedArray or an ArrayBuffer. If you need to support chunks of different types, consider {@link readableStreamToBlob}. + * + * @param stream The stream to consume. + * @returns A promise that resolves with the concatenated chunks as a {@link String}. + */ + export function readableStreamToText(stream: ReadableStream): Promise<string>; + + /** + * Consume all data from a {@link ReadableStream} until it closes or errors. + * + * Concatenate the chunks into a single string and parse as JSON. Chunks must be a TypedArray or an ArrayBuffer. If you need to support chunks of different types, consider {@link readableStreamToBlob}. + * + * @param stream The stream to consume. + * @returns A promise that resolves with the concatenated chunks as a {@link String}. + */ + export function readableStreamToJSON(stream: ReadableStream): Promise<any>; + + /** + * Consume all data from a {@link ReadableStream} until it closes or errors. + * + * @param stream The stream to consume + * @returns A promise that resolves with the chunks as an array + * + */ + export function readableStreamToArray<T>( + stream: ReadableStream, + ): Promise<T[]> | T[]; + + /** + * Escape the following characters in a string: + * + * - `"` becomes `"""` + * - `&` becomes `"&"` + * - `'` becomes `"'"` + * - `<` becomes `"<"` + * - `>` becomes `">"` + * + * This function is optimized for large input. On an M1X, it processes 480 MB/s - + * 20 GB/s, depending on how much data is being escaped and whether there is non-ascii + * text. + * + * Non-string types will be converted to a string before escaping. + */ + export function escapeHTML(input: string | object | number | boolean): string; + + /** + * Convert a filesystem path to a file:// URL. + * + * @param path The path to convert. + * @returns A {@link URL} with the file:// scheme. + * + * @example + * ```js + * const url = Bun.pathToFileURL("/foo/bar.txt"); + * console.log(url.href); // "file:///foo/bar.txt" + *``` + * + * Internally, this function uses WebKit's URL API to + * convert the path to a file:// URL. + */ + export function pathToFileURL(path: string): URL; + + export interface Peek { + <T = undefined>(promise: T | Promise<T>): Promise<T> | T; + status<T = undefined>( + promise: T | Promise<T>, + ): "pending" | "fulfilled" | "rejected"; + } + /** + * Extract the value from the Promise in the same tick of the event loop + */ + export const peek: Peek; + + /** + * Convert a {@link URL} to a filesystem path. + * @param url The URL to convert. + * @returns A filesystem path. + * @throws If the URL is not a URL. + * @example + * ```js + * const path = Bun.fileURLToPath(new URL("file:///foo/bar.txt")); + * console.log(path); // "/foo/bar.txt" + * ``` + */ + export function fileURLToPath(url: URL): string; + + /** + * Fast incremental writer that becomes an `ArrayBuffer` on end(). + */ + export class ArrayBufferSink { + constructor(); + + start(options?: { + asUint8Array?: boolean; + /** + * Preallocate an internal buffer of this size + * This can significantly improve performance when the chunk size is small + */ + highWaterMark?: number; + /** + * On {@link ArrayBufferSink.flush}, return the written data as a `Uint8Array`. + * Writes will restart from the beginning of the buffer. + */ + stream?: boolean; + }): void; + + write(chunk: string | ArrayBufferView | ArrayBuffer): number; + /** + * Flush the internal buffer + * + * If {@link ArrayBufferSink.start} was passed a `stream` option, this will return a `ArrayBuffer` + * If {@link ArrayBufferSink.start} was passed a `stream` option and `asUint8Array`, this will return a `Uint8Array` + * Otherwise, this will return the number of bytes written since the last flush + * + * This API might change later to separate Uint8ArraySink and ArrayBufferSink + */ + flush(): number | Uint8Array | ArrayBuffer; + end(): ArrayBuffer | Uint8Array; + } + + /** + * Fast incremental writer for files and pipes. + * + * This uses the same interface as {@link ArrayBufferSink}, but writes to a file or pipe. + */ + export interface FileSink { + /** + * Write a chunk of data to the file. + * + * If the file descriptor is not writable yet, the data is buffered. + */ + write(chunk: string | ArrayBufferView | ArrayBuffer): number; + /** + * Flush the internal buffer, committing the data to disk or the pipe. + */ + flush(): number | Promise<number>; + /** + * Close the file descriptor. This also flushes the internal buffer. + */ + end(error?: Error): number | Promise<number>; + } + + /** + * [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) powered by the fastest system calls available for operating on files. + * + * This Blob is lazy. That means it won't do any work until you read from it. + * + * - `size` will not be valid until the contents of the file are read at least once. + * - `type` is auto-set based on the file extension when possible + * + * @example + * ```js + * const file = Bun.file("./hello.json"); + * console.log(file.type); // "application/json" + * console.log(await file.text()); // '{"hello":"world"}' + * ``` + * + * @example + * ```js + * await Bun.write( + * Bun.file("./hello.txt"), + * "Hello, world!" + * ); + * ``` + * + */ + export interface FileBlob extends Blob { + /** + * Offset any operation on the file starting at `begin` and ending at `end`. `end` is relative to 0 + * + * Similar to [`TypedArray.subarray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). Does not copy the file, open the file, or modify the file. + * + * If `begin` > 0, {@link Bun.write()} will be slower on macOS + * + * @param begin - start offset in bytes + * @param end - absolute offset in bytes (relative to 0) + */ + slice(begin?: number, end?: number): FileBlob; + + /** + * Incremental writer for files and pipes. + */ + writer(options?: { highWaterMark?: number }): FileSink; + + readonly readable: ReadableStream; + + // TODO: writable: WritableStream; + } + + /** + * This lets you use macros as regular imports + * @example + * ``` + * { + * "react-relay": { + * "graphql": "bun-macro-relay/bun-macro-relay.tsx" + * } + * } + * ``` + */ + export type MacroMap = Record<string, Record<string, string>>; + + /** + * Hash a string or array buffer using Wyhash + * + * This is not a cryptographic hash function. + * @param data The data to hash. + * @param seed The seed to use. + */ + export const hash: (( + data: string | ArrayBufferView | ArrayBuffer, + seed?: number, + ) => number | bigint) & + Hash; + + interface Hash { + wyhash: ( + data: string | ArrayBufferView | ArrayBuffer, + seed?: number, + ) => number | bigint; + crc32: ( + data: string | ArrayBufferView | ArrayBuffer, + seed?: number, + ) => number | bigint; + adler32: ( + data: string | ArrayBufferView | ArrayBuffer, + seed?: number, + ) => number | bigint; + cityHash32: ( + data: string | ArrayBufferView | ArrayBuffer, + seed?: number, + ) => number | bigint; + cityHash64: ( + data: string | ArrayBufferView | ArrayBuffer, + seed?: number, + ) => number | bigint; + murmur32v3: ( + data: string | ArrayBufferView | ArrayBuffer, + seed?: number, + ) => number | bigint; + murmur64v2: ( + data: string | ArrayBufferView | ArrayBuffer, + seed?: number, + ) => number | bigint; + } + + export type Platform = + /** + * When building for bun.js + */ + | "bun" + /** + * When building for the web + */ + | "browser" + /** + * When building for node.js + */ + | "node" + | "neutral"; + + export type JavaScriptLoader = "jsx" | "js" | "ts" | "tsx"; + + export interface TranspilerOptions { + /** + * Replace key with value. Value must be a JSON string. + * @example + * ``` + * { "process.env.NODE_ENV": "\"production\"" } + * ``` + */ + define?: Record<string, string>; + + /** What is the default loader used for this transpiler? */ + loader?: JavaScriptLoader; + + /** What platform are we targeting? This may affect how import and/or require is used */ + /** @example "browser" */ + platform?: Platform; + + /** + * TSConfig.json file as stringified JSON or an object + * Use this to set a custom JSX factory, fragment, or import source + * For example, if you want to use Preact instead of React. Or if you want to use Emotion. + */ + tsconfig?: string; + + /** + * Replace an import statement with a macro. + * + * This will remove the import statement from the final output + * and replace any function calls or template strings with the result returned by the macro + * + * @example + * ```json + * { + * "react-relay": { + * "graphql": "bun-macro-relay" + * } + * } + * ``` + * + * Code that calls `graphql` will be replaced with the result of the macro. + * + * ```js + * import {graphql} from "react-relay"; + * + * // Input: + * const query = graphql` + * query { + * ... on User { + * id + * } + * } + * }`; + * ``` + * + * Will be replaced with: + * + * ```js + * import UserQuery from "./UserQuery.graphql"; + * const query = UserQuery; + * ``` + */ + macros?: MacroMap; + + autoImportJSX?: boolean; + allowBunRuntime?: boolean; + exports?: { + eliminate?: string[]; + replace?: Record<string, string>; + }; + treeShaking?: boolean; + trimUnusedImports?: boolean; + jsxOptimizationInline?: boolean; + } + + /** + * Quickly transpile TypeScript, JSX, or JS to modern JavaScript. + * + * @example + * ```js + * const transpiler = new Bun.Transpiler(); + * transpiler.transformSync(` + * const App = () => <div>Hello World</div>; + *export default App; + * `); + * // This outputs: + * const output = ` + * const App = () => jsx("div", { + * children: "Hello World" + * }, undefined, false, undefined, this); + *export default App; + * ` + * ``` + * + */ + export class Transpiler { + constructor(options: TranspilerOptions); + + /** + * Transpile code from TypeScript or JSX into valid JavaScript. + * This function does not resolve imports. + * @param code The code to transpile + */ + transform(code: StringOrBuffer, loader?: JavaScriptLoader): Promise<string>; + /** + * Transpile code from TypeScript or JSX into valid JavaScript. + * This function does not resolve imports. + * @param code The code to transpile + * + */ + transformSync( + code: StringOrBuffer, + loader: JavaScriptLoader, + ctx: object, + ): string; + /** + * Transpile code from TypeScript or JSX into valid JavaScript. + * This function does not resolve imports. + * @param code The code to transpile + * @param ctx An object to pass to macros + * + */ + transformSync(code: StringOrBuffer, ctx: object): string; + + /** + * Transpile code from TypeScript or JSX into valid JavaScript. + * This function does not resolve imports. + * @param code The code to transpile + * + */ + transformSync(code: StringOrBuffer, loader: JavaScriptLoader): string; + + /** + * Get a list of import paths and paths from a TypeScript, JSX, TSX, or JavaScript file. + * @param code The code to scan + * @example + * ```js + * const {imports, exports} = transpiler.scan(` + * import {foo} from "baz"; + * const hello = "hi!"; + * `); + * + * console.log(imports); // ["baz"] + * console.log(exports); // ["hello"] + * ``` + */ + scan(code: StringOrBuffer): { exports: string[]; imports: Import[] }; + + /** + * Get a list of import paths from a TypeScript, JSX, TSX, or JavaScript file. + * @param code The code to scan + * @example + * ```js + * const imports = transpiler.scanImports(` + * import {foo} from "baz"; + * import type {FooType} from "bar"; + * import type {DogeType} from "wolf"; + * `); + * + * console.log(imports); // ["baz"] + * ``` + * This is a fast path which performs less work than `scan`. + */ + scanImports(code: StringOrBuffer): Import[]; + } + + export interface Import { + path: string; + + kind: + | "import-statement" + | "require-call" + | "require-resolve" + | "dynamic-import" + | "import-rule" + | "url-token" + | "internal" + | "entry-point"; + } + + /** + * **0** means the message was **dropped** + * + * **-1** means **backpressure** + * + * **> 0** is the **number of bytes sent** + * + */ + type ServerWebSocketSendStatus = 0 | -1 | number; + + /** + * Fast WebSocket API designed for server environments. + * + * Features: + * - **Message compression** - Messages can be compressed + * - **Backpressure** - If the client is not ready to receive data, the server will tell you. + * - **Dropped messages** - If the client cannot receive data, the server will tell you. + * - **Topics** - Messages can be {@link ServerWebSocket.publish}ed to a specific topic and the client can {@link ServerWebSocket.subscribe} to topics + * + * This is slightly different than the browser {@link WebSocket} which Bun supports for clients. + * + * Powered by [uWebSockets](https://github.com/uNetworking/uWebSockets) + */ + export interface ServerWebSocket<T = undefined> { + /** + * + * Send a message to the client. + * + * @param data The message to send + * @param compress Should the data be compressed? Ignored if the client does not support compression. + * + * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent. + * + * @example + * + * ```js + * const status = ws.send("Hello World"); + * if (status === 0) { + * console.log("Message was dropped"); + * } else if (status === -1) { + * console.log("Backpressure was applied"); + * } else { + * console.log(`Message sent! ${status} bytes sent`); + * } + * ``` + * + * @example + * + * ```js + * ws.send("Feeling very compressed", true); + * ``` + * + * @example + * + * ```js + * ws.send(new Uint8Array([1, 2, 3, 4])); + * ``` + * + * @example + * + * ```js + * ws.send(new ArrayBuffer(4)); + * ``` + * + * @example + * + * ```js + * ws.send(new DataView(new ArrayBuffer(4))); + * ``` + * + */ + send( + data: string | ArrayBufferView | ArrayBuffer, + compress?: boolean, + ): ServerWebSocketSendStatus; + + /** + * + * Send a message to the client. + * + * This function is the same as {@link ServerWebSocket.send} but it only accepts a string. This function includes a fast path. + * + * @param data The message to send + * @param compress Should the data be compressed? Ignored if the client does not support compression. + * + * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent. + * + * @example + * + * ```js + * const status = ws.send("Hello World"); + * if (status === 0) { + * console.log("Message was dropped"); + * } else if (status === -1) { + * console.log("Backpressure was applied"); + * } else { + * console.log(`Message sent! ${status} bytes sent`); + * } + * ``` + * + * @example + * + * ```js + * ws.send("Feeling very compressed", true); + * ``` + * + * + */ + sendText(data: string, compress?: boolean): ServerWebSocketSendStatus; + + /** + * + * Send a message to the client. + * + * This function is the same as {@link ServerWebSocket.send} but it only accepts Uint8Array. + * + * @param data The message to send + * @param compress Should the data be compressed? Ignored if the client does not support compression. + * + * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent. + * + * + * ```js + * ws.sendBinary(new Uint8Array([1, 2, 3, 4])); + * ``` + * + * @example + * + * ```js + * ws.sendBinary(new ArrayBuffer(4)); + * ``` + * + * @example + * + * ```js + * ws.sendBinary(new DataView(new ArrayBuffer(4))); + * ``` + * + */ + sendBinary(data: Uint8Array, compress?: boolean): ServerWebSocketSendStatus; + + /** + * Gently close the connection. + * + * @param code The close code + * + * @param reason The close reason + * + * To close the connection abruptly, use `close(0, "")` + */ + close(code?: number, reason?: string): void; + + /** + * Send a message to all subscribers of a topic + * + * @param topic The topic to publish to + * @param data The data to send + * @param compress Should the data be compressed? Ignored if the client does not support compression. + * + * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent. + * + * @example + * + * ```js + * ws.publish("chat", "Hello World"); + * ``` + * + * @example + * ```js + * ws.publish("chat", new Uint8Array([1, 2, 3, 4])); + * ``` + * + * @example + * ```js + * ws.publish("chat", new ArrayBuffer(4), true); + * ``` + * + * @example + * ```js + * ws.publish("chat", new DataView(new ArrayBuffer(4))); + * ``` + */ + publish( + topic: string, + data: string | ArrayBufferView | ArrayBuffer, + compress?: boolean, + ): ServerWebSocketSendStatus; + + /** + * Send a message to all subscribers of a topic + * + * This function is the same as {@link publish} but only accepts string input. This function has a fast path. + * + * @param topic The topic to publish to + * @param data The data to send + * @param compress Should the data be compressed? Ignored if the client does not support compression. + * + * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent. + * + * @example + * + * ```js + * ws.publishText("chat", "Hello World"); + * ``` + * + */ + publishText( + topic: string, + data: string, + compress?: boolean, + ): ServerWebSocketSendStatus; + + /** + * Send a message to all subscribers of a topic + * + * This function is the same as {@link publish} but only accepts a Uint8Array. This function has a fast path. + * + * @param topic The topic to publish to + * @param data The data to send + * @param compress Should the data be compressed? Ignored if the client does not support compression. + * + * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent. + * + * @example + * + * ```js + * ws.publishBinary("chat", "Hello World"); + * ``` + * + * @example + * ```js + * ws.publishBinary("chat", new Uint8Array([1, 2, 3, 4])); + * ``` + * + * @example + * ```js + * ws.publishBinary("chat", new ArrayBuffer(4), true); + * ``` + * + * @example + * ```js + * ws.publishBinary("chat", new DataView(new ArrayBuffer(4))); + * ``` + */ + publishBinary( + topic: string, + data: Uint8Array, + compress?: boolean, + ): ServerWebSocketSendStatus; + + /** + * Subscribe to a topic + * @param topic The topic to subscribe to + * + * @example + * ```js + * ws.subscribe("chat"); + * ``` + */ + subscribe(topic: string): void; + + /** + * Unsubscribe from a topic + * @param topic The topic to unsubscribe from + * + * @example + * ```js + * ws.unsubscribe("chat"); + * ``` + * + */ + unsubscribe(topic: string): void; + + /** + * Is the socket subscribed to a topic? + * @param topic The topic to check + * + * @returns `true` if the socket is subscribed to the topic, `false` otherwise + */ + isSubscribed(topic: string): boolean; + + /** + * The remote address of the client + * @example + * ```js + * console.log(socket.remoteAddress); // "127.0.0.1" + * ``` + */ + readonly remoteAddress: string; + + /** + * Ready state of the socket + * + * @example + * ```js + * console.log(socket.readyState); // 1 + * ``` + */ + readonly readyState: -1 | 0 | 1 | 2 | 3; + + /** + * The data from the {@link Server.upgrade} function + * + * Put any data you want to share between the `fetch` function and the websocket here. + * + * You can read/write to this property at any time. + */ + data: T; + + /** + * Batch data sent to a {@link ServerWebSocket} + * + * This makes it significantly faster to {@link ServerWebSocket.send} or {@link ServerWebSocket.publish} multiple messages + * + * The `message`, `open`, and `drain` callbacks are automatically corked, so + * you only need to call this if you are sending messages outside of those + * callbacks or in async functions + */ + cork: (callback: (ws: ServerWebSocket<T>) => any) => void | Promise<void>; + + /** + * Configure the {@link WebSocketHandler.message} callback to return a {@link ArrayBuffer} instead of a {@link Uint8Array} + * + * @default "uint8array" + */ + binaryType?: "arraybuffer" | "uint8array"; + } + + type WebSocketCompressor = + | "disable" + | "shared" + | "dedicated" + | "3KB" + | "4KB" + | "8KB" + | "16KB" + | "32KB" + | "64KB" + | "128KB" + | "256KB"; + + /** + * Create a server-side {@link ServerWebSocket} handler for use with {@link Bun.serve} + * + * @example + * ```ts + * import { websocket, serve } from "bun"; + * + * serve({ + * port: 3000, + * websocket: websocket<{name: string}>({ + * open: (ws) => { + * console.log("Client connected"); + * }, + * message: (ws, message) => { + * console.log(`${ws.data.name}: ${message}`); + * }, + * close: (ws) => { + * console.log("Client disconnected"); + * }, + * }), + * + * fetch(req, server) { + * if (req.url === "/chat") { + * const upgraded = server.upgrade(req, { + * data: { + * name: new URL(req.url).searchParams.get("name"), + * }, + * }); + * if (!upgraded) { + * return new Response("Upgrade failed", { status: 400 }); + * } + * return; + * } + * return new Response("Hello World"); + * }, + * }); + */ + export interface WebSocketHandler<T = undefined> { + /** + * Handle an incoming message to a {@link ServerWebSocket} + * + * @param ws The {@link ServerWebSocket} that received the message + * @param message The message received + * + * To change `message` to be an `ArrayBuffer` instead of a `Uint8Array`, set `ws.binaryType = "arraybuffer"` + */ + message: ( + ws: ServerWebSocket<T>, + message: string | Uint8Array, + ) => void | Promise<void>; + + /** + * The {@link ServerWebSocket} has been opened + * + * @param ws The {@link ServerWebSocket} that was opened + */ + open?: (ws: ServerWebSocket<T>) => void | Promise<void>; + /** + * The {@link ServerWebSocket} is ready for more data + * + * @param ws The {@link ServerWebSocket} that is ready + */ + drain?: (ws: ServerWebSocket<T>) => void | Promise<void>; + /** + * The {@link ServerWebSocket} is being closed + * @param ws The {@link ServerWebSocket} that was closed + * @param code The close code + * @param message The close message + */ + close?: ( + ws: ServerWebSocket<T>, + code: number, + message: string, + ) => void | Promise<void>; + + /** + * Enable compression for clients that support it. By default, compression is disabled. + * + * @default false + * + * `true` is equivalent to `"shared" + */ + perMessageDeflate?: + | true + | false + | { + /** + * Enable compression on the {@link ServerWebSocket} + * + * @default false + * + * `true` is equivalent to `"shared" + */ + compress?: WebSocketCompressor | false | true; + /** + * Configure decompression + * + * @default false + * + * `true` is equivalent to `"shared" + */ + decompress?: WebSocketCompressor | false | true; + }; + + /** + * The maximum size of a message + */ + maxPayloadLength?: number; + /** + * After a connection has not received a message for this many seconds, it will be closed. + * @default 120 (2 minutes) + */ + idleTimeout?: number; + /** + * The maximum number of bytes that can be buffered for a single connection. + * @default 16MB + */ + backpressureLimit?: number; + /** + * Close the connection if the backpressure limit is reached. + * @default false + * @see {@link backpressureLimit} + * @see {@link ServerWebSocketSendStatus} + * @see {@link ServerWebSocket.send} + * @see {@link ServerWebSocket.publish} + */ + closeOnBackpressureLimit?: boolean; + } + + interface GenericServeOptions { + /** + * What port should the server listen on? + * @default process.env.PORT || "3000" + */ + port?: string | number; + + /** + * What hostname should the server listen on? + * + * @default + * ```js + * "0.0.0.0" // listen on all interfaces + * ``` + * @example + * ```js + * "127.0.0.1" // Only listen locally + * ``` + * @example + * ```js + * "remix.run" // Only listen on remix.run + * ```` + * + * note: hostname should not include a {@link port} + */ + hostname?: string; + + /** + * What URI should be used to make {@link Request.url} absolute? + * + * By default, looks at {@link hostname}, {@link port}, and whether or not SSL is enabled to generate one + * + * @example + *```js + * "http://my-app.com" + * ``` + * + * @example + *```js + * "https://wongmjane.com/" + * ``` + * + * This should be the public, absolute URL – include the protocol and {@link hostname}. If the port isn't 80 or 443, then include the {@link port} too. + * + * @example + * "http://localhost:3000" + * + */ + baseURI?: string; + + /** + * What is the maximum size of a request body? (in bytes) + * @default 1024 * 1024 * 128 // 128MB + */ + maxRequestBodySize?: number; + + /** + * Render contextual errors? This enables bun's error page + * @default process.env.NODE_ENV !== 'production' + */ + development?: boolean; + + error?: ( + this: Server, + request: Errorlike, + ) => Response | Promise<Response> | undefined | void | Promise<undefined>; + } + + export interface ServeOptions extends GenericServeOptions { + /** + * Handle HTTP requests + * + * Respond to {@link Request} objects with a {@link Response} object. + * + */ + fetch( + this: Server, + request: Request, + server: Server, + ): Response | Promise<Response>; + } + + export interface WebSocketServeOptions<WebSocketDataType = undefined> + extends GenericServeOptions { + /** + * Enable websockets with {@link Bun.serve} + * + * For simpler type safety, see {@link Bun.websocket} + * + * @example + * ```js + *import { serve, websocket } from "bun"; + *serve({ + * websocket: websocket({ + * open: (ws) => { + * console.log("Client connected"); + * }, + * message: (ws, message) => { + * console.log("Client sent message", message); + * }, + * close: (ws) => { + * console.log("Client disconnected"); + * }, + * }), + * fetch(req, server) { + * if (req.url === "/chat") { + * const upgraded = server.upgrade(req); + * if (!upgraded) { + * return new Response("Upgrade failed", { status: 400 }); + * } + * } + * return new Response("Hello World"); + * }, + *}); + *``` + * Upgrade a {@link Request} to a {@link ServerWebSocket} via {@link Server.upgrade} + * + * Pass `data` in @{link Server.upgrade} to attach data to the {@link ServerWebSocket.data} property + * + * + */ + websocket: WebSocketHandler<WebSocketDataType>; + + /** + * Handle HTTP requests or upgrade them to a {@link ServerWebSocket} + * + * Respond to {@link Request} objects with a {@link Response} object. + * + */ + fetch( + this: Server, + request: Request, + server: Server, + ): Response | undefined | Promise<Response | undefined>; + } + + export interface Errorlike extends Error { + code?: string; + errno?: number; + syscall?: string; + } + + interface TLSOptions { + /** + * File path to a TLS key + * + * To enable TLS, this option is required. + */ + keyFile: string; + /** + * File path to a TLS certificate + * + * To enable TLS, this option is required. + */ + certFile: string; + + passphrase?: string; + caFile?: string; + dhParamsFile?: string; + + /** + * This sets `OPENSSL_RELEASE_BUFFERS` to 1. + * It reduces overall performance but saves some memory. + * @default false + */ + lowMemoryMode?: boolean; + } + + export type TLSServeOptions<WebSocketDataType = undefined> = ( + | WebSocketServeOptions<WebSocketDataType> + | ServerWebSocket + ) & + TLSOptions & { + /** + * The keys are [SNI](https://en.wikipedia.org/wiki/Server_Name_Indication) hostnames. + * The values are SSL options objects. + */ + serverNames: Record<string, TLSOptions>; + }; + + /** + * HTTP & HTTPS Server + * + * To start the server, see {@link serve} + * + * For performance, Bun pre-allocates most of the data for 2048 concurrent requests. + * That means starting a new server allocates about 500 KB of memory. Try to + * avoid starting and stopping the server often (unless it's a new instance of bun). + * + * Powered by a fork of [uWebSockets](https://github.com/uNetworking/uWebSockets). Thank you @alexhultman. + * + */ + export interface Server { + /** + * Stop listening to prevent new connections from being accepted. + * + * It does not close existing connections. + * + * It may take a second or two to actually stop. + */ + stop(): void; + + /** + * Update the `fetch` and `error` handlers without restarting the server. + * + * This is useful if you want to change the behavior of your server without + * restarting it or for hot reloading. + * + * @example + * + * ```js + * // create the server + * const server = Bun.serve({ + * fetch(request) { + * return new Response("Hello World v1") + * } + * }); + * + * // Update the server to return a different response + * server.update({ + * fetch(request) { + * return new Response("Hello World v2") + * } + * }); + * ``` + * + * Passing other options such as `port` or `hostname` won't do anything. + */ + reload(options: Serve): void; + + /** + * Mock the fetch handler for a running server. + * + * This feature is not fully implemented yet. It doesn't normalize URLs + * consistently in all cases and it doesn't yet call the `error` handler + * consistently. This needs to be fixed + */ + fetch(request: Request): Response | Promise<Response>; + + /** + * Upgrade a {@link Request} to a {@link ServerWebSocket} + * + * @param request The {@link Request} to upgrade + * @param options Pass headers or attach data to the {@link ServerWebSocket} + * + * @returns `true` if the upgrade was successful and `false` if it failed + * + * @example + * ```js + * import { serve, websocket } from "bun"; + * serve({ + * websocket: websocket({ + * open: (ws) => { + * console.log("Client connected"); + * }, + * message: (ws, message) => { + * console.log("Client sent message", message); + * }, + * close: (ws) => { + * console.log("Client disconnected"); + * }, + * }), + * fetch(req, server) { + * if (req.url === "/chat") { + * const upgraded = server.upgrade(req); + * if (!upgraded) { + * return new Response("Upgrade failed", { status: 400 }); + * } + * } + * return new Response("Hello World"); + * }, + * }); + * ``` + * What you pass to `data` is available on the {@link ServerWebSocket.data} property + * + */ + upgrade<T = undefined>( + request: Request, + options?: { + /** + * Send any additional headers while upgrading, like cookies + */ + headers?: HeadersInit; + /** + * This value is passed to the {@link ServerWebSocket.data} property + */ + data?: T; + }, + ): boolean; + + /** + * How many requests are in-flight right now? + */ + readonly pendingRequests: number; + + /** + * How many {@link ServerWebSocket}s are in-flight right now? + */ + readonly pendingWebSockets: number; + + readonly port: number; + /** + * The hostname the server is listening on. Does not include the port + * @example + * ```js + * "localhost" + * ``` + */ + readonly hostname: string; + /** + * Is the server running in development mode? + * + * In development mode, `Bun.serve()` returns rendered error messages with + * stack traces instead of a generic 500 error. This makes debugging easier, + * but development mode shouldn't be used in production or you will risk + * leaking sensitive information. + * + */ + readonly development: boolean; + } + + export type Serve<WebSocketDataType = undefined> = + | TLSServeOptions<WebSocketDataType> + | WebSocketServeOptions<WebSocketDataType> + | ServeOptions; + + /** + * [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) powered by the fastest system calls available for operating on files. + * + * This Blob is lazy. That means it won't do any work until you read from it. + * + * - `size` will not be valid until the contents of the file are read at least once. + * - `type` is auto-set based on the file extension when possible + * + * @example + * ```js + * const file = Bun.file("./hello.json"); + * console.log(file.type); // "application/json" + * console.log(await file.json()); // { hello: "world" } + * ``` + * + * @example + * ```js + * await Bun.write( + * Bun.file("./hello.txt"), + * "Hello, world!" + * ); + * ``` + * @param path The path to the file (lazily loaded) + * + */ + // tslint:disable-next-line:unified-signatures + export function file(path: string, options?: BlobPropertyBag): FileBlob; + + /** + * `Blob` that leverages the fastest system calls available to operate on files. + * + * This Blob is lazy. It won't do any work until you read from it. Errors propagate as promise rejections. + * + * `Blob.size` will not be valid until the contents of the file are read at least once. + * `Blob.type` will have a default set based on the file extension + * + * @example + * ```js + * const file = Bun.file(new TextEncoder.encode("./hello.json")); + * console.log(file.type); // "application/json" + * ``` + * + * @param path The path to the file as a byte buffer (the buffer is copied) + */ + // tslint:disable-next-line:unified-signatures + export function file( + path: ArrayBufferLike | Uint8Array, + options?: BlobPropertyBag, + ): FileBlob; + + /** + * [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) powered by the fastest system calls available for operating on files. + * + * This Blob is lazy. That means it won't do any work until you read from it. + * + * - `size` will not be valid until the contents of the file are read at least once. + * + * @example + * ```js + * const file = Bun.file(fd); + * ``` + * + * @param fileDescriptor The file descriptor of the file + */ + // tslint:disable-next-line:unified-signatures + export function file( + fileDescriptor: number, + options?: BlobPropertyBag, + ): FileBlob; + + /** + * Allocate a new [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) without zeroing the bytes. + * + * This can be 3.5x faster than `new Uint8Array(size)`, but if you send uninitialized memory to your users (even unintentionally), it can potentially leak anything recently in memory. + */ + export function allocUnsafe(size: number): Uint8Array; + + /** + * Pretty-print an object the same as {@link console.log} to a `string` + * + * Supports JSX + * + * @param args + */ + export function inspect(...args: any): string; + + interface MMapOptions { + /** + * Sets MAP_SYNC flag on Linux. Ignored on macOS due to lack of support. + */ + sync?: boolean; + /** + * Allow other processes to see results instantly? + * This enables MAP_SHARED. If false, it enables MAP_PRIVATE. + * @default true + */ + shared?: boolean; + } + /** + * Open a file as a live-updating `Uint8Array` without copying memory + * - Writing to the array writes to the file. + * - Reading from the array reads from the file. + * + * This uses the [`mmap()`](https://man7.org/linux/man-pages/man2/mmap.2.html) syscall under the hood. + * + * --- + * + * This API inherently has some rough edges: + * - It does not support empty files. It will throw a `SystemError` with `EINVAL` + * - Usage on shared/networked filesystems is discouraged. It will be very slow. + * - If you delete or truncate the file, that will crash bun. This is called a segmentation fault. + * + * --- + * + * To close the file, set the array to `null` and it will be garbage collected eventually. + * + */ + export function mmap(path: PathLike, opts?: MMapOptions): Uint8Array; + + /** Write to stdout */ + const stdout: FileBlob; + /** Write to stderr */ + const stderr: FileBlob; + /** + * Read from stdin + * + * This is read-only + */ + const stdin: FileBlob; + + interface unsafe { + /** + * Cast bytes to a `String` without copying. This is the fastest way to get a `String` from a `Uint8Array` or `ArrayBuffer`. + * + * **Only use this for ASCII strings**. If there are non-ascii characters, your application may crash and/or very confusing bugs will happen such as `"foo" !== "foo"`. + * + * **The input buffer must not be garbage collected**. That means you will need to hold on to it for the duration of the string's lifetime. + * + */ + arrayBufferToString(buffer: Uint8Array | ArrayBufferLike): string; + + /** + * Cast bytes to a `String` without copying. This is the fastest way to get a `String` from a `Uint16Array` + * + * **The input must be a UTF-16 encoded string**. This API does no validation whatsoever. + * + * **The input buffer must not be garbage collected**. That means you will need to hold on to it for the duration of the string's lifetime. + * + */ + // tslint:disable-next-line:unified-signatures + arrayBufferToString(buffer: Uint16Array): string; + + /** Mock bun's segfault handler. You probably don't want to use this */ + segfault(): void; + } + export const unsafe: unsafe; + + type DigestEncoding = "hex" | "base64"; + + /** + * Are ANSI colors enabled for stdin and stdout? + * + * Used for {@link console.log} + */ + export const enableANSIColors: boolean; + + /** + * What script launched bun? + * + * Absolute file path + * + * @example "/never-gonna-give-you-up.js" + */ + export const main: string; + + /** + * Manually trigger the garbage collector + * + * This does two things: + * 1. It tells JavaScriptCore to run the garbage collector + * 2. It tells [mimalloc](https://github.com/microsoft/mimalloc) to clean up fragmented memory. Mimalloc manages the heap not used in JavaScriptCore. + * + * @param force Synchronously run the garbage collector + */ + export function gc(force: boolean): void; + + /** + * JavaScriptCore engine's internal heap snapshot + * + * I don't know how to make this something Chrome or Safari can read. + * + * If you have any ideas, please file an issue https://github.com/oven-sh/bun + */ + interface HeapSnapshot { + /** "2" */ + version: string; + + /** "Inspector" */ + type: string; + + nodes: number[]; + + nodeClassNames: string[]; + edges: number[]; + edgeTypes: string[]; + edgeNames: string[]; + } + + /** + * Nanoseconds since Bun.js was started as an integer. + * + * This uses a high-resolution monotonic system timer. + * + * After 14 weeks of consecutive uptime, this function + * wraps + */ + export function nanoseconds(): number; + + /** + * Generate a heap snapshot for seeing where the heap is being used + */ + export function generateHeapSnapshot(): HeapSnapshot; + + /** + * The next time JavaScriptCore is idle, clear unused memory and attempt to reduce the heap size. + */ + export function shrink(): void; + + /** + * Open a file in your local editor. Auto-detects via `$VISUAL` || `$EDITOR` + * + * @param path path to open + */ + export function openInEditor(path: string, options?: EditorOptions): void; + + interface EditorOptions { + editor?: "vscode" | "subl"; + line?: number; + column?: number; + } + + /** + * This class only exists in types + */ + abstract class CryptoHashInterface<T> { + /** + * Update the hash with data + * + * @param data + */ + update(data: StringOrBuffer): T; + + /** + * Finalize the hash + * + * @param encoding `DigestEncoding` to return the hash in. If none is provided, it will return a `Uint8Array`. + */ + digest(encoding: DigestEncoding): string; + + /** + * Finalize the hash + * + * @param hashInto `TypedArray` to write the hash into. Faster than creating a new one each time + */ + digest(hashInto?: TypedArray): TypedArray; + + /** + * Run the hash over the given data + * + * @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` is faster. + * + * @param hashInto `TypedArray` to write the hash into. Faster than creating a new one each time + */ + static hash(input: StringOrBuffer, hashInto?: TypedArray): TypedArray; + + /** + * Run the hash over the given data + * + * @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` is faster. + * + * @param encoding `DigestEncoding` to return the hash in + */ + static hash(input: StringOrBuffer, encoding: DigestEncoding): string; + } + + /** + * Sleep the thread for a given number of milliseconds + * + * This is a blocking function. + * + * Internally, it calls [nanosleep(2)](https://man7.org/linux/man-pages/man2/nanosleep.2.html) + */ + export function sleepSync(ms: number): void; + + /** + * + * Hash `input` using [SHA-2 512/256](https://en.wikipedia.org/wiki/SHA-2#Comparison_of_SHA_functions) + * + * @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` will be faster + * @param hashInto optional `Uint8Array` to write the hash to. 32 bytes minimum. + * + * This hashing function balances speed with cryptographic strength. This does not encrypt or decrypt data. + * + * The implementation uses [BoringSSL](https://boringssl.googlesource.com/boringssl) (used in Chromium & Go) + * + * The equivalent `openssl` command is: + * + * ```bash + * # You will need OpenSSL 3 or later + * openssl sha512-256 /path/to/file + *``` + */ + export function sha(input: StringOrBuffer, hashInto?: Uint8Array): Uint8Array; + + /** + * + * Hash `input` using [SHA-2 512/256](https://en.wikipedia.org/wiki/SHA-2#Comparison_of_SHA_functions) + * + * @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` will be faster + * @param encoding `DigestEncoding` to return the hash in + * + * This hashing function balances speed with cryptographic strength. This does not encrypt or decrypt data. + * + * The implementation uses [BoringSSL](https://boringssl.googlesource.com/boringssl) (used in Chromium & Go) + * + * The equivalent `openssl` command is: + * + * ```bash + * # You will need OpenSSL 3 or later + * openssl sha512-256 /path/to/file + *``` + */ + export function sha(input: StringOrBuffer, encoding: DigestEncoding): string; + + /** + * This is not the default because it's not cryptographically secure and it's slower than {@link SHA512} + * + * Consider using the ugly-named {@link SHA512_256} instead + */ + export class SHA1 extends CryptoHashInterface<SHA1> { + constructor(); + + /** + * The number of bytes the hash will produce + */ + static readonly byteLength: 20; + } + export class MD5 extends CryptoHashInterface<MD5> { + constructor(); + + /** + * The number of bytes the hash will produce + */ + static readonly byteLength: 16; + } + export class MD4 extends CryptoHashInterface<MD4> { + constructor(); + + /** + * The number of bytes the hash will produce + */ + static readonly byteLength: 16; + } + export class SHA224 extends CryptoHashInterface<SHA224> { + constructor(); + + /** + * The number of bytes the hash will produce + */ + static readonly byteLength: 28; + } + export class SHA512 extends CryptoHashInterface<SHA512> { + constructor(); + + /** + * The number of bytes the hash will produce + */ + static readonly byteLength: 64; + } + export class SHA384 extends CryptoHashInterface<SHA384> { + constructor(); + + /** + * The number of bytes the hash will produce + */ + static readonly byteLength: 48; + } + export class SHA256 extends CryptoHashInterface<SHA256> { + constructor(); + + /** + * The number of bytes the hash will produce + */ + static readonly byteLength: 32; + } + /** + * See also {@link sha} + */ + export class SHA512_256 extends CryptoHashInterface<SHA512_256> { + constructor(); + + /** + * The number of bytes the hash will produce + */ + static readonly byteLength: 32; + } + + /** Compression options for `Bun.deflateSync` and `Bun.gzipSync` */ + export type ZlibCompressionOptions = { + /** + * The compression level to use. Must be between `-1` and `9`. + * - A value of `-1` uses the default compression level (Currently `6`) + * - A value of `0` gives no compression + * - A value of `1` gives least compression, fastest speed + * - A value of `9` gives best compression, slowest speed + */ + level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + /** + * How much memory should be allocated for the internal compression state. + * + * A value of `1` uses minimum memory but is slow and reduces compression ratio. + * + * A value of `9` uses maximum memory for optimal speed. The default is `8`. + */ + memLevel?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + /** + * The base 2 logarithm of the window size (the size of the history buffer). + * + * Larger values of this parameter result in better compression at the expense of memory usage. + * + * The following value ranges are supported: + * - `9..15`: The output will have a zlib header and footer (Deflate) + * - `-9..-15`: The output will **not** have a zlib header or footer (Raw Deflate) + * - `25..31` (16+`9..15`): The output will have a gzip header and footer (gzip) + * + * The gzip header will have no file name, no extra data, no comment, no modification time (set to zero) and no header CRC. + */ + windowBits?: + | -9 + | -10 + | -11 + | -12 + | -13 + | -14 + | -15 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 15 + | 25 + | 26 + | 27 + | 28 + | 29 + | 30 + | 31; + /** + * Tunes the compression algorithm. + * + * - `Z_DEFAULT_STRATEGY`: For normal data **(Default)** + * - `Z_FILTERED`: For data produced by a filter or predictor + * - `Z_HUFFMAN_ONLY`: Force Huffman encoding only (no string match) + * - `Z_RLE`: Limit match distances to one (run-length encoding) + * - `Z_FIXED` prevents the use of dynamic Huffman codes + * + * `Z_RLE` is designed to be almost as fast as `Z_HUFFMAN_ONLY`, but give better compression for PNG image data. + * + * `Z_FILTERED` forces more Huffman coding and less string matching, it is + * somewhat intermediate between `Z_DEFAULT_STRATEGY` and `Z_HUFFMAN_ONLY`. + * Filtered data consists mostly of small values with a somewhat random distribution. + */ + strategy?: number; + }; + + /** + * Compresses a chunk of data with `zlib` DEFLATE algorithm. + * @param data The buffer of data to compress + * @param options Compression options to use + * @returns The output buffer with the compressed data + */ + export function deflateSync( + data: Uint8Array, + options?: ZlibCompressionOptions, + ): Uint8Array; + /** + * Compresses a chunk of data with `zlib` GZIP algorithm. + * @param data The buffer of data to compress + * @param options Compression options to use + * @returns The output buffer with the compressed data + */ + export function gzipSync( + data: Uint8Array, + options?: ZlibCompressionOptions, + ): Uint8Array; + /** + * Decompresses a chunk of data with `zlib` INFLATE algorithm. + * @param data The buffer of data to decompress + * @returns The output buffer with the decompressed data + */ + export function inflateSync(data: Uint8Array): Uint8Array; + /** + * Decompresses a chunk of data with `zlib` GUNZIP algorithm. + * @param data The buffer of data to decompress + * @returns The output buffer with the decompressed data + */ + export function gunzipSync(data: Uint8Array): Uint8Array; + + export type PluginTarget = + /** + * The default environment when using `bun run` or `bun` to load a script + */ + | "bun" + /** + * The plugin will be applied to Node.js builds + */ + | "node" + /** + * The plugin will be applied to browser builds + */ + | "browser"; + + interface PluginConstraints { + /** + * Only apply the plugin when the import specifier matches this regular expression + * + * @example + * ```ts + * // Only apply the plugin when the import specifier matches the regex + * Bun.plugin({ + * setup(builder) { + * builder.onLoad({ filter: /node_modules\/underscore/ }, (args) => { + * return { contents: "throw new Error('Please use lodash instead of underscore.')" }; + * }); + * } + * }) + * ``` + */ + filter: RegExp; + + /** + * Only apply the plugin when the import specifier has a namespace matching + * this string + * + * Namespaces are prefixes in import specifiers. For example, `"bun:ffi"` + * has the namespace `"bun"`. + * + * The default namespace is `"file"` and it can be omitted from import + * specifiers. + */ + namespace?: string; + } + + interface OnLoadResultSourceCode { + /** + * The source code of the module + */ + contents: string | ArrayBufferView | ArrayBuffer; + /** + * The loader to use for this file + * + * "css" will be added in a future version of Bun. + */ + loader: "js" | "jsx" | "ts" | "tsx"; + } + + interface OnLoadResultObject { + /** + * The object to use as the module + * @example + * ```ts + * // In your loader + * builder.onLoad({ filter: /^hello:world$/ }, (args) => { + * return { exports: { foo: "bar" }, loader: "object" }; + * }); + * + * // In your script + * import {foo} from "hello:world"; + * console.log(foo); // "bar" + * ``` + */ + exports: Record<string, unknown>; + /** + * The loader to use for this file + */ + loader: "object"; + } + + interface OnLoadArgs { + /** + * The resolved import specifier of the module being loaded + * @example + * ```ts + * builder.onLoad({ filter: /^hello:world$/ }, (args) => { + * console.log(args.path); // "hello:world" + * return { exports: { foo: "bar" }, loader: "object" }; + * }); + * ``` + */ + path: string; + } + + type OnLoadResult = OnLoadResultSourceCode | OnLoadResultObject; + type OnLoadCallback = ( + args: OnLoadArgs, + ) => OnLoadResult | Promise<OnLoadResult>; + + interface OnResolveArgs { + /** + * The import specifier of the module being loaded + */ + path: string; + /** + * The module that imported the module being resolved + */ + importer: string; + } + + interface OnResolveResult { + /** + * The destination of the import + */ + path: string; + /** + * The namespace of the destination + * It will be concatenated with `path` to form the final import specifier + * @example + * ```ts + * "foo" // "foo:bar" + * ``` + */ + namespace?: string; + } + + type OnResolveCallback = (args: OnResolveArgs) => OnResolveResult | void; + + interface PluginBuilder { + /** + * Register a callback to load imports with a specific import specifier + * @param constraints The constraints to apply the plugin to + * @param callback The callback to handle the import + * @example + * ```ts + * Bun.plugin({ + * setup(builder) { + * builder.onLoad({ filter: /^hello:world$/ }, (args) => { + * return { exports: { foo: "bar" }, loader: "object" }; + * }); + * }, + * }); + * ``` + */ + onLoad(constraints: PluginConstraints, callback: OnLoadCallback): void; + /** + * Register a callback to resolve imports matching a filter and/or namespace + * @param constraints The constraints to apply the plugin to + * @param callback The callback to handle the import + * @example + * ```ts + * Bun.plugin({ + * setup(builder) { + * builder.onResolve({ filter: /^wat$/ }, (args) => { + * return { path: "/tmp/woah.js" }; + * }); + * }, + * }); + * ``` + */ + onResolve( + constraints: PluginConstraints, + callback: OnResolveCallback, + ): void; + /** + * The current target environment + */ + target: PluginTarget; + } + + /** + * Extend Bun's module resolution and loading behavior + * + * Plugins are applied in the order they are defined. + * + * Today, there are two kinds of hooks: + * - `onLoad` lets you return source code or an object that will become the module's exports + * - `onResolve` lets you redirect a module specifier to another module specifier. It does not chain. + * + * Plugin hooks must define a `filter` RegExp and will only be matched if the + * import specifier contains a "." or a ":". + * + * ES Module resolution semantics mean that plugins may be initialized _after_ + * a module is resolved. You might need to load plugins at the very beginning + * of the application and then use a dynamic import to load the rest of the + * application. A future version of Bun may also support specifying plugins + * via `bunfig.toml`. + * + * + * @example + * A YAML loader plugin + * + * ```js + *Bun.plugin({ + * setup(builder) { + * builder.onLoad({ filter: /\.yaml$/ }, ({path}) => ({ + * loader: "object", + * exports: require("js-yaml").load(fs.readFileSync(path, "utf8")) + * })); + *}); + * + * // You can use require() + * const {foo} = require("./file.yaml"); + * + * // Or import + * await import("./file.yaml"); + * + * ``` + */ + interface BunPlugin { + (options: { + /** + * Human-readable name of the plugin + * + * In a future version of Bun, this will be used in error messages. + */ + name?: string; + + /** + * The target JavaScript environment the plugin should be applied to. + * - `bun`: The default environment when using `bun run` or `bun` to load a script + * - `browser`: The plugin will be applied to browser builds + * - `node`: The plugin will be applied to Node.js builds + * + * If in Bun's runtime, the default target is `bun`. + * + * If unspecified, it is assumed that the plugin is compatible with the default target. + */ + target?: PluginTarget; + /** + * A function that will be called when the plugin is loaded. + * + * This function may be called in the same tick that it is registered, or it may be called later. It could potentially be called multiple times for different targets. + */ + setup( + /** + * A builder object that can be used to register plugin hooks + * @example + * ```ts + * builder.onLoad({ filter: /\.yaml$/ }, ({ path }) => ({ + * loader: "object", + * exports: require("js-yaml").load(fs.readFileSync(path, "utf8")), + * })); + * ``` + */ + builder: PluginBuilder, + ): void | Promise<void>; + }): ReturnType<typeof options["setup"]>; + + /** + * Deactivate all plugins + * + * This prevents registered plugins from being applied to future builds. + */ + clearAll(): void; + } + + var plugin: BunPlugin; + + interface Socket<Data = undefined> { + /** + * Write `data` to the socket + * + * @param data The data to write to the socket + * @param byteOffset The offset in the buffer to start writing from (defaults to 0) + * @param byteLength The number of bytes to write (defaults to the length of the buffer) + * + * When passed a string, `byteOffset` and `byteLength` refer to the UTF-8 offset, not the string character offset. + * + * This is unbuffered as of Bun v0.2.2. That means individual write() calls + * will be slow. In the future, Bun will buffer writes and flush them at the + * end of the tick, when the event loop is idle, or sooner if the buffer is full. + */ + write( + data: string | BufferSource, + byteOffset?: number, + byteLength?: number, + ): number; + + /** + * The data context for the socket. + */ + data: Data; + + /** + * Like {@link Socket.write} except it includes a TCP FIN packet + * + * Use it to send your last message and close the connection. + */ + end( + data?: string | BufferSource, + byteOffset?: number, + byteLength?: number, + ): number; + + /** + * Close the socket immediately + */ + end(): void; + + /** + * Keep Bun's process alive at least until this socket is closed + * + * After the socket has closed, the socket is unref'd, the process may exit, + * and this becomes a no-op + */ + ref(): void; + + /** + * Set a timeout until the socket automatically closes. + * + * To reset the timeout, call this function again. + * + * When a timeout happens, the `timeout` callback is called and the socket is closed. + */ + timeout(seconds: number): void; + + /** + * Shutdown writes to a socket + * + * This makes the socket a half-closed socket. It can still receive data. + * + * This calls [shutdown(2)](https://man7.org/linux/man-pages/man2/shutdown.2.html) internally + */ + shutdown(halfClose?: boolean): void; + + readonly readyState: "open" | "closing" | "closed"; + + /** + * Allow Bun's process to exit even if this socket is still open + * + * After the socket has closed, this function does nothing. + */ + unref(): void; + + /** + * Reset the socket's callbacks. This is useful with `bun --hot` to facilitate hot reloading. + * + * This will apply to all sockets from the same {@link Listener}. it is per socket only for {@link Bun.connect}. + */ + reload(handler: SocketHandler): void; + + /** + * Get the server that created this socket + * + * This will return undefined if the socket was created by {@link Bun.connect} or if the listener has already closed. + */ + readonly listener?: SocketListener; + } + + interface SocketListener<Options extends SocketOptions = SocketOptions> { + stop(): void; + ref(): void; + unref(): void; + reload(options: Pick<Partial<Options>, "socket">): void; + data: Options["data"]; + } + interface TCPSocketListener<Options extends TCPSocketOptions<unknown>> + extends SocketListener<Options> { + readonly port: number; + readonly hostname: string; + } + interface UnixSocketListener<Options extends UnixSocketOptions<unknown>> + extends SocketListener<Options> { + readonly unix: string; + } + + interface TCPSocket extends Socket {} + interface TLSSocket extends Socket {} + + interface SocketHandler<Data = unknown> { + open(socket: Socket<Data>): void | Promise<void>; + close?(socket: Socket<Data>): void | Promise<void>; + error?(socket: Socket<Data>, error: Error): void | Promise<void>; + data?(socket: Socket<Data>, data: BufferSource): void | Promise<void>; + drain?(socket: Socket<Data>): void | Promise<void>; + } + + interface SocketOptions<Data = unknown> { + socket: SocketHandler<Data>; + tls?: TLSOptions; + data?: Data; + } + interface TCPSocketOptions<Data = undefined> extends SocketOptions<Data> { + hostname: string; + port: number; + } + + interface UnixSocketOptions<Data = undefined> extends SocketOptions<Data> { + unix: string; + } + + /** + * + * Create a TCP client that connects to a server + * + * @param options The options to use when creating the client + * @param options.socket The socket handler to use + * @param options.data The per-instance data context + * @param options.hostname The hostname to connect to + * @param options.port The port to connect to + * @param options.tls The TLS configuration object + * @param options.unix The unix socket to connect to + * + */ + export function connect<Data = undefined>( + options: TCPSocketOptions<Data>, + ): Promise<TCPSocketListener<typeof options>>; + export function connect<Data = undefined>( + options: UnixSocketOptions<Data>, + ): Promise<UnixSocketListener<typeof options>>; + + /** + * + * Create a TCP server that listens on a port + * + * @param options The options to use when creating the server + * @param options.socket The socket handler to use + * @param options.data The per-instance data context + * @param options.hostname The hostname to connect to + * @param options.port The port to connect to + * @param options.tls The TLS configuration object + * @param options.unix The unix socket to connect to + * + */ + export function listen<Data = undefined>( + options: TCPSocketOptions<Data>, + ): TCPSocketListener<typeof options>; + export function listen<Data = undefined>( + options: UnixSocketOptions<Data>, + ): UnixSocketListener<typeof options>; + + namespace SpawnOptions { + type Readable = + | "inherit" + | "ignore" + | "pipe" + | null + | undefined + | FileBlob + | ArrayBufferView + | number; + + type Writable = + | "inherit" + | "ignore" + | "pipe" + | null + | ReadableStream // supported by stdin + | undefined + | FileBlob + | ArrayBufferView + | Blob + | number + | Response + | Request; + + interface OptionsObject { + /** + * The current working directory of the process + * + * Defaults to `process.cwd()` + */ + cwd?: string; + + /** + * The environment variables of the process + * + * Defaults to `process.env` as it was when the current Bun process launched. + * + * Changes to `process.env` at runtime won't automatically be reflected in the default value. For that, you can pass `process.env` explicitly. + * + */ + env?: Record<string, string>; + + /** + * The standard file descriptors of the process + * - `inherit`: The process will inherit the standard input of the current process + * - `pipe`: The process will have a new pipe for standard input + * - `null`: The process will have no standard input + * - `ArrayBufferView`, `Blob`: The process will read from the buffer + * - `number`: The process will read from the file descriptor + * - `undefined`: The default value + */ + stdio?: [ + SpawnOptions.Writable, + SpawnOptions.Readable, + SpawnOptions.Readable, + ]; + stdin?: SpawnOptions.Writable; + stdout?: SpawnOptions.Readable; + stderr?: SpawnOptions.Readable; + + /** + * Callback that runs when the {@link Subprocess} exits + * + * You can also do `await subprocess.exited` to wait for the process to exit. + * + * @example + * + * ```ts + * const subprocess = spawn({ + * cmd: ["echo", "hello"], + * onExit: (code) => { + * console.log(`Process exited with code ${code}`); + * }, + * }); + * ``` + */ + onExit?: (exitCode: number) => void | Promise<void>; + } + } + + interface SubprocessIO { + readonly stdin?: undefined | number | ReadableStream | FileSink; + readonly stdout?: undefined | number | ReadableStream; + readonly stderr?: undefined | number | ReadableStream; + } + interface Subprocess<T extends SubprocessIO = SubprocessIO> { + readonly stdin: T["stdin"] | undefined; + readonly stdout: T["stdout"] | undefined; + readonly stderr: T["stderr"] | undefined; + + /** + * This returns the same value as {@link Subprocess.stdout} + * + * It exists for compatibility with {@link ReadableStream.pipeThrough} + */ + readonly readable: T["stdout"] | undefined; + + /** + * The process ID of the child process + * @example + * ```ts + * const { pid } = Bun.spawn({ cmd: ["echo", "hello"] }); + * console.log(pid); // 1234 + * ``` + */ + readonly pid: number; + /** + * The exit code of the process + * + * The promise will resolve when the process exits + */ + readonly exited: Promise<number>; + + /** + * Has the process exited? + */ + readonly killed: boolean; + + /** + * Kill the process + * @param exitCode The exitCode to send to the process + */ + kill(exitCode?: number): void; + + /** + * This method will tell Bun to wait for this process to exit after you already + * called `unref()`. + * + * Before shutting down, Bun will wait for all subprocesses to exit by default + */ + ref(): void; + + /** + * Before shutting down, Bun will wait for all subprocesses to exit by default + * + * This method will tell Bun to not wait for this process to exit before shutting down. + */ + unref(): void; + } + + interface SyncSubprocess { + stdout?: Buffer; + stderr?: Buffer; + exitCode: number; + success: boolean; + } + + /** + * Spawn a new process + * + * ```js + * const subprocess = Bun.spawn({ + * cmd: ["echo", "hello"], + * stdout: "pipe", + * }); + * const text = await readableStreamToText(subprocess.stdout); + * console.log(text); // "hello\n" + * ``` + * + * Internally, this uses [posix_spawn(2)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/posix_spawn.2.html) + */ + function spawn<Opts extends SpawnOptions.OptionsObject>( + options: Opts & { + /** + * The command to run + * + * The first argument will be resolved to an absolute executable path. It must be a file, not a directory. + * + * If you explicitly set `PATH` in `env`, that `PATH` will be used to resolve the executable instead of the default `PATH`. + * + * To check if the command exists before running it, use `Bun.which(bin)`. + * + */ + cmd: string[]; // to support dynamically constructed commands + }, + ): Subprocess<OptionsToSubprocessIO<Opts>>; + + /** + * Spawn a new process + * + * ```js + * const {stdout} = Bun.spawn(["echo", "hello"])); + * const text = await readableStreamToText(stdout); + * console.log(text); // "hello\n" + * ``` + * + * Internally, this uses [posix_spawn(2)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/posix_spawn.2.html) + */ + function spawn<Opts extends SpawnOptions.OptionsObject>( + /** + * The command to run + * @example + * ```ts + * const subprocess = Bun.spawn(["echo", "hello"]); + */ + cmds: string[], + options?: Opts, + ): Subprocess<OptionsToSubprocessIO<Opts>>; + type OptionsToSubprocessIO<Opts extends SpawnOptions.OptionsObject> = { + stdin?: Opts["stdin"] extends number + ? number + : Opts["stdin"] extends "pipe" + ? FileSink + : ReadableStream; + stdout?: Opts["stdout"] extends number ? number : ReadableStream; + stderr?: Opts["stderr"] extends number ? number : ReadableStream; + }; + + /** + * Spawn a new process + * + * ```js + * const {stdout} = Bun.spawnSync({ + * cmd: ["echo", "hello"], + * }); + * console.log(stdout.toString()); // "hello\n" + * ``` + * + * Internally, this uses [posix_spawn(2)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/posix_spawn.2.html) + */ + function spawnSync( + options: SpawnOptions.OptionsObject & { + /** + * The command to run + * + * The first argument will be resolved to an absolute executable path. It must be a file, not a directory. + * + * If you explicitly set `PATH` in `env`, that `PATH` will be used to resolve the executable instead of the default `PATH`. + * + * To check if the command exists before running it, use `Bun.which(bin)`. + * + */ + cmd: [string, ...string[]]; + }, + ): SyncSubprocess; + + /** + * Synchronously spawn a new process + * + * ```js + * const {stdout} = Bun.spawnSync(["echo", "hello"])); + * console.log(stdout.toString()); // "hello\n" + * ``` + * + * Internally, this uses [posix_spawn(2)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/posix_spawn.2.html) + */ + function spawnSync( + /** + * The command to run + * @example + * ```ts + * const subprocess = Bun.spawn(["echo", "hello"]); + */ + cmds: [ + /** One command is required */ + string, + /** Additional arguments */ + ...string[], + ], + options?: SpawnOptions.OptionsObject, + ): SyncSubprocess; + + /** + * The current version of Bun + * @example + * "0.2.0" + */ + export const version: string; + + /** + * The git sha at the time the currently-running version of Bun was compiled + * @example + * "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2" + */ + export const revision: string; +} + +type TypedArray = + | Uint8Array + | Int8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array; +type TimeLike = string | number | Date; +type StringOrBuffer = string | TypedArray | ArrayBufferLike; +type PathLike = string | TypedArray | ArrayBufferLike | URL; +type PathOrFileDescriptor = PathLike | number; +type NoParamCallback = VoidFunction; +type BufferEncoding = + | "buffer" + | "utf8" + | "utf-8" + | "ascii" + | "utf16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary" + | "hex" + | "base64" + | "base64url"; + +interface BufferEncodingOption { + encoding?: BufferEncoding; +} + +// declare var Bun: typeof import("bun"); +declare namespace Bun { + export * from "bun"; +} diff --git a/packages/bun-types/bun.lockb b/packages/bun-types/bun.lockb Binary files differnew file mode 100755 index 000000000..cf33f4cab --- /dev/null +++ b/packages/bun-types/bun.lockb diff --git a/packages/bun-types/child_process.d.ts b/packages/bun-types/child_process.d.ts new file mode 100644 index 000000000..639dcaf62 --- /dev/null +++ b/packages/bun-types/child_process.d.ts @@ -0,0 +1,1702 @@ +/** + * The `child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `child_process` module provides a handful of synchronous + * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/child_process.js) + */ +declare module "child_process" { + import { BunSpawnOptions } from "bun"; + 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"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + spawn( + options: BunSpawnOptions & { cmd: string[] }, + ): ChildProcessWithoutNullStreams; + + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel currently exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('assert'); + * const fs = require('fs'); + * const child_process = require('child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ] + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'] + * } + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received + * and buffered in the socket will not be sent to the child. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on + * a `'message'` event instead of `'connection'` and using `server.bind()` instead + * of `server.listen()`. This is, however, currently only supported on Unix + * platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send( + message: Serializable, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + addListener( + event: "message", + listener: (message: Serializable, sendHandle: SendHandle) => void, + ): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit( + event: "close", + code: number | null, + signal: NodeJS.Signals | null, + ): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit( + event: "exit", + code: number | null, + signal: NodeJS.Signals | null, + ): boolean; + emit( + event: "message", + message: Serializable, + sendHandle: SendHandle, + ): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + on( + event: "message", + listener: (message: Serializable, sendHandle: SendHandle) => void, + ): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + once( + event: "message", + listener: (message: Serializable, sendHandle: SendHandle) => void, + ): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependListener( + event: "message", + listener: (message: Serializable, sendHandle: SendHandle) => void, + ): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener( + event: string, + listener: (...args: any[]) => void, + ): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener( + event: "message", + listener: (message: Serializable, sendHandle: SendHandle) => void, + ): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio< + I extends null | Writable, + O extends null | Readable, + E extends null | Readable, + > extends ChildProcess { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = + | IOType + | Array<IOType | "ipc" | Stream | number | null | undefined>; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default true + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions + extends CommonOptions, + MessagingOptions, + Abortable { + argv0?: string | undefined; + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, + * retrieve it with the`process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn( + command: string, + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>, + ): ChildProcessByStdio<Writable, Readable, Readable>; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>, + ): ChildProcessByStdio<Writable, Readable, null>; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>, + ): ChildProcessByStdio<Writable, null, Readable>; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>, + ): ChildProcessByStdio<null, Readable, Readable>; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>, + ): ChildProcessByStdio<Writable, null, null>; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>, + ): ChildProcessByStdio<null, Readable, null>; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>, + ): ChildProcessByStdio<null, null, Readable>; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>, + ): ChildProcessByStdio<null, null, null>; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: ReadonlyArray<string>, + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: ReadonlyArray<string>, + options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>, + ): ChildProcessByStdio<Writable, Readable, Readable>; + function spawn( + command: string, + args: ReadonlyArray<string>, + options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>, + ): ChildProcessByStdio<Writable, Readable, null>; + function spawn( + command: string, + args: ReadonlyArray<string>, + options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>, + ): ChildProcessByStdio<Writable, null, Readable>; + function spawn( + command: string, + args: ReadonlyArray<string>, + options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>, + ): ChildProcessByStdio<null, Readable, Readable>; + function spawn( + command: string, + args: ReadonlyArray<string>, + options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>, + ): ChildProcessByStdio<Writable, null, null>; + function spawn( + command: string, + args: ReadonlyArray<string>, + options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>, + ): ChildProcessByStdio<null, Readable, null>; + function spawn( + command: string, + args: ReadonlyArray<string>, + options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>, + ): ChildProcessByStdio<null, null, Readable>; + function spawn( + command: string, + args: ReadonlyArray<string>, + options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>, + ): ChildProcessByStdio<null, null, null>; + function spawn( + command: string, + args: ReadonlyArray<string>, + options: SpawnOptions, + ): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const exec = util.promisify(require('child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: ( + error: ExecException | null, + stdout: string, + stderr: string, + ) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: { + encoding: "buffer" | null; + } & ExecOptions, + callback?: ( + error: ExecException | null, + stdout: Buffer, + stderr: Buffer, + ) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: ( + error: ExecException | null, + stdout: string, + stderr: string, + ) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: ( + error: ExecException | null, + stdout: string | Buffer, + stderr: string | Buffer, + ) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptions, + callback?: ( + error: ExecException | null, + stdout: string, + stderr: string, + ) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: ( + error: ExecException | null, + stdout: string | Buffer, + stderr: string | Buffer, + ) => void, + ): ChildProcess; + interface PromiseWithChild<T> extends Promise<T> { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: "buffer" | null; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = ExecException & NodeJS.ErrnoException; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const execFile = util.promisify(require('child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + function execFile(file: string): ChildProcess; + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + function execFile( + file: string, + args?: ReadonlyArray<string> | null, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<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: ReadonlyArray<string> | undefined | null, + callback: ( + error: ExecFileException | null, + stdout: string, + stderr: string, + ) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback: ( + error: ExecFileException | null, + stdout: Buffer, + stderr: Buffer, + ) => void, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<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<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<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<string> | undefined | null, + options: ExecFileOptions, + callback: ( + error: ExecFileException | null, + stdout: string, + stderr: string, + ) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | Buffer, + stderr: string | Buffer, + ) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | Buffer, + stderr: string | Buffer, + ) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray<string> | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork( + modulePath: string, + args?: ReadonlyArray<string>, + options?: ForkOptions, + ): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns<T> { + pid: number; + output: Array<T | null>; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns<Buffer>; + function spawnSync( + command: string, + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns<string>; + function spawnSync( + command: string, + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns<Buffer>; + function spawnSync( + command: string, + options?: SpawnSyncOptions, + ): SpawnSyncReturns<string | Buffer>; + function spawnSync( + command: string, + args: ReadonlyArray<string>, + ): SpawnSyncReturns<Buffer>; + function spawnSync( + command: string, + args: ReadonlyArray<string>, + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns<string>; + function spawnSync( + command: string, + args: ReadonlyArray<string>, + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns<Buffer>; + function spawnSync( + command: string, + args?: ReadonlyArray<string>, + options?: SpawnSyncOptions, + ): SpawnSyncReturns<string | Buffer>; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync( + command: string, + options: ExecSyncOptionsWithStringEncoding, + ): string; + function execSync( + command: string, + options: ExecSyncOptionsWithBufferEncoding, + ): Buffer; + function execSync( + command: string, + options?: ExecSyncOptions, + ): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync( + file: string, + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + options: ExecFileSyncOptionsWithBufferEncoding, + ): Buffer; + function execFileSync( + file: string, + options?: ExecFileSyncOptions, + ): string | Buffer; + function execFileSync(file: string, args: ReadonlyArray<string>): Buffer; + function execFileSync( + file: string, + args: ReadonlyArray<string>, + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: ReadonlyArray<string>, + options: ExecFileSyncOptionsWithBufferEncoding, + ): Buffer; + function execFileSync( + file: string, + args?: ReadonlyArray<string>, + options?: ExecFileSyncOptions, + ): string | Buffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/packages/bun-types/constants.d.ts b/packages/bun-types/constants.d.ts new file mode 100644 index 000000000..6a672ad3d --- /dev/null +++ b/packages/bun-types/constants.d.ts @@ -0,0 +1,18 @@ +/** @deprecated 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/packages/bun-types/crypto.d.ts b/packages/bun-types/crypto.d.ts new file mode 100644 index 000000000..288bfe916 --- /dev/null +++ b/packages/bun-types/crypto.d.ts @@ -0,0 +1,3918 @@ +/** + * The `crypto` module provides cryptographic functionality that includes a set of + * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * + * ```js + * const { createHmac } = await import('crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/crypto.js) + */ +declare module "crypto" { + import * as stream from "node:stream"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of [HTML5's `keygen` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen). + * + * `<keygen>` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5`<keygen>` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html) internally. + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): Buffer; + /** + * ```js + * const { Certificate } = await import('crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as <Buffer ...> + * ``` + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * ```js + * import { Buffer } from 'buffer'; + * const { Certificate } = await import('crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const ALPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @param options `stream.transform` options + */ + function createHmac( + algorithm: string, + key: BinaryLike | KeyObject, + options?: stream.TransformOptions, + ): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = + | BinaryToTextEncoding + | CharacterEncoding + | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @param options `stream.transform` options + */ + copy(options?: stream.TransformOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions<T extends KeyFormat> { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { webcrypto, KeyObject } = await import('crypto'); + * const { subtle } = webcrypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256 + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + */ + // static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + */ + asymmetricKeyType?: KeyType | undefined; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + */ + export(options: KeyExportOptions<"pem">): string | Buffer; + export(options?: KeyExportOptions<"der">): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + */ + symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + */ + type: KeyObjectType; + } + type CipherCCMTypes = + | "aes-128-ccm" + | "aes-192-ccm" + | "aes-256-ccm" + | "chacha20-poly1305"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type BinaryLike = string | ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher( + algorithm: CipherCCMTypes, + password: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher( + algorithm: CipherGCMTypes, + password: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher( + algorithm: string, + password: BinaryLike, + options?: stream.TransformOptions, + ): Cipher; + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update( + data: ArrayBufferView, + inputEncoding: undefined, + outputEncoding: Encoding, + ): string; + update( + data: string, + inputEncoding: Encoding | undefined, + outputEncoding: Encoding, + ): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher( + algorithm: CipherCCMTypes, + password: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher( + algorithm: CipherGCMTypes, + password: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher( + algorithm: string, + password: BinaryLike, + options?: stream.TransformOptions, + ): Decipher; + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update( + data: ArrayBufferView, + inputEncoding: undefined, + outputEncoding: Encoding, + ): string; + update( + data: string, + inputEncoding: Encoding | undefined, + outputEncoding: Encoding, + ): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: ArrayBufferView): this; + setAAD( + buffer: ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: ArrayBufferView): this; + setAAD( + buffer: ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipher { + setAuthTag(buffer: ArrayBufferView): this; + setAAD( + buffer: ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey + * } = await import('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync + * } = await import('crypto'); + * + * const key = generateKeySync('hmac', { length: 64 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + */ + function createPrivateKey( + key: PrivateKeyInput | string | Buffer | JsonWebKeyInput, + ): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + */ + function createPublicKey( + key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput, + ): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @param options `stream.Writable` options + */ + function createSign( + algorithm: string, + options?: stream.WritableOptions, + ): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @See crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1' + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + */ + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + ): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @param options `stream.Writable` options + */ + function createVerify( + algorithm: string, + options?: stream.WritableOptions, + ): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman( + primeLength: number, + generator?: number | ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman(prime: ArrayBufferView): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: number | ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createDiffieHellman + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: ArrayBufferView): Buffer; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + ): Buffer; + computeSecret( + otherPublicKey: ArrayBufferView, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `constants`module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + */ + verifyError: number; + } + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The + * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman + * } = await import('crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + */ + function getDiffieHellman(groupName: string): DiffieHellman; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2 + * } = await import('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync + * } = await import('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes( + size: number, + callback: (err: Error | null, buf: Buffer) => void, + ): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes( + size: number, + callback: (err: Error | null, buf: Buffer) => void, + ): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 248. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt + * } = await import('crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt( + max: number, + callback: (err: Error | null, value: number) => void, + ): void; + function randomInt( + min: number, + max: number, + callback: (err: Error | null, value: number) => void, + ): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync<T extends ArrayBufferView>( + buffer: T, + offset?: number, + size?: number, + ): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill<T extends ArrayBufferView>( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill<T extends ArrayBufferView>( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill<T extends ArrayBufferView>( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt + * } = await import('crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync + * } = await import('crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + */ + function scryptSync( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options?: ScryptOptions, + ): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + */ + function publicEncrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: ArrayBufferView, + ): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + */ + function publicDecrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: ArrayBufferView, + ): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + */ + function privateDecrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: ArrayBufferView, + ): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + */ + function privateEncrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: ArrayBufferView, + ): Buffer; + /** + * ```js + * const { + * getCiphers + * } = await import('crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves + * } = await import('crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * ```js + * const { + * getHashes + * } = await import('crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createECDH + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'`format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH + * } = await import('crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys( + encoding: BinaryToTextEncoding, + format?: ECDHKeyFormat, + ): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: ArrayBufferView): Buffer; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + ): Buffer; + computeSecret( + otherPublicKey: ArrayBufferView, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(): Buffer; + getPublicKey( + encoding: BinaryToTextEncoding, + format?: ECDHKeyFormat, + ): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + */ + function createECDH(curveName: string): ECDH; + /** + * This function is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + */ + function timingSafeEqual(a: ArrayBufferView, b: 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"; + interface BasePrivateKeyEncodingOptions<T extends KeyFormat> { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface ED25519KeyPairKeyObjectOptions {} + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface ED448KeyPairKeyObjectOptions {} + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface X25519KeyPairKeyObjectOptions {} + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions< + PubF extends KeyFormat, + PrivF extends KeyFormat, + > { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { + /** + * Name of the curve to use. + */ + namedCurve: string; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions< + PubF extends KeyFormat, + PrivF extends KeyFormat, + > { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions< + PubF extends KeyFormat, + PrivF extends KeyFormat, + > { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions< + PubF extends KeyFormat, + PrivF extends KeyFormat, + > { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions< + PubF extends KeyFormat, + PrivF extends KeyFormat, + > { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult< + T1 extends string | Buffer, + T2 extends string | Buffer, + > { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync + * } = await import('crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult<string, string>; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult<Buffer, Buffer>; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult<string, string>; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult<Buffer, Buffer>; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult<string, string>; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult<Buffer, Buffer>; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult<string, string>; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult<Buffer, Buffer>; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult<string, string>; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult<Buffer, Buffer>; + function generateKeyPairSync( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult<string, string>; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult<Buffer, Buffer>; + function generateKeyPairSync( + type: "ed448", + options?: ED448KeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult<string, string>; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult<Buffer, Buffer>; + function generateKeyPairSync( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult<string, string>; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult<Buffer, Buffer>; + function generateKeyPairSync( + type: "x448", + options?: X448KeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair + * } = await import('crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: ( + err: Error | null, + publicKey: KeyObject, + privateKey: KeyObject, + ) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: ( + err: Error | null, + publicKey: KeyObject, + privateKey: KeyObject, + ) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: ( + err: Error | null, + publicKey: KeyObject, + privateKey: KeyObject, + ) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: ( + err: Error | null, + publicKey: KeyObject, + privateKey: KeyObject, + ) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: ( + err: Error | null, + publicKey: KeyObject, + privateKey: KeyObject, + ) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: ( + err: Error | null, + publicKey: KeyObject, + privateKey: KeyObject, + ) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: ( + err: Error | null, + publicKey: KeyObject, + privateKey: KeyObject, + ) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: ( + err: Error | null, + publicKey: string, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: string, + ) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: ( + err: Error | null, + publicKey: Buffer, + privateKey: Buffer, + ) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: ( + err: Error | null, + publicKey: KeyObject, + privateKey: KeyObject, + ) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + ): Promise<KeyPairKeyObjectResult>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise<KeyPairKeyObjectResult>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + ): Promise<KeyPairKeyObjectResult>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairKeyObjectOptions, + ): Promise<KeyPairKeyObjectResult>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise<KeyPairKeyObjectResult>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed448", + options?: ED448KeyPairKeyObjectOptions, + ): Promise<KeyPairKeyObjectResult>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise<KeyPairKeyObjectResult>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "x448", + options?: X448KeyPairKeyObjectOptions, + ): Promise<KeyPairKeyObjectResult>; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + */ + function sign( + algorithm: string | null | undefined, + data: ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + */ + function verify( + algorithm: string | null | undefined, + data: ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: 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). + */ + function diffieHellman(options: { + privateKey: KeyObject; + publicKey: KeyObject; + }): Buffer; + type CipherMode = + | "cbc" + | "ccm" + | "cfb" + | "ctr" + | "ecb" + | "gcm" + | "ocb" + | "ofb" + | "stream" + | "wrap" + | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo( + nameOrNid: string | number, + options?: CipherInfoOptions, + ): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdf + * } = await import('crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdfSync + * } = await import('crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + /** + * 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. + */ + function randomUUID(options?: RandomUUIDOptions): string; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject: "always" | "never"; + /** + * @default true + */ + wildcards: boolean; + /** + * @default true + */ + partialWildcards: boolean; + /** + * @default false + */ + multiLabelWildcards: boolean; + /** + * @default false + */ + singleLabelSubdomains: boolean; + } + type LargeNumberLike = + | ArrayBufferView + | SharedArrayBuffer + | ArrayBuffer + | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime( + size: number, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync( + size: number, + options: GeneratePrimeOptionsBigInt, + ): bigint; + function generatePrimeSync( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + ): ArrayBuffer; + function generatePrimeSync( + size: number, + options: GeneratePrimeOptions, + ): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime( + value: LargeNumberLike, + callback: (err: Error | null, result: boolean) => void, + ): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync( + candidate: LargeNumberLike, + options?: CheckPrimeOptions, + ): boolean; +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/packages/bun-types/domain.d.ts b/packages/bun-types/domain.d.ts new file mode 100644 index 000000000..e1df3fc7a --- /dev/null +++ b/packages/bun-types/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/domain.js) + */ +declare module "domain" { + import EventEmitter = require("node:events"); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array<EventEmitter | number>; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and lowlevel requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * const domain = require('domain'); + * const fs = require('fs'); + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run<T>(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | number): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | number): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind<T extends Function>(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept<T extends Function>(callback: T): T; + } + function create(): Domain; +} +declare module "node:domain" { + export * from "domain"; +} diff --git a/packages/bun-types/events.d.ts b/packages/bun-types/events.d.ts new file mode 100644 index 000000000..2e9056618 --- /dev/null +++ b/packages/bun-types/events.d.ts @@ -0,0 +1,647 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * const EventEmitter = require('events'); + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/events.js) + */ +declare module "events" { + 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 { + signal?: AbortSignal | undefined; + } + interface EventEmitter { + /** + * Alias for `emitter.on(eventName, listener)`. + */ + addListener( + eventName: string | symbol, + listener: (...args: any[]) => void, + ): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes the specified `listener` from the listener array for the event named`eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and_before_ the last listener finishes execution will + * not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')`listener is removed: + * + * ```js + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + */ + removeListener( + eventName: string | symbol, + listener: (...args: any[]) => void, + ): this; + /** + * Alias for `emitter.removeListener()`. + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + */ + removeAllListeners(event?: string | symbol): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + */ + listeners(eventName: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + */ + rawListeners(eventName: string | symbol): Function[]; + /** + * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * const EventEmitter = require('events'); + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + */ + emit(eventName: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening to the event named `eventName`. + * @param eventName The name of the event being listened for + */ + listenerCount(eventName: string | symbol): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener( + eventName: string | symbol, + listener: (...args: any[]) => void, + ): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the_beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener( + eventName: string | symbol, + listener: (...args: any[]) => void, + ): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * const EventEmitter = require('events'); + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + */ + eventNames(): Array<string | symbol>; + } + /** + * The `EventEmitter` class is defined and exposed by the `events` module: + * + * ```js + * const EventEmitter = require('events'); + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + */ + class EventEmitter { + constructor(options?: EventEmitterOptions); + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * const { once, EventEmitter } = require('events'); + * + * async function run() { + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.log('error happened', err); + * } + * } + * + * run(); + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.log('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + */ + static once( + emitter: NodeEventTarget, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise<any[]>; + static once( + emitter: DOMEventTarget, + eventName: string, + options?: StaticEventEmitterOptions, + ): Promise<any[]>; + /** + * ```js + * const { on, EventEmitter } = require('events'); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * const { on, EventEmitter } = require('events'); + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @param eventName The name of the event being listened for + * @return that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: EventEmitter, + eventName: string, + options?: StaticEventEmitterOptions, + ): AsyncIterableIterator<any>; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * const { EventEmitter, listenerCount } = require('events'); + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount( + emitter: EventEmitter, + eventName: string | symbol, + ): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * const { getEventListeners, EventEmitter } = require('events'); + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * getEventListeners(ee, 'foo'); // [listener] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * getEventListeners(et, 'foo'); // [listener] + * } + * ``` + */ + static getEventListeners( + emitter: DOMEventTarget | EventEmitter, + name: string | symbol, + ): Function[]; + /** + * ```js + * const { + * setMaxListeners, + * EventEmitter + * } = require('events'); + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners( + n?: number, + ...eventTargets: Array<DOMEventTarget | EventEmitter> + ): 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. + * + * Installing a listener using this symbol does not change the behavior once an + * `'error'` event is emitted, therefore the process will still crash if no + * regular `'error'` listener is installed. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + /** + * Sets or gets the default captureRejection value for all emitters. + */ + static captureRejections: boolean; + static defaultMaxListeners: number; + } + import internal = require("node:events"); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/packages/bun-types/ffi.d.ts b/packages/bun-types/ffi.d.ts new file mode 100644 index 000000000..316673b9e --- /dev/null +++ b/packages/bun-types/ffi.d.ts @@ -0,0 +1,813 @@ +/** + * `bun:ffi` lets you efficiently call C functions & FFI functions from JavaScript + * without writing bindings yourself. + * + * ```js + * import {dlopen, CString, ptr} from 'bun:ffi'; + * + * const lib = dlopen('libsqlite3', { + * }); + * ``` + * + * This is powered by just-in-time compiling C wrappers + * that convert JavaScript types to C types and back. Internally, + * bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks + * goes to Fabrice Bellard and TinyCC maintainers for making this possible. + * + */ +declare module "bun:ffi" { + export enum FFIType { + char = 0, + /** + * 8-bit signed integer + * + * Must be a value between -127 and 127 + * + * When passing to a FFI function (C ABI), type coercion is not performed. + * + * In C: + * ```c + * signed char + * char // on x64 & aarch64 macOS + * ``` + * + * In JavaScript: + * ```js + * var num = 0; + * ``` + */ + int8_t = 1, + /** + * 8-bit signed integer + * + * Must be a value between -127 and 127 + * + * When passing to a FFI function (C ABI), type coercion is not performed. + * + * In C: + * ```c + * signed char + * char // on x64 & aarch64 macOS + * ``` + * + * In JavaScript: + * ```js + * var num = 0; + * ``` + */ + i8 = 1, + + /** + * 8-bit unsigned integer + * + * Must be a value between 0 and 255 + * + * When passing to a FFI function (C ABI), type coercion is not performed. + * + * In C: + * ```c + * unsigned char + * ``` + * + * In JavaScript: + * ```js + * var num = 0; + * ``` + */ + uint8_t = 2, + /** + * 8-bit unsigned integer + * + * Must be a value between 0 and 255 + * + * When passing to a FFI function (C ABI), type coercion is not performed. + * + * In C: + * ```c + * unsigned char + * ``` + * + * In JavaScript: + * ```js + * var num = 0; + * ``` + */ + u8 = 2, + + /** + * 16-bit signed integer + * + * Must be a value between -32768 and 32767 + * + * When passing to a FFI function (C ABI), type coercion is not performed. + * + * In C: + * ```c + * in16_t + * short // on arm64 & x64 + * ``` + * + * In JavaScript: + * ```js + * var num = 0; + * ``` + */ + int16_t = 3, + /** + * 16-bit signed integer + * + * Must be a value between -32768 and 32767 + * + * When passing to a FFI function (C ABI), type coercion is not performed. + * + * In C: + * ```c + * in16_t + * short // on arm64 & x64 + * ``` + * + * In JavaScript: + * ```js + * var num = 0; + * ``` + */ + i16 = 3, + + /** + * 16-bit unsigned integer + * + * Must be a value between 0 and 65535, inclusive. + * + * When passing to a FFI function (C ABI), type coercion is not performed. + * + * In C: + * ```c + * uint16_t + * unsigned short // on arm64 & x64 + * ``` + * + * In JavaScript: + * ```js + * var num = 0; + * ``` + */ + uint16_t = 4, + /** + * 16-bit unsigned integer + * + * Must be a value between 0 and 65535, inclusive. + * + * When passing to a FFI function (C ABI), type coercion is not performed. + * + * In C: + * ```c + * uint16_t + * unsigned short // on arm64 & x64 + * ``` + * + * In JavaScript: + * ```js + * var num = 0; + * ``` + */ + u16 = 4, + + /** + * 32-bit signed integer + * + */ + int32_t = 5, + + /** + * 32-bit signed integer + * + * Alias of {@link FFIType.int32_t} + */ + i32 = 5, + /** + * 32-bit signed integer + * + * The same as `int` in C + * + * ```c + * int + * ``` + */ + int = 5, + + /** + * 32-bit unsigned integer + * + * The same as `unsigned int` in C (on x64 & arm64) + * + * C: + * ```c + * unsigned int + * ``` + * JavaScript: + * ```js + * ptr(new Uint32Array(1)) + * ``` + */ + uint32_t = 6, + /** + * 32-bit unsigned integer + * + * Alias of {@link FFIType.uint32_t} + */ + u32 = 6, + + /** + * int64 is a 64-bit signed integer + * + * This is not implemented yet! + */ + int64_t = 7, + /** + * i64 is a 64-bit signed integer + * + * This is not implemented yet! + */ + i64 = 7, + + /** + * 64-bit unsigned integer + * + * This is not implemented yet! + */ + uint64_t = 8, + /** + * 64-bit unsigned integer + * + * This is not implemented yet! + */ + u64 = 8, + + /** + * Doubles are not supported yet! + */ + double = 9, + /** + * Doubles are not supported yet! + */ + f64 = 9, + /** + * Floats are not supported yet! + */ + float = 10, + /** + * Floats are not supported yet! + */ + f32 = 10, + + /** + * Booelan value + * + * Must be `true` or `false`. `0` and `1` type coercion is not supported. + * + * In C, this corresponds to: + * ```c + * bool + * _Bool + * ``` + * + * + */ + bool = 11, + + /** + * Pointer value + * + * See {@link Bun.FFI.ptr} for more information + * + * In C: + * ```c + * void* + * ``` + * + * In JavaScript: + * ```js + * ptr(new Uint8Array(1)) + * ``` + */ + ptr = 12, + /** + * Pointer value + * + * alias of {@link FFIType.ptr} + */ + pointer = 12, + + /** + * void value + * + * void arguments are not supported + * + * void return type is the default return type + * + * In C: + * ```c + * void + * ``` + * + */ + void = 13, + + /** + * When used as a `returns`, this will automatically become a {@link CString}. + * + * When used in `args` it is equivalent to {@link FFIType.pointer} + * + */ + cstring = 14, + + /** + * Attempt to coerce `BigInt` into a `Number` if it fits. This improves performance + * but means you might get a `BigInt` or you might get a `number`. + * + * In C, this always becomes `int64_t` + * + * In JavaScript, this could be number or it could be BigInt, depending on what + * value is passed in. + * + */ + i64_fast = 15, + + /** + * Attempt to coerce `BigInt` into a `Number` if it fits. This improves performance + * but means you might get a `BigInt` or you might get a `number`. + * + * In C, this always becomes `uint64_t` + * + * In JavaScript, this could be number or it could be BigInt, depending on what + * value is passed in. + * + */ + u64_fast = 16, + } + export type FFITypeOrString = + | FFIType + | "char" + | "int8_t" + | "i8" + | "uint8_t" + | "u8" + | "int16_t" + | "i16" + | "uint16_t" + | "u16" + | "int32_t" + | "i32" + | "int" + | "uint32_t" + | "u32" + | "int64_t" + | "i64" + | "uint64_t" + | "u64" + | "double" + | "f64" + | "float" + | "f32" + | "bool" + | "ptr" + | "pointer" + | "void" + | "cstring" + | "function"; + + interface FFIFunction { + /** + * Arguments to a FFI function (C ABI) + * + * Defaults to an empty array, which means no arguments. + * + * To pass a pointer, use "ptr" or "pointer" as the type name. To get a pointer, see {@link ptr}. + * + * @example + * From JavaScript: + * ```js + * const lib = dlopen('add', { + * // FFIType can be used or you can pass string labels. + * args: [FFIType.i32, "i32"], + * returns: "i32", + * }); + * lib.symbols.add(1, 2) + * ``` + * In C: + * ```c + * int add(int a, int b) { + * return a + b; + * } + * ``` + */ + args?: FFITypeOrString[]; + /** + * Return type to a FFI function (C ABI) + * + * Defaults to {@link FFIType.void} + * + * To pass a pointer, use "ptr" or "pointer" as the type name. To get a pointer, see {@link ptr}. + * + * @example + * From JavaScript: + * ```js + * const lib = dlopen('z', { + * version: { + * returns: "ptr", + * } + * }); + * console.log(new CString(lib.symbols.version())); + * ``` + * In C: + * ```c + * char* version() + * { + * return "1.0.0"; + * } + * ``` + */ + returns?: FFITypeOrString; + + /** + * Function pointer to the native function + * + * If provided, instead of using dlsym() to lookup the function, Bun will use this instead. + * This pointer should not be null (0). + * + * This is useful if the library has already been loaded + * or if the module is also using Node-API. + */ + ptr?: number | bigint; + + /** + * Can C/FFI code call this function from a separate thread? + * + * Only supported with {@link JSCallback}. + * + * This does not make the function run in a separate thread. It is still up to the application/library + * to run their code in a separate thread. + * + * By default, {@link JSCallback} calls are not thread-safe. Turning this on + * incurs a small performance penalty for every function call. That small + * performance penalty needs to be less than the performance gain from + * running the function in a separate thread. + * + * @default false + */ + threadsafe?: boolean; + } + + type Symbols = Record<string, FFIFunction>; + + // /** + // * Compile a callback function + // * + // * Returns a function pointer + // * + // */ + // export function callback(ffi: FFIFunction, cb: Function): number; + + export interface Library { + symbols: Record< + string, + CallableFunction & { + /** + * The function without a wrapper + */ + native: CallableFunction; + } + >; + + /** + * `dlclose` the library, unloading the symbols and freeing allocated memory. + * + * Once called, the library is no longer usable. + * + * Calling a function from a library that has been closed is undefined behavior. + */ + close(): void; + } + + /** + * Open a library using `"bun:ffi"` + * + * @param name The name of the library or file path. This will be passed to `dlopen()` + * @param symbols Map of symbols to load where the key is the symbol name and the value is the {@link FFIFunction} + * + * @example + * + * ```js + * import {dlopen} from 'bun:ffi'; + * + * const lib = dlopen("duckdb.dylib", { + * get_version: { + * returns: "cstring", + * args: [], + * }, + * }); + * lib.symbols.get_version(); + * // "1.0.0" + * ``` + * + * This is powered by just-in-time compiling C wrappers + * that convert JavaScript types to C types and back. Internally, + * bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks + * goes to Fabrice Bellard and TinyCC maintainers for making this possible. + * + */ + export function dlopen(name: string, symbols: Symbols): Library; + + /** + * Turn a native library's function pointer into a JavaScript function + * + * Libraries using Node-API & bun:ffi in the same module could use this to skip an extra dlopen() step. + * + * @param fn {@link FFIFunction} declaration. `ptr` is required + * + * @example + * + * ```js + * import {CFunction} from 'bun:ffi'; + * + * const getVersion = new CFunction({ + * returns: "cstring", + * args: [], + * ptr: myNativeLibraryGetVersion, + * }); + * getVersion(); + * getVersion.close(); + * ``` + * + * This is powered by just-in-time compiling C wrappers + * that convert JavaScript types to C types and back. Internally, + * bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks + * goes to Fabrice Bellard and TinyCC maintainers for making this possible. + * + */ + export function CFunction( + fn: FFIFunction & { ptr: number | bigint }, + ): CallableFunction & { + /** + * Free the memory allocated by the wrapping function + */ + close(): void; + }; + + /** + * Link a map of symbols to JavaScript functions + * + * This lets you use native libraries that were already loaded somehow. You usually will want {@link dlopen} instead. + * + * You could use this with Node-API to skip loading a second time. + * + * @param symbols Map of symbols to load where the key is the symbol name and the value is the {@link FFIFunction} + * + * @example + * + * ```js + * import { linkSymbols } from "bun:ffi"; + * + * const [majorPtr, minorPtr, patchPtr] = getVersionPtrs(); + * + * const lib = linkSymbols({ + * // Unlike with dlopen(), the names here can be whatever you want + * getMajor: { + * returns: "cstring", + * args: [], + * + * // Since this doesn't use dlsym(), you have to provide a valid ptr + * // That ptr could be a number or a bigint + * // An invalid pointer will crash your program. + * ptr: majorPtr, + * }, + * getMinor: { + * returns: "cstring", + * args: [], + * ptr: minorPtr, + * }, + * getPatch: { + * returns: "cstring", + * args: [], + * ptr: patchPtr, + * }, + * }); + * + * const [major, minor, patch] = [ + * lib.symbols.getMajor(), + * lib.symbols.getMinor(), + * lib.symbols.getPatch(), + * ]; + * ``` + * + * This is powered by just-in-time compiling C wrappers + * that convert JavaScript types to C types and back. Internally, + * bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks + * goes to Fabrice Bellard and TinyCC maintainers for making this possible. + * + */ + export function linkSymbols(symbols: Symbols): Library; + + /** + * Read a pointer as a {@link Buffer} + * + * If `byteLength` is not provided, the pointer is assumed to be 0-terminated. + * + * @param ptr The memory address to read + * @param byteOffset bytes to skip before reading + * @param byteLength bytes to read + * + * While there are some checks to catch invalid pointers, this is a difficult + * thing to do safely. Passing an invalid pointer can crash the program and + * reading beyond the bounds of the pointer will crash the program or cause + * undefined behavior. Use with care! + * + */ + export function toBuffer( + ptr: number, + byteOffset?: number, + byteLength?: number, + ): Buffer; + + /** + * Read a pointer as an {@link ArrayBuffer} + * + * If `byteLength` is not provided, the pointer is assumed to be 0-terminated. + * + * @param ptr The memory address to read + * @param byteOffset bytes to skip before reading + * @param byteLength bytes to read + * + * While there are some checks to catch invalid pointers, this is a difficult + * thing to do safely. Passing an invalid pointer can crash the program and + * reading beyond the bounds of the pointer will crash the program or cause + * undefined behavior. Use with care! + */ + export function toArrayBuffer( + ptr: number, + byteOffset?: number, + byteLength?: number, + ): ArrayBuffer; + + /** + * Get the pointer backing a {@link TypedArray} or {@link ArrayBuffer} + * + * Use this to pass {@link TypedArray} or {@link ArrayBuffer} to C functions. + * + * This is for use with FFI functions. For performance reasons, FFI will + * not automatically convert typed arrays to C pointers. + * + * @param {TypedArray|ArrayBuffer|DataView} view the typed array or array buffer to get the pointer for + * @param {number} byteOffset optional offset into the view in bytes + * + * @example + * + * From JavaScript: + * ```js + * const array = new Uint8Array(10); + * const rawPtr = ptr(array); + * myFFIFunction(rawPtr); + * ``` + * To C: + * ```c + * void myFFIFunction(char* rawPtr) { + * // Do something with rawPtr + * } + * ``` + * + */ + export function ptr( + view: TypedArray | ArrayBufferLike | DataView, + byteOffset?: number, + ): number; + + /** + * Get a string from a UTF-8 encoded C string + * If `byteLength` is not provided, the string is assumed to be null-terminated. + * + * @example + * ```js + * var ptr = lib.symbols.getVersion(); + * console.log(new CString(ptr)); + * ``` + * + * @example + * ```js + * var ptr = lib.symbols.getVersion(); + * // print the first 4 characters + * console.log(new CString(ptr, 0, 4)); + * ``` + * + * While there are some checks to catch invalid pointers, this is a difficult + * thing to do safely. Passing an invalid pointer can crash the program and + * reading beyond the bounds of the pointer will crash the program or cause + * undefined behavior. Use with care! + */ + + export class CString extends String { + /** + * Get a string from a UTF-8 encoded C string + * If `byteLength` is not provided, the string is assumed to be null-terminated. + * + * @param ptr The pointer to the C string + * @param byteOffset bytes to skip before reading + * @param byteLength bytes to read + * + * + * @example + * ```js + * var ptr = lib.symbols.getVersion(); + * console.log(new CString(ptr)); + * ``` + * + * @example + * ```js + * var ptr = lib.symbols.getVersion(); + * // print the first 4 characters + * console.log(new CString(ptr, 0, 4)); + * ``` + * + * While there are some checks to catch invalid pointers, this is a difficult + * thing to do safely. Passing an invalid pointer can crash the program and + * reading beyond the bounds of the pointer will crash the program or cause + * undefined behavior. Use with care! + */ + constructor(ptr: number, byteOffset?: number, byteLength?: number); + + /** + * The ptr to the C string + * + * This `CString` instance is a clone of the string, so it + * is safe to continue using this instance after the `ptr` has been + * freed. + */ + ptr: number; + byteOffset?: number; + byteLength?: number; + + /** + * Get the {@link ptr} as an `ArrayBuffer` + * + * `null` or empty ptrs returns an `ArrayBuffer` with `byteLength` 0 + */ + get arrayBuffer(): ArrayBuffer; + } + + /** + * Pass a JavaScript function to FFI (Foreign Function Interface) + */ + export class JSCallback { + /** + * Enable a JavaScript callback function to be passed to C with bun:ffi + * + * @param callback The JavaScript function to be called + * @param definition The C function definition + */ + constructor(callback: (...args: any[]) => any, definition: FFIFunction); + + /** + * The pointer to the C function + * + * Becomes `null` once {@link JSCallback.prototype.close} is called + */ + readonly ptr: number | null; + + /** + * Can the callback be called from a different thread? + */ + readonly threadsafe: boolean; + + /** + * Free the memory allocated for the callback + * + * If called multiple times, does nothing after the first call. + */ + close(): void; + } + + /** + * View the generated C code for FFI bindings + * + * You probably won't need this unless there's a bug in the FFI bindings + * generator or you're just curious. + */ + export function viewSource(symbols: Symbols, is_callback?: false): string[]; + export function viewSource(callback: FFIFunction, is_callback: true): string; + + /** + * Platform-specific file extension name for dynamic libraries + * + * "." is not included + * + * @example + * ```js + * "dylib" // macOS + * ``` + * + * @example + * ```js + * "so" // linux + * ``` + */ + export const suffix: string; +} diff --git a/packages/bun-types/fs.d.ts b/packages/bun-types/fs.d.ts new file mode 100644 index 000000000..c4fc1f99c --- /dev/null +++ b/packages/bun-types/fs.d.ts @@ -0,0 +1,3935 @@ +/** + * The `fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'fs'; + * ``` + * + * All file system operations have synchronous and callback + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + */ +declare module "fs" { + import * as stream from "stream"; + import type { SystemError } from "bun"; + + interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + type EncodingOption = + | ObjectEncodingOptions + | BufferEncoding + | undefined + | null; + type OpenMode = number | string; + type Mode = number | string; + type SimlinkType = "symlink" | "junction" | undefined | null; + interface StatsBase<T> { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + interface Stats extends StatsBase<number> {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.0.67 + */ + class Stats {} + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v0.0.67 + */ + class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v0.0.67 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v0.0.67 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v0.0.67 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v0.0.67 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v0.0.67 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v0.0.67 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v0.0.67 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v0.0.67 + */ + name: string; + } + + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.67 + */ + function rename( + oldPath: PathLike, + newPath: PathLike, + callback: NoParamCallback, + ): void; + // namespace rename { + // /** + // * Asynchronous rename(2) - Change the name or location of a file or directory. + // * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + // * URL support is _experimental_. + // * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + // * URL support is _experimental_. + // */ + // function __promisify__(oldPath: PathLike, newPath: PathLike): Promise<void>; + // } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.0.67 + */ + function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.0.67 + * @param [len=0] + */ + function truncate( + path: PathLike, + len: number | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function truncate(path: PathLike, callback: NoParamCallback): void; + // namespace truncate { + // /** + // * Asynchronous truncate(2) - Truncate a file to a specified length. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param len If not specified, defaults to `0`. + // */ + // function __promisify__(path: PathLike, len?: number | null): Promise<void>; + // } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.0.67 + * @param [len=0] + */ + function truncateSync(path: PathLike, len?: number | null): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.0.67 + * @param [len=0] + */ + function ftruncate( + fd: number, + len: number | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + function ftruncate(fd: number, callback: NoParamCallback): void; + // namespace ftruncate { + // /** + // * Asynchronous ftruncate(2) - Truncate a file to a specified length. + // * @param fd A file descriptor. + // * @param len If not specified, defaults to `0`. + // */ + // function __promisify__(fd: number, len?: number | null): Promise<void>; + // } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.0.67 + * @param [len=0] + */ + function ftruncateSync(fd: number, len?: number | null): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.0.67 + */ + function chown( + path: PathLike, + uid: number, + gid: number, + callback: NoParamCallback, + ): void; + // namespace chown { + // /** + // * Asynchronous chown(2) - Change ownership of a file. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // */ + // function __promisify__( + // path: PathLike, + // uid: number, + // gid: number + // ): Promise<void>; + // } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.0.67 + */ + function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.0.67 + */ + function fchown( + fd: number, + uid: number, + gid: number, + callback: NoParamCallback, + ): void; + // namespace fchown { + // /** + // * Asynchronous fchown(2) - Change ownership of a file. + // * @param fd A file descriptor. + // */ + // function __promisify__(fd: number, uid: number, gid: number): Promise<void>; + // } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.0.67 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + function lchown( + path: PathLike, + uid: number, + gid: number, + callback: NoParamCallback, + ): void; + // namespace lchown { + // /** + // * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // */ + // function __promisify__( + // path: PathLike, + // uid: number, + // gid: number + // ): Promise<void>; + // } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v0.0.67 + */ + function lutimes( + path: PathLike, + atime: TimeLike, + mtime: TimeLike, + callback: NoParamCallback, + ): void; + // namespace lutimes { + // /** + // * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + // * with the difference that if the path refers to a symbolic link, then the link is not + // * dereferenced: instead, the timestamps of the symbolic link itself are changed. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param atime The last access time. If a string is provided, it will be coerced to number. + // * @param mtime The last modified time. If a string is provided, it will be coerced to number. + // */ + // function __promisify__( + // path: PathLike, + // atime: TimeLike, + // mtime: TimeLike + // ): Promise<void>; + // } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v0.0.67 + */ + function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.0.67 + */ + function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + // namespace chmod { + // /** + // * Asynchronous chmod(2) - Change permissions of a file. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + // */ + // function __promisify__(path: PathLike, mode: Mode): Promise<void>; + // } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.0.67 + */ + function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.0.67 + */ + function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + // namespace fchmod { + // /** + // * Asynchronous fchmod(2) - Change permissions of a file. + // * @param fd A file descriptor. + // * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + // */ + // function __promisify__(fd: number, mode: Mode): Promise<void>; + // } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.0.67 + */ + function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + // /** @deprecated */ + // namespace lchmod { + // /** + // * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + // */ + // function __promisify__(path: PathLike, mode: Mode): Promise<void>; + // } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.67 + */ + function stat( + path: PathLike, + callback: (err: SystemError | null, stats: Stats) => void, + ): void; + function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: SystemError | null, stats: Stats) => void, + ): void; + function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: SystemError | null, stats: BigIntStats) => void, + ): void; + function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: SystemError | null, stats: Stats | BigIntStats) => void, + ): void; + // namespace stat { + // /** + // * Asynchronous stat(2) - Get file status. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // */ + // function __promisify__( + // path: PathLike, + // options?: StatOptions & { + // bigint?: false | undefined; + // } + // ): Promise<Stats>; + // function __promisify__( + // path: PathLike, + // options: StatOptions & { + // bigint: true; + // } + // ): Promise<BigIntStats>; + // function __promisify__( + // path: PathLike, + // options?: StatOptions + // ): Promise<Stats | BigIntStats>; + // } + // tslint:disable-next-line:unified-signatures + interface StatSyncFn extends Function { + // tslint:disable-next-line:unified-signatures + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + // tslint:disable-next-line:unified-signatures + ( + path: PathLike, + // tslint:disable-next-line:unified-signatures + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): + | Stats + | BigIntStats + | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + var statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.0.67 + */ + function fstat( + fd: number, + callback: (err: SystemError | null, stats: Stats) => void, + ): void; + function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: SystemError | null, stats: Stats) => void, + ): void; + function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: SystemError | null, stats: BigIntStats) => void, + ): void; + function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: SystemError | null, stats: Stats | BigIntStats) => void, + ): void; + // namespace fstat { + // /** + // * Asynchronous fstat(2) - Get file status. + // * @param fd A file descriptor. + // */ + // function __promisify__( + // fd: number, + // options?: StatOptions & { + // bigint?: false | undefined; + // } + // ): Promise<Stats>; + // function __promisify__( + // fd: number, + // options: StatOptions & { + // bigint: true; + // } + // ): Promise<BigIntStats>; + // function __promisify__( + // fd: number, + // options?: StatOptions + // ): Promise<Stats | BigIntStats>; + // } + /** + * 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.0.67 + */ + function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.0.67 + */ + function lstat( + path: PathLike, + callback: (err: SystemError | null, stats: Stats) => void, + ): void; + function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: SystemError | null, stats: Stats) => void, + ): void; + function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: SystemError | null, stats: BigIntStats) => void, + ): void; + function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: SystemError | null, stats: Stats | BigIntStats) => void, + ): void; + // namespace lstat { + // /** + // * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // */ + // function __promisify__( + // path: PathLike, + // options?: StatOptions & { + // bigint?: false | undefined; + // } + // ): Promise<Stats>; + // function __promisify__( + // path: PathLike, + // options: StatOptions & { + // bigint: true; + // } + // ): Promise<BigIntStats>; + // function __promisify__( + // path: PathLike, + // options?: StatOptions + // ): Promise<Stats | BigIntStats>; + // } + /** + * 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. + */ + var lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.0.67 + */ + function link( + existingPath: PathLike, + newPath: PathLike, + callback: NoParamCallback, + ): void; + // namespace link { + // /** + // * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + // * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + // */ + // function __promisify__( + // existingPath: PathLike, + // newPath: PathLike + // ): Promise<void>; + // } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.0.67 + */ + function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If + * the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from 'fs'; + * + * symlink('./mew', './example/mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` in the `example` which points + * to `mew` in the same directory: + * + * ```bash + * $ tree example/ + * example/ + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.0.67 + */ + function symlink( + target: PathLike, + path: PathLike, + type: SimlinkType, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + function symlink( + target: PathLike, + path: PathLike, + callback: NoParamCallback, + ): void; + // namespace symlink { + // /** + // * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + // * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + // * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + // * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + // * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + // */ + // function __promisify__( + // target: PathLike, + // path: PathLike, + // type?: string | null + // ): Promise<void>; + // type Type = "dir" | "file" | "junction"; + // } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.0.67 + */ + function symlinkSync( + target: PathLike, + path: PathLike, + type?: SimlinkType, + ): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.0.67 + */ + function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: SystemError | 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. + */ + // tslint:disable-next-line:unified-signatures + function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: SystemError | 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. + */ + // tslint:disable-next-line:unified-signatures + function readlink( + path: PathLike, + options: EncodingOption, + // tslint:disable-next-line:unified-signatures + callback: (err: SystemError | 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. + */ + // tslint:disable-next-line:unified-signatures + function readlink( + path: PathLike, + callback: (err: SystemError | null, linkString: string) => void, + ): void; + // namespace readlink { + // /** + // * Asynchronous readlink(2) - read value of a symbolic link. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // path: PathLike, + // options?: EncodingOption + // ): Promise<string>; + // /** + // * Asynchronous readlink(2) - read value of a symbolic link. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // path: PathLike, + // options: BufferEncodingOption + // ): Promise<Buffer>; + // /** + // * Asynchronous readlink(2) - read value of a symbolic link. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // path: PathLike, + // options?: EncodingOption + // ): Promise<string | Buffer>; + // } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.0.67 + */ + function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync( + path: PathLike, + options?: EncodingOption, + ): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.0.67 + */ + function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: SystemError | 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. + */ + // tslint:disable-next-line:unified-signatures + function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: SystemError | 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. + */ + // tslint:disable-next-line:unified-signatures + function realpath( + path: PathLike, + options: EncodingOption, + // tslint:disable-next-line:unified-signatures + callback: (err: SystemError | 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. + */ + // tslint:disable-next-line:unified-signatures + function realpath( + path: PathLike, + callback: (err: SystemError | null, resolvedPath: string) => void, + ): void; + // namespace realpath { + // /** + // * Asynchronous realpath(3) - return the canonicalized absolute pathname. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // path: PathLike, + // options?: EncodingOption + // ): Promise<string>; + // /** + // * Asynchronous realpath(3) - return the canonicalized absolute pathname. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // path: PathLike, + // options: BufferEncodingOption + // ): Promise<Buffer>; + // /** + // * Asynchronous realpath(3) - return the canonicalized absolute pathname. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // path: PathLike, + // options?: EncodingOption + // ): Promise<string | Buffer>; + // /** + // * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + // * + // * The `callback` gets two arguments `(err, resolvedPath)`. + // * + // * Only paths that can be converted to UTF8 strings are supported. + // * + // * The optional `options` argument can be a string specifying an encoding, or an + // * object with an `encoding` property specifying the character encoding to use for + // * the path passed to the callback. If the `encoding` is set to `'buffer'`, + // * the path returned will be passed as a `Buffer` object. + // * + // * On Linux, when Node.js is linked against musl libc, the procfs file system must + // * be mounted on `/proc` in order for this function to work. Glibc does not have + // * this restriction. + // * @since v0.0.67 + // */ + // function native( + // path: PathLike, + // options: EncodingOption, + // // tslint:disable-next-line:unified-signatures + // callback: (err: SystemError | null, resolvedPath: string) => void + // ): void; + // function native( + // path: PathLike, + // options: BufferEncodingOption, + // // tslint:disable-next-line:unified-signatures + // callback: (err: SystemError | null, resolvedPath: Buffer) => void + // ): void; + // function native( + // path: PathLike, + // options: EncodingOption, + // // tslint:disable-next-line:unified-signatures + // callback: (err: SystemError | null, resolvedPath: string | Buffer) => void + // ): void; + // function native( + // path: PathLike, + // callback: (err: SystemError | null, resolvedPath: string) => void + // ): void; + // } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.0.67 + */ + function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync( + path: PathLike, + options?: EncodingOption, + ): string | Buffer; + namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.67 + */ + function unlink(path: PathLike, callback: NoParamCallback): void; + // namespace unlink { + // /** + // * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // */ + // function __promisify__(path: PathLike): Promise<void>; + // } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.0.67 + */ + function unlinkSync(path: PathLike): void; + interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.67 + */ + function rmdir(path: PathLike, callback: NoParamCallback): void; + function rmdir( + path: PathLike, + options: RmDirOptions, + callback: NoParamCallback, + ): void; + // namespace rmdir { + // /** + // * Asynchronous rmdir(2) - delete a directory. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // */ + // function __promisify__( + // path: PathLike, + // options?: RmDirOptions + // ): Promise<void>; + // } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.0.67 + */ + function rmdirSync(path: PathLike, options?: RmDirOptions): void; + interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm( + path: PathLike, + options: RmOptions, + callback: NoParamCallback, + ): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise<void>; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. + * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.0.67 + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: SystemError | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + // tslint:disable-next-line:unified-signatures + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: SystemError | 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. + */ + function mkdir(path: PathLike, callback: NoParamCallback): void; + // namespace mkdir { + // /** + // * Asynchronous mkdir(2) - create a directory. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + // * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + // */ + // function __promisify__( + // path: PathLike, + // options: MakeDirectoryOptions & { + // recursive: true; + // } + // ): Promise<string | undefined>; + // /** + // * Asynchronous mkdir(2) - create a directory. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + // * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + // */ + // function __promisify__( + // path: PathLike, + // options?: + // | Mode + // | (MakeDirectoryOptions & { + // recursive?: false | undefined; + // }) + // | null + // ): Promise<void>; + // /** + // * Asynchronous mkdir(2) - create a directory. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + // * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + // */ + // function __promisify__( + // path: PathLike, + // options?: Mode | MakeDirectoryOptions | null + // ): Promise<string | undefined>; + // } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.0.67 + */ + function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs'; + * + * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from 'fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v0.0.67 + */ + function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: SystemError | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp( + prefix: string, + options: + | "buffer" + | { + encoding: "buffer"; + }, + callback: (err: SystemError | 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. + */ + function mkdtemp( + prefix: string, + options: EncodingOption, + // tslint:disable-next-line:unified-signatures + callback: (err: SystemError | 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. + */ + // tslint:disable-next-line:unified-signatures + function mkdtemp( + prefix: string, + callback: (err: SystemError | null, folder: string) => void, + ): void; + // namespace mkdtemp { + // /** + // * Asynchronously creates a unique temporary directory. + // * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // prefix: string, + // options?: EncodingOption + // ): Promise<string>; + // /** + // * Asynchronously creates a unique temporary directory. + // * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // prefix: string, + // options: BufferEncodingOption + // ): Promise<Buffer>; + // /** + // * Asynchronously creates a unique temporary directory. + // * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // prefix: string, + // options?: EncodingOption + // ): Promise<string | Buffer>; + // } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v0.0.67 + */ + function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync( + prefix: string, + options?: EncodingOption, + ): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.0.67 + */ + function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: SystemError | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + } + | "buffer", + callback: (err: SystemError | null, files: Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: SystemError | 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. + */ + function readdir( + path: PathLike, + callback: (err: SystemError | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + }, + callback: (err: SystemError | null, files: Dirent[]) => void, + ): void; + // namespace readdir { + // /** + // * Asynchronous readdir(3) - read a directory. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // path: PathLike, + // options?: + // | { + // encoding: BufferEncoding | null; + // withFileTypes?: false | undefined; + // } + // | BufferEncoding + // | null + // ): Promise<string[]>; + // /** + // * Asynchronous readdir(3) - read a directory. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // path: PathLike, + // options: + // | "buffer" + // | { + // encoding: "buffer"; + // withFileTypes?: false | undefined; + // } + // ): Promise<Buffer[]>; + // /** + // * Asynchronous readdir(3) - read a directory. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + // */ + // function __promisify__( + // path: PathLike, + // options?: + // | (ObjectEncodingOptions & { + // withFileTypes?: false | undefined; + // }) + // | BufferEncoding + // | null + // ): Promise<string[] | Buffer[]>; + // /** + // * Asynchronous readdir(3) - read a directory. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + // */ + // function __promisify__( + // path: PathLike, + // options: ObjectEncodingOptions & { + // withFileTypes: true; + // } + // ): Promise<Dirent[]>; + // } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.0.67 + */ + function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + } + | "buffer", + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null, + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.67 + */ + function close(fd: number, callback?: NoParamCallback): void; + // namespace close { + // /** + // * Asynchronous close(2) - close a file descriptor. + // * @param fd A file descriptor. + // */ + // function __promisify__(fd: number): Promise<void>; + // } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.67 + */ + function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.67 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + function open( + path: PathLike, + flags: OpenMode, + mode: Mode | undefined | null, + callback: (err: SystemError | 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. + */ + function open( + path: PathLike, + flags: OpenMode, + callback: (err: SystemError | null, fd: number) => void, + ): void; + // namespace open { + // /** + // * Asynchronous open(2) - open and possibly create a file. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + // */ + // function __promisify__( + // path: PathLike, + // flags: OpenMode, + // mode?: Mode | null + // ): Promise<number>; + // } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.0.67 + * @param [flags='r'] + * @param [mode=0o666] + */ + function openSync( + path: PathLike, + flags: OpenMode, + mode?: Mode | null, + ): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v0.0.67 + */ + function utimes( + path: PathLike, + atime: TimeLike, + mtime: TimeLike, + callback: NoParamCallback, + ): void; + // namespace utimes { + // /** + // * Asynchronously change file timestamps of the file referenced by the supplied path. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * @param atime The last access time. If a string is provided, it will be coerced to number. + // * @param mtime The last modified time. If a string is provided, it will be coerced to number. + // */ + // function __promisify__( + // path: PathLike, + // atime: TimeLike, + // mtime: TimeLike + // ): Promise<void>; + // } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.0.67 + */ + function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.0.67 + */ + function futimes( + fd: number, + atime: TimeLike, + mtime: TimeLike, + callback: NoParamCallback, + ): void; + // namespace futimes { + // /** + // * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + // * @param fd A file descriptor. + // * @param atime The last access time. If a string is provided, it will be coerced to number. + // * @param mtime The last modified time. If a string is provided, it will be coerced to number. + // */ + // function __promisify__( + // fd: number, + // atime: TimeLike, + // mtime: TimeLike + // ): Promise<void>; + // } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.0.67 + */ + function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.0.67 + */ + function fsync(fd: number, callback: NoParamCallback): void; + // namespace fsync { + // /** + // * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + // * @param fd A file descriptor. + // */ + // function __promisify__(fd: number): Promise<void>; + // } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.0.67 + */ + 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. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.67 + */ + function write<TBuffer extends ArrayBufferView>( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: ( + err: SystemError | null, + written: number, + buffer: TBuffer, + ) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + function write<TBuffer extends ArrayBufferView>( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: ( + err: SystemError | null, + written: number, + buffer: TBuffer, + ) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + function write<TBuffer extends ArrayBufferView>( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: ( + err: SystemError | null, + written: number, + buffer: TBuffer, + ) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + function write<TBuffer extends ArrayBufferView>( + fd: number, + buffer: TBuffer, + callback: ( + err: SystemError | null, + written: number, + buffer: TBuffer, + ) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: SystemError | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: SystemError | 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. + */ + function write( + fd: number, + string: string, + callback: (err: SystemError | null, written: number, str: string) => void, + ): void; + // namespace write { + // /** + // * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + // * @param fd A file descriptor. + // * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + // * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + // * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + // */ + // function __promisify__<TBuffer extends ArrayBufferView>( + // fd: number, + // buffer?: TBuffer, + // offset?: number, + // length?: number, + // position?: number | null + // ): Promise<{ + // bytesWritten: number; + // buffer: TBuffer; + // }>; + // /** + // * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + // * @param fd A file descriptor. + // * @param string A string to write. + // * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + // * @param encoding The expected string encoding. + // */ + // function __promisify__( + // fd: number, + // string: string, + // position?: number | null, + // encoding?: BufferEncoding | null + // ): Promise<{ + // bytesWritten: number; + // buffer: string; + // }>; + // } + /** + * 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.0.67 + * @return The number of bytes written. + */ + function writeSync( + fd: number, + buffer: ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + type ReadPosition = number | bigint; + interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + interface ReadAsyncOptions<TBuffer extends ArrayBufferView> + extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.67 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + function read<TBuffer extends ArrayBufferView>( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: ( + err: SystemError | 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 v0.0.67 + */ + function read<TBuffer extends ArrayBufferView>( + fd: number, + options: ReadAsyncOptions<TBuffer>, + callback: ( + err: SystemError | null, + bytesRead: number, + buffer: TBuffer, + ) => void, + ): void; + function read( + fd: number, + callback: ( + err: SystemError | null, + bytesRead: number, + buffer: ArrayBufferView, + ) => void, + ): void; + // namespace read { + // /** + // * @param fd A file descriptor. + // * @param buffer The buffer that the data will be written to. + // * @param offset The offset in the buffer at which to start writing. + // * @param length The number of bytes to read. + // * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + // */ + // function __promisify__<TBuffer extends ArrayBufferView>( + // fd: number, + // buffer: TBuffer, + // offset: number, + // length: number, + // position: number | null + // ): Promise<{ + // bytesRead: number; + // buffer: TBuffer; + // }>; + // function __promisify__<TBuffer extends ArrayBufferView>( + // fd: number, + // options: ReadAsyncOptions<TBuffer> + // ): Promise<{ + // bytesRead: number; + // buffer: TBuffer; + // }>; + // function __promisify__(fd: number): Promise<{ + // bytesRead: number; + // buffer: ArrayBufferView; + // }>; + // } + + // TODO: Add AbortSignal support + // tslint:disable-next-line:no-empty-interface + interface Abortable {} + + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.0.67 + */ + function readSync( + fd: number, + buffer: 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. + */ + function readSync( + fd: number, + buffer: ArrayBufferView, + opts?: ReadSyncOptions, + ): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'fs'; + * + * // macOS, Linux, and Windows + * readFile('<directory>', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read <directory>] + * }); + * + * // FreeBSD + * readFile('<directory>', (err, data) => { + * // => null, <data> + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.0.67 + * @param path filename or file descriptor + */ + function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: SystemError | null, data: Buffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: SystemError | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: SystemError | 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. + */ + function readFile( + path: PathOrFileDescriptor, + callback: (err: SystemError | null, data: Buffer) => void, + ): void; + // namespace readFile { + // /** + // * Asynchronously reads the entire contents of a file. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + // * @param options An object that may contain an optional flag. + // * If a flag is not provided, it defaults to `'r'`. + // */ + // function __promisify__( + // path: PathOrFileDescriptor, + // options?: { + // encoding?: null | undefined; + // flag?: string | undefined; + // } | null + // ): Promise<Buffer>; + // /** + // * Asynchronously reads the entire contents of a file. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * URL support is _experimental_. + // * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + // * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + // * If a flag is not provided, it defaults to `'r'`. + // */ + // function __promisify__( + // path: PathOrFileDescriptor, + // options: + // | { + // encoding: BufferEncoding; + // flag?: string | undefined; + // } + // | BufferEncoding + // ): Promise<string>; + // /** + // * Asynchronously reads the entire contents of a file. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * URL support is _experimental_. + // * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + // * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + // * If a flag is not provided, it defaults to `'r'`. + // */ + // function __promisify__( + // path: PathOrFileDescriptor, + // options?: + // | (ObjectEncodingOptions & { + // flag?: string | undefined; + // }) + // | BufferEncoding + // | null + // ): Promise<string | Buffer>; + // } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'fs'; + * + * // macOS, Linux, and Windows + * readFileSync('<directory>'); + * // => [Error: EISDIR: illegal operation on a directory, read <directory>] + * + * // FreeBSD + * readFileSync('<directory>'); // => <data> + * ``` + * @since v0.0.67 + * @param path filename or file descriptor + */ + function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Buffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | Buffer; + type WriteFileOptions = + | (ObjectEncodingOptions & + Abortable & { + mode?: Mode | undefined; + flag?: string | undefined; + }) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * 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'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.0.67 + * @param file filename or file descriptor + */ + function writeFile( + file: PathOrFileDescriptor, + data: string | ArrayBufferView | ArrayBufferLike, + 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. + */ + function writeFile( + path: PathOrFileDescriptor, + data: string | ArrayBufferView | ArrayBufferLike, + callback: NoParamCallback, + ): void; + // namespace writeFile { + // /** + // * Asynchronously writes data to a file, replacing the file if it already exists. + // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + // * URL support is _experimental_. + // * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + // * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + // * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + // * If `encoding` is not supplied, the default of `'utf8'` is used. + // * If `mode` is not supplied, the default of `0o666` is used. + // * If `mode` is a string, it is parsed as an octal integer. + // * If `flag` is not supplied, the default of `'w'` is used. + // */ + // function __promisify__( + // path: PathOrFileDescriptor, + // data: string | ArrayBufferView, + // options?: WriteFileOptions + // ): Promise<void>; + // } + /** + * 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 + * this API: {@link writeFile}. + * @since v0.0.67 + * @param file filename or file descriptor + */ + function writeFileSync( + file: PathOrFileDescriptor, + data: string | ArrayBufferView | ArrayBufferLike, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.0.67 + * @param path filename or file descriptor + */ + function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function appendFile( + file: PathOrFileDescriptor, + data: string | Uint8Array, + callback: NoParamCallback, + ): void; + // namespace appendFile { + // /** + // * Asynchronously append data to a file, creating the file if it does not exist. + // * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + // * URL support is _experimental_. + // * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + // * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + // * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + // * If `encoding` is not supplied, the default of `'utf8'` is used. + // * If `mode` is not supplied, the default of `0o666` is used. + // * If `mode` is a string, it is parsed as an octal integer. + // * If `flag` is not supplied, the default of `'a'` is used. + // */ + // function __promisify__( + // file: PathOrFileDescriptor, + // data: string | Uint8Array, + // options?: WriteFileOptions + // ): Promise<void>; + // } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.0.67 + * @param path filename or file descriptor + */ + function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won’t be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.67 + */ + function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.0.67 + */ + function existsSync(path: PathLike): boolean; + namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + var F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + var R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + var W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + var X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + var COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + var COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + var COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + var O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + var O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + var O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + var O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + var O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + var O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + var O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + var O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + var O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + var O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + var O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + var O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + var O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + var O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + var O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + var O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + var S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + var S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + var S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + var S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + var S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + var S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + var S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + var S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + var S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + var S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + var S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + var S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + var S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + var S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + var S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + var S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + var S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + var S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + var S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + var S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + var UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. 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`). + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file 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`); + * } + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.0.67 + * @param [mode=fs.constants.F_OK] + */ + function access( + path: PathLike, + mode: number | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + function access(path: PathLike, callback: NoParamCallback): void; + // namespace access { + // /** + // * Asynchronously tests a user's permissions for the file specified by path. + // * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + // * URL support is _experimental_. + // */ + // function __promisify__(path: PathLike, mode?: number): Promise<void>; + // } + /** + * 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`). + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.0.67 + * @param [mode=fs.constants.F_OK] + */ + function accessSync(path: PathLike, mode?: number): void; + + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | undefined; // | promises.FileHandle; + mode?: number | undefined; + autoClose?: boolean | undefined; + /** + * @default false + */ + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + } + interface ReadStreamOptions extends StreamOptions { + end?: number | undefined; + } + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream( + path: PathLike, + options?: BufferEncoding | ReadStreamOptions, + ): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream( + path: PathLike, + options?: BufferEncoding | StreamOptions, + ): WriteStream; + + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.0.67 + */ + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: ErrnoException | null) => void): Promise<void>; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener( + event: "data", + listener: (chunk: Buffer | string) => void, + ): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "ready", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "ready", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + // prependListener(event: 'close', listener: () => void): this; + // prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + // prependListener(event: 'end', listener: () => void): this; + // prependListener(event: 'error', listener: (err: Error) => void): this; + // prependListener(event: 'open', listener: (fd: number) => void): this; + // prependListener(event: 'pause', listener: () => void): this; + // prependListener(event: 'readable', listener: () => void): this; + // prependListener(event: 'ready', listener: () => void): this; + // prependListener(event: 'resume', listener: () => void): this; + // prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + // prependOnceListener(event: 'close', listener: () => void): this; + // prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + // prependOnceListener(event: 'end', listener: () => void): this; + // prependOnceListener(event: 'error', listener: (err: Error) => void): this; + // prependOnceListener(event: 'open', listener: (fd: number) => void): this; + // prependOnceListener(event: 'pause', listener: () => void): this; + // prependOnceListener(event: 'readable', listener: () => void): this; + // prependOnceListener(event: 'ready', listener: () => void): this; + // prependOnceListener(event: 'resume', listener: () => void): this; + // prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: ErrnoException | null) => void): Promise<void>; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + // pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "ready", listener: () => void): this; + addListener( + event: "unpipe", + listener: (src: stream.Readable) => void, + ): this; + addListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "ready", listener: () => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + // prependListener(event: 'close', listener: () => void): this; + // prependListener(event: 'drain', listener: () => void): this; + // prependListener(event: 'error', listener: (err: Error) => void): this; + // prependListener(event: 'finish', listener: () => void): this; + // prependListener(event: 'open', listener: (fd: number) => void): this; + // prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + // prependListener(event: 'ready', listener: () => void): this; + // prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + // prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + // prependOnceListener(event: 'close', listener: () => void): this; + // prependOnceListener(event: 'drain', listener: () => void): this; + // prependOnceListener(event: 'error', listener: (err: Error) => void): this; + // prependOnceListener(event: 'finish', listener: () => void): this; + // prependOnceListener(event: 'open', listener: (fd: number) => void): this; + // prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + // prependOnceListener(event: 'ready', listener: () => void): this; + // prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + // prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + function fdatasync(fd: number, callback: NoParamCallback): void; + // namespace fdatasync { + // /** + // * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + // * @param fd A file descriptor. + // */ + // function __promisify__(fd: number): Promise<void>; + // } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.0.67 + */ + function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v0.0.67 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + function copyFile( + src: PathLike, + dest: PathLike, + callback: NoParamCallback, + ): void; + function copyFile( + src: PathLike, + dest: PathLike, + mode: number, + callback: NoParamCallback, + ): void; + // namespace copyFile { + // function __promisify__( + // src: PathLike, + // dst: PathLike, + // mode?: number + // ): Promise<void>; + // } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v0.0.67 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.67 + */ + function writev( + fd: number, + buffers: ReadonlyArray<ArrayBufferView>, + cb: ( + err: SystemError | null, + bytesWritten: number, + buffers: ArrayBufferView[], + ) => void, + ): void; + function writev( + fd: number, + buffers: ReadonlyArray<ArrayBufferView>, + position: number, + cb: ( + err: SystemError | null, + bytesWritten: number, + buffers: ArrayBufferView[], + ) => void, + ): void; + interface WriteVResult { + bytesWritten: number; + buffers: ArrayBufferView[]; + } + // namespace writev { + // function __promisify__( + // fd: number, + // buffers: ReadonlyArray<ArrayBufferView>, + // position?: number + // ): Promise<WriteVResult>; + // } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v0.0.67 + * @return The number of bytes written. + */ + function writevSync( + fd: number, + buffers: ReadonlyArray<ArrayBufferView>, + position?: number, + ): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v0.0.67 + */ + function readv( + fd: number, + buffers: ReadonlyArray<ArrayBufferView>, + cb: ( + err: SystemError | null, + bytesRead: number, + buffers: ArrayBufferView[], + ) => void, + ): void; + function readv( + fd: number, + buffers: ReadonlyArray<ArrayBufferView>, + position: number, + cb: ( + err: SystemError | null, + bytesRead: number, + buffers: ArrayBufferView[], + ) => void, + ): void; + interface ReadVResult { + bytesRead: number; + buffers: ArrayBufferView[]; + } + // namespace readv { + // function __promisify__( + // fd: number, + // buffers: ReadonlyArray<ArrayBufferView>, + // position?: number + // ): Promise<ReadVResult>; + // } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v0.0.67 + * @return The number of bytes read. + */ + function readvSync( + fd: number, + buffers: ReadonlyArray<ArrayBufferView>, + position?: number, + ): number; + interface OpenDirOptions { + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + } + + interface BigIntStats extends StatsBase<bigint> { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + interface BigIntOptions { + bigint: true; + } + interface StatOptions { + bigint?: boolean | undefined; + } + interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptions { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + } +} + +declare module "node:fs" { + import * as fs from "fs"; + export = fs; +} diff --git a/packages/bun-types/fs/promises.d.ts b/packages/bun-types/fs/promises.d.ts new file mode 100644 index 000000000..3749ca058 --- /dev/null +++ b/packages/bun-types/fs/promises.d.ts @@ -0,0 +1,677 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Bun threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + */ +declare module "fs/promises" { + import { + Stats, + BigIntStats, + StatOptions, + MakeDirectoryOptions, + Dirent, + ObjectEncodingOptions, + OpenMode, + Mode, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + CopyOptions, + EncodingOption, + WriteFileOptions, + SimlinkType, + Abortable, + } from "node:fs"; + + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult<T extends ArrayBufferView> { + bytesRead: number; + buffer: T; + } + interface FileReadOptions<T extends ArrayBufferView = Buffer> { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: number | null; + } + /** + * Tests a user"s permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is resolved with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access } from "fs/promises"; + * import { constants } from "fs"; + * + * try { + * await access("/etc/passwd", constants.R_OK | constants.W_OK); + * console.log("can access"); + * } catch { + * console.error("cannot access"); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file"s state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v0.0.67 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise<void>; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { constants } from "fs"; + * import { copyFile } from "fs/promises"; + * + * try { + * await copyFile("source.txt", "destination.txt"); + * console.log("source.txt was copied to destination.txt"); + * } catch { + * console.log("The file could not be copied"); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile("source.txt", "destination.txt", constants.COPYFILE_EXCL); + * console.log("source.txt was copied to destination.txt"); + * } catch { + * console.log("The file could not be copied"); + * } + * ``` + * @since v0.0.67 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile( + src: PathLike, + dest: PathLike, + mode?: number, + ): Promise<void>; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v0.0.67 + * @param [flags="r"] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: OpenMode, mode?: Mode): Promise<number>; + /** + * Renames `oldPath` to `newPath`. + * @since v0.0.67 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise<void>; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * @since v0.0.67 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise<void>; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * @since v0.0.67 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise<string | undefined>; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise<void>; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null | undefined, + ): Promise<string | undefined>; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `"buffer"`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from "fs/promises"; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v0.0.67 + * @return Fulfills with an array of the names of the files in the directory excluding `"."` and `".."`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | undefined + | null, + ): Promise<string[]>; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + } + | "buffer", + ): Promise<Buffer[]>; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null, + ): Promise<string[] | Buffer[]>; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + }, + ): Promise<Dirent[]>; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * resolved with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `"buffer"`, the link path + * returned will be passed as a `Buffer` object. + * @since v0.0.67 + * @return Fulfills with the `linkString` upon success. + */ + function readlink( + path: PathLike, + options?: EncodingOption | BufferEncoding | null, + ): Promise<string>; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used. + */ + function readlink( + path: PathLike, + options: BufferEncodingOption, + ): Promise<Buffer>; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used. + */ + function readlink( + path: PathLike, + options?: EncodingOption | string | null, + ): Promise<string | Buffer>; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `"dir"`,`"file"`, or `"junction"`. Windows junction points require the destination path + * to be absolute. When using `"junction"`, the `target` argument will + * automatically be normalized to absolute path. + * @since v0.0.67 + * @param [type="file"] + * @return Fulfills with `undefined` upon success. + */ + function symlink( + target: PathLike, + path: PathLike, + type?: SimlinkType, + ): Promise<void>; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v0.0.67 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + options?: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + ): Promise<Stats>; + function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise<BigIntStats>; + function lstat( + path: PathLike, + options?: StatOptions, + ): Promise<Stats | BigIntStats>; + /** + * @since v0.0.67 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + options?: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + ): Promise<Stats>; + function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise<BigIntStats>; + function stat( + path: PathLike, + options?: StatOptions, + ): Promise<Stats | BigIntStats>; + /** + * 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 v0.0.67 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise<void>; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v0.0.67 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise<void>; + /** + * Changes the permissions of a file. + * @since v0.0.67 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise<void>; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v0.4.7 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise<void>; + /** + * Changes the ownership on a symbolic link. + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise<void>; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v0.0.67 + * @return Fulfills with `undefined` upon success. + */ + function lutimes( + path: PathLike, + atime: TimeLike, + mtime: TimeLike, + ): Promise<void>; + /** + * Changes the ownership of a file. + * @since v0.0.67 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise<void>; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `"123456789.0"`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v0.0.67 + * @return Fulfills with `undefined` upon success. + */ + function utimes( + path: PathLike, + atime: TimeLike, + mtime: TimeLike, + ): Promise<void>; + /** + * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `"buffer"`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v0.0.67 + * @return Fulfills with the resolved path upon success. + */ + function realpath( + path: PathLike, + options?: EncodingOption | null, + ): Promise<string>; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used. + */ + function realpath( + path: PathLike, + options: BufferEncodingOption, + ): Promise<Buffer>; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used. + */ + function realpath( + path: PathLike, + options?: EncodingOption | null, + ): Promise<string | Buffer>; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from "fs/promises"; + * + * try { + * await mkdtemp(path.join(os.tmpdir(), "foo-")); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing + * platform-specific path separator + * (`require("path").sep`). + * @since v0.0.67 + * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. + */ + function mkdtemp( + prefix: string, + options?: EncodingOption | null, + ): Promise<string>; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used. + */ + function mkdtemp( + prefix: string, + options: BufferEncodingOption, + ): Promise<Buffer>; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used. + */ + function mkdtemp( + prefix: string, + options?: EncodingOption | null, + ): Promise<string | Buffer>; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from "fs/promises"; + * import { Buffer } from "buffer"; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from("Hello Node.js")); + * const promise = writeFile("message.txt", data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.0.67 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathOrFileDescriptor, + data: string | ArrayBufferView | ArrayBufferLike, + options?: WriteFileOptions, + ): Promise<void>; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v0.0.67 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise<void>; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory"s contents will be + * returned. + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from "fs/promises"; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v0.0.67 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathOrFileDescriptor, + options?: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | null, + ): Promise<Buffer>; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `"r"`. + */ + function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise<string>; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `"r"`. + */ + function readFile( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & + Abortable & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null, + ): Promise<string | Buffer>; +} + +declare module "node:fs/promises" { + import * as fsPromises from "fs/promises"; + export = fsPromises; +} diff --git a/packages/bun-types/globals.d.ts b/packages/bun-types/globals.d.ts new file mode 100644 index 000000000..1c6474297 --- /dev/null +++ b/packages/bun-types/globals.d.ts @@ -0,0 +1,2562 @@ +type BinaryType = "arraybuffer" | "blob"; +type Transferable = ArrayBuffer; +type MessageEventSource = undefined; +type Encoding = "utf-8" | "windows-1252" | "utf-16"; +type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; +type Architecture = + | "arm" + | "arm64" + | "ia32" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "s390" + | "s390x" + | "x64"; +type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + +interface console { + assert(condition?: boolean, ...data: any[]): void; + clear(): void; + /** + * Increment a [count](https://www.youtube.com/watch?v=2AoxCkySv34&t=22s) + * @param label label counter + */ + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + /** + * Log to stderr in your terminal + * + * Appears in red + * + * @param data something to display + */ + error(...data: any[]): void; + /** Does nothing currently */ + group(...data: any[]): void; + /** Does nothing currently */ + groupCollapsed(...data: any[]): void; + /** Does nothing currently */ + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + /** Does nothing currently */ + table(tabularData?: any, properties?: string[]): void; + /** + * Begin a timer to log with {@link console.timeEnd} + * + * @param label - The label to use for the timer + * + * ```ts + * console.time("how long????"); + * for (let i = 0; i < 999999; i++) { + * // do stuff + * let x = i * i; + * } + * console.timeEnd("how long????"); + * ``` + */ + time(label?: string): void; + /** + * End a timer to log with {@link console.time} + * + * @param label - The label to use for the timer + * + * ```ts + * console.time("how long????"); + * for (let i = 0; i < 999999; i++) { + * // do stuff + * let x = i * i; + * } + * console.timeEnd("how long????"); + * ``` + */ + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} + +declare var console: console; + +declare namespace NodeJS { + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined }): string; + paths(request: string): string[] | null; + } + + interface Require { + (id: string): any; + resolve: RequireResolve; + } +} + +interface ImportMeta { + /** + * `file://` url string for the current module. + * + * @example + * ```ts + * console.log(import.meta.url); + * "file:///Users/me/projects/my-app/src/my-app.ts" + * ``` + */ + url: string; + /** + * Absolute path to the source file + */ + path: string; + /** + * Absolute path to the directory containing the source file. + * + * Does not have a trailing slash + */ + dir: string; + /** + * Filename of the source file + */ + file: string; + /** + * Resolve a module ID the same as if you imported it + * + * On failure, throws a `ResolveError` + */ + resolve(moduleId: string): Promise<string>; + /** + * Resolve a `moduleId` as though it were imported from `parent` + * + * On failure, throws a `ResolveError` + */ + // tslint:disable-next-line:unified-signatures + resolve(moduleId: string, parent: string): Promise<string>; + + /** + * Resolve a module ID the same as if you imported it + * + * The `parent` argument is optional, and defaults to the current module's path. + */ + resolveSync(moduleId: string, parent?: string): string; + + /** + * Resolve a module ID the same as if you imported it + * + * The `parent` argument is optional, and defaults to the current module's path. + */ + require: NodeJS.Require; +} + +/** + * NodeJS-style `require` function + * + * Internally, uses `import.meta.require` + * + * @param moduleId - The module ID to resolve + */ +declare var require: NodeJS.Require; + +/** @deprecated Please use `import.meta.path` instead. */ +declare var __filename: string; + +/** @deprecated Please use `import.meta.dir` instead. */ +declare var __dirname: string; + +interface StructuredSerializeOptions { + transfer?: Transferable[]; +} + +interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; +} + +interface Process { + /** + * The current version of Bun + */ + version: string; + /** + * Run a function on the next tick of the event loop + * + * This is the same as {@link queueMicrotask} + * + * @param callback - The function to run + */ + nextTick(callback: (...args: any) => any, ...args: any): void; + title: string; + exitCode: number; + browser: boolean; + versions: Record<string, string>; + ppid: number; + hrtime: { + (time?: [number, number]): [number, number]; + bigint(): bigint; + }; + pid: number; + arch: Architecture; + platform: Platform; + argv: string[]; + // execArgv: string[]; + env: Record<string, string> & { + NODE_ENV: string; + }; + + /** Whether you are using Bun */ + isBun: 1; // FIXME: this should actually return a boolean + /** The current git sha of Bun **/ + revision: string; + // execPath: string; + // abort(): void; + chdir(directory: string): void; + cwd(): string; + exit(code?: number): void; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + dlopen(module: { exports: any }, filename: string, flags?: number): void; +} + +declare var process: Process; + +declare module "process" { + var process: Process; + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} + +interface BlobInterface { + text(): Promise<string>; + arrayBuffer(): Promise<ArrayBuffer>; + json<TJSONReturnType = unknown>(): Promise<TJSONReturnType>; +} + +type BlobPart = string | Blob | BufferSource | ArrayBuffer; +interface BlobPropertyBag { + /** Set a default "type" */ + type?: string; + + /** Not implemented in Bun yet. */ + endings?: "transparent" | "native"; +} + +/** + * This Fetch API interface allows you to perform various actions on HTTP + * request and response headers. These actions include retrieving, setting, + * adding to, and removing. A Headers object has an associated header list, + * which is initially empty and consists of zero or more name and value + * pairs. + * + * You can add to this using methods like append() + * + * In all methods of this interface, header names are matched by + * case-insensitive byte sequence. + */ +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + entries(): IterableIterator<[string, string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach( + callbackfn: (value: string, key: string, parent: Headers) => void, + thisArg?: any, + ): void; +} + +declare var Headers: { + prototype: Headers; + new (init?: HeadersInit): Headers; +}; + +type HeadersInit = Array<[string, string]> | Record<string, string> | Headers; +type ResponseType = + | "basic" + | "cors" + | "default" + | "error" + | "opaque" + | "opaqueredirect"; + +declare class Blob implements BlobInterface { + /** + * Create a new [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + * + * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects + * @param `options` - An object containing properties to be added to the [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + */ + constructor(parts?: BlobPart[] | Blob, options?: BlobPropertyBag); + /** + * Create a new view **without 🚫 copying** the underlying data. + * + * Similar to [`BufferSource.subarray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BufferSource/subarray) + * + * @param begin The index that sets the beginning of the view. + * @param end The index that sets the end of the view. + * + */ + slice(begin?: number, end?: number): Blob; + + /** + * Read the data from the blob as a string. It will be decoded from UTF-8. + */ + text(): Promise<string>; + + /** + * Read the data from the blob as a ReadableStream. + */ + stream(): ReadableStream<Uint8Array>; + + /** + * Read the data from the blob as an ArrayBuffer. + * + * This copies the data into a new ArrayBuffer. + */ + arrayBuffer(): Promise<ArrayBuffer>; + + /** + * Read the data from the blob as a JSON object. + * + * This first decodes the data from UTF-8, then parses it as JSON. + * + */ + json<TJSONReturnType = unknown>(): Promise<TJSONReturnType>; + + type: string; + size: number; +} + +interface ResponseInit { + headers?: HeadersInit; + /** @default 200 */ + status?: number; + + /** @default "OK" */ + statusText?: string; +} + +/** + * Represents an HTTP [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * + * Use it to get the body of the response, the status code, and other information. + * + * @example + * ```ts + * const response: Response = await fetch("https://remix.run"); + * await response.text(); + * ``` + * @example + * ```ts + * const response: Response = await fetch("https://remix.run"); + * await Bun.write("remix.html", response); + * ``` + */ +declare class Response implements BlobInterface { + constructor( + body?: ReadableStream | BlobPart | BlobPart[] | null, + options?: ResponseInit, + ); + + /** + * Create a new {@link Response} with a JSON body + * + * @param body - The body of the response + * @param options - options to pass to the response + * + * @example + * + * ```ts + * const response = Response.json({hi: "there"}); + * console.assert( + * await response.text(), + * `{"hi":"there"}` + * ); + * ``` + * ------- + * + * This is syntactic sugar for: + * ```js + * new Response(JSON.stringify(body), {headers: { "Content-Type": "application/json" }}) + * ``` + * @link https://github.com/whatwg/fetch/issues/1389 + */ + static json(body?: any, options?: ResponseInit | number): Response; + /** + * Create a new {@link Response} that redirects to url + * + * @param url - the URL to redirect to + * @param status - the HTTP status code to use for the redirect + */ + // tslint:disable-next-line:unified-signatures + static redirect(url: string, status?: number): Response; + + /** + * Create a new {@link Response} that redirects to url + * + * @param url - the URL to redirect to + * @param options - options to pass to the response + */ + // tslint:disable-next-line:unified-signatures + static redirect(url: string, options?: ResponseInit): Response; + + /** + * Create a new {@link Response} that has a network error + */ + static error(): Response; + + /** + * HTTP [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) sent with the response. + * + * @example + * ```ts + * const {headers} = await fetch("https://remix.run"); + * headers.get("Content-Type"); + * headers.get("Content-Length"); + * headers.get("Set-Cookie"); + * ``` + */ + readonly headers: Headers; + + /** + * HTTP response body as a [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) + * + * This is part of web Streams + * + * @example + * ```ts + * const {body} = await fetch("https://remix.run"); + * const reader = body.getReader(); + * const {done, value} = await reader.read(); + * console.log(value); // Uint8Array + * ``` + */ + readonly body: ReadableStream | null; + + /** + * Has the body of the response already been consumed? + */ + readonly bodyUsed: boolean; + + /** + * Read the data from the Response as a string. It will be decoded from UTF-8. + * + * When the body is valid latin1, this operation is zero copy. + */ + text(): Promise<string>; + + /** + * Read the data from the Response as a string. It will be decoded from UTF-8. + * + * When the body is valid latin1, this operation is zero copy. + */ + arrayBuffer(): Promise<ArrayBuffer>; + + /** + * Read the data from the Response as a JSON object. + * + * This first decodes the data from UTF-8, then parses it as JSON. + * + */ + json<TJSONReturnType = unknown>(): Promise<TJSONReturnType>; + + /** + * Read the data from the Response as a Blob. + * + * This allows you to reuse the underlying data. + * + * @returns Promise<Blob> - The body of the response as a {@link Blob}. + */ + blob(): Promise<Blob>; + + readonly ok: boolean; + readonly redirected: boolean; + /** + * HTTP status code + * + * @example + * 200 + * + * 0 for network errors + */ + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + /** HTTP url as a string */ + readonly url: string; + + /** Copy the Response object into a new Response, including the body */ + clone(): Response; +} + +type RequestCache = + | "default" + | "force-cache" + | "no-cache" + | "no-store" + | "only-if-cached" + | "reload"; +type RequestCredentials = "include" | "omit" | "same-origin"; +type RequestDestination = + | "" + | "audio" + | "audioworklet" + | "document" + | "embed" + | "font" + | "frame" + | "iframe" + | "image" + | "manifest" + | "object" + | "paintworklet" + | "report" + | "script" + | "sharedworker" + | "style" + | "track" + | "video" + | "worker" + | "xslt"; +type RequestMode = "cors" | "navigate" | "no-cors" | "same-origin"; +type RequestRedirect = "error" | "follow" | "manual"; +type ReferrerPolicy = + | "" + | "no-referrer" + | "no-referrer-when-downgrade" + | "origin" + | "origin-when-cross-origin" + | "same-origin" + | "strict-origin" + | "strict-origin-when-cross-origin" + | "unsafe-url"; +type RequestInfo = Request | string; + +type BodyInit = ReadableStream | XMLHttpRequestBodyInit; +type XMLHttpRequestBodyInit = Blob | BufferSource | string; +type ReadableStreamController<T> = ReadableStreamDefaultController<T>; +type ReadableStreamDefaultReadResult<T> = + | ReadableStreamDefaultReadValueResult<T> + | ReadableStreamDefaultReadDoneResult; +type ReadableStreamReader<T> = ReadableStreamDefaultReader<T>; + +interface RequestInit { + /** + * A BodyInit object or null to set request's body. + */ + body?: BodyInit | null; + /** + * A string indicating how the request will interact with the browser's cache to set request's cache. + * + * Note: as of Bun v0.0.74, this is not implemented yet. + */ + cache?: RequestCache; + /** + * A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. + */ + credentials?: RequestCredentials; + /** + * A Headers object, an object literal, or an array of two-item arrays to set request's headers. + */ + headers?: HeadersInit; + /** + * A cryptographic hash of the resource to be fetched by request. Sets request's integrity. + * + * Note: as of Bun v0.0.74, this is not implemented yet. + */ + integrity?: string; + /** + * A boolean to set request's keepalive. + * + * Available in Bun v0.2.0 and above. + * + * This is enabled by default + */ + keepalive?: boolean; + /** + * A string to set request's method. + */ + method?: string; + /** + * A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. + */ + mode?: RequestMode; + /** + * A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. + */ + redirect?: RequestRedirect; + /** + * A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. + */ + referrer?: string; + /** + * A referrer policy to set request's referrerPolicy. + */ + referrerPolicy?: ReferrerPolicy; + /** + * An AbortSignal to set request's signal. + * + * Note: as of Bun v0.0.74, this is not implemented yet. + */ + signal?: AbortSignal | null; + /** + * Can only be null. Used to disassociate request from any Window. + * + * This does nothing in Bun + */ + window?: any; + + /** + * Enable or disable HTTP request timeout + */ + timeout?: boolean; +} + +/** + * [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) represents an HTTP request. + * + * @example + * ```ts + * const request = new Request("https://remix.run/"); + * await fetch(request); + * ``` + * + * @example + * ```ts + * const request = new Request("https://remix.run/"); + * await fetch(request); + * ``` + */ +declare class Request implements BlobInterface { + constructor(requestInfo: RequestInfo, requestInit?: RequestInit); + + /** + * Read or write the HTTP headers for this request. + * + * @example + * ```ts + * const request = new Request("https://remix.run/"); + * request.headers.set("Content-Type", "application/json"); + * request.headers.set("Accept", "application/json"); + * await fetch(request); + * ``` + */ + headers: Headers; + + /** + * The URL (as a string) corresponding to the HTTP request + * @example + * ```ts + * const request = new Request("https://remix.run/"); + * request.url; // "https://remix.run/" + * ``` + */ + readonly url: string; + + /** + * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as a string. It will be decoded from UTF-8. + * + * When the body is valid latin1, this operation is zero copy. + */ + text(): Promise<string>; + + /** + * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as a {@link ReadableStream}. + * + * Streaming **outgoing** HTTP request bodies via `fetch()` is not yet supported in + * Bun. + * + * Reading **incoming** HTTP request bodies via `ReadableStream` in `Bun.serve()` is supported + * as of Bun v0.2.0. + * + * + */ + get body(): ReadableStream | null; + + /** + * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as an ArrayBuffer. + * + */ + arrayBuffer(): Promise<ArrayBuffer>; + + /** + * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as a JSON object. + * + * This first decodes the data from UTF-8, then parses it as JSON. + * + */ + json<TJSONReturnType = unknown>(): Promise<TJSONReturnType>; + + /** + * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as a `Blob`. + * + * This allows you to reuse the underlying data. + * + */ + blob(): Promise<Blob>; + + /** + * Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching. + */ + readonly cache: RequestCache; + /** + * Returns the credentials mode associated with request, which is a string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. + */ + readonly credentials: RequestCredentials; + /** + * Returns the kind of resource requested by request, e.g., "document" or "script". + * + * In Bun, this always returns "navigate". + */ + readonly destination: RequestDestination; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * This does nothing in Bun right now. + */ + readonly integrity: string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * In Bun, this always returns false. + */ + readonly keepalive: boolean; + /** + * Returns request's HTTP method, which is "GET" by default. + */ + readonly method: string; + /** + * Returns the mode associated with request, which is a string indicating whether the request will use CORS, or will be restricted to same-origin URLs. + */ + readonly mode: RequestMode; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + */ + readonly redirect: RequestRedirect; + /** + * Returns the referrer of request. Its value can be a same-origin URL + * if explicitly set in init, the empty string to indicate no referrer, + * and "about:client" when defaulting to the global's default. This is + * used during fetching to determine the value of the `Referer` header + * of the request being made. + */ + readonly referrer: string; + /** + * Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer. + */ + readonly referrerPolicy: ReferrerPolicy; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * Note: this is **not implemented yet**. The cake is a lie. + */ + readonly signal: AbortSignal; + + /** Copy the Request object into a new Request, including the body */ + clone(): Request; +} + +interface Crypto { + readonly subtle: SubtleCrypto; + + getRandomValues<T extends BufferSource = BufferSource>(array: T): T; + /** + * Generate a cryptographically secure random UUID. + * + * @example + * + * ```js + * crypto.randomUUID() + * '5e6adf82-f516-4468-b1e1-33d6f664d7dc' + * ``` + */ + randomUUID(): string; +} + +declare var crypto: Crypto; + +/** + * [`atob`](https://developer.mozilla.org/en-US/docs/Web/API/atob) decodes base64 into ascii text. + * + * @param asciiText The base64 string to decode. + */ +declare function atob(encodedData: string): string; + +/** + * [`btoa`](https://developer.mozilla.org/en-US/docs/Web/API/btoa) encodes ascii text into base64. + * + * @param stringToEncode The ascii text to encode. + */ +declare function btoa(stringToEncode: string): string; + +/** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + */ +declare class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: "utf-8"; + + constructor(encoding?: "utf-8"); + + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src?: string, dest?: BufferSource): EncodeIntoResult; +} + +/** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + */ +declare class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + + constructor( + encoding?: Encoding, + options?: { fatal?: boolean; ignoreBOM?: boolean }, + ); + + /** + * 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 `BufferSource` instance containing the encoded data. + */ + decode(input?: BufferSource | ArrayBuffer): string; +} + +/** + * ShadowRealms are a distinct global environment, with its own global object + * containing its own intrinsics and built-ins (standard objects that are not + * bound to global variables, like the initial value of Object.prototype). + * + * + * @example + * + * ```js + * const red = new ShadowRealm(); + * + * // realms can import modules that will execute within it's own environment. + * // When the module is resolved, it captured the binding value, or creates a new + * // wrapped function that is connected to the callable binding. + * const redAdd = await red.importValue('./inside-code.js', 'add'); + * + * // redAdd is a wrapped function exotic object that chains it's call to the + * // respective imported binding. + * let result = redAdd(2, 3); + * + * console.assert(result === 5); // yields true + * + * // The evaluate method can provide quick code evaluation within the constructed + * // shadowRealm without requiring any module loading, while it still requires CSP + * // relaxing. + * globalThis.someValue = 1; + * red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global + * console.assert(globalThis.someValue === 1); + * + * // The wrapped functions can also wrap other functions the other way around. + * const setUniqueValue = + * await red.importValue('./inside-code.js', 'setUniqueValue'); + * + * // setUniqueValue = (cb) => (cb(globalThis.someValue) * 2); + * + * result = setUniqueValue((x) => x ** 3); + * + * console.assert(result === 16); // yields true + * ``` + */ +declare class ShadowRealm { + /** + * Creates a new [ShadowRealm](https://github.com/tc39/proposal-shadowrealm/blob/main/explainer.md#introduction) + * + * @example + * + * ```js + * const red = new ShadowRealm(); + * + * // realms can import modules that will execute within it's own environment. + * // When the module is resolved, it captured the binding value, or creates a new + * // wrapped function that is connected to the callable binding. + * const redAdd = await red.importValue('./inside-code.js', 'add'); + * + * // redAdd is a wrapped function exotic object that chains it's call to the + * // respective imported binding. + * let result = redAdd(2, 3); + * + * console.assert(result === 5); // yields true + * + * // The evaluate method can provide quick code evaluation within the constructed + * // shadowRealm without requiring any module loading, while it still requires CSP + * // relaxing. + * globalThis.someValue = 1; + * red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global + * console.assert(globalThis.someValue === 1); + * + * // The wrapped functions can also wrap other functions the other way around. + * const setUniqueValue = + * await red.importValue('./inside-code.js', 'setUniqueValue'); + * + * // setUniqueValue = (cb) => (cb(globalThis.someValue) * 2); + * + * result = setUniqueValue((x) => x ** 3); + * + * console.assert(result === 16); // yields true + * ``` + */ + constructor(); + importValue(specifier: string, bindingName: string): Promise<any>; + evaluate(sourceText: string): any; +} + +interface Blob { + /** + * Read the contents of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) as a JSON object + * @warn in browsers, this function is only available for `Response` and `Request` + */ + json(): Promise<any>; + /** + * Read the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) as a UTF-8 string + * @link https://developer.mozilla.org/en-US/docs/Web/API/Blob/text + */ + text(): Promise<string>; + /** + * Read the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) as an ArrayBuffer object + * @link https://developer.mozilla.org/en-US/docs/Web/API/Blob/arrayBuffer + */ + arrayBuffer(): Promise<ArrayBuffer>; +} + +declare var performance: { + /** + * Seconds since Bun.js started + * + * Uses a high-precision system timer to measure the time elapsed since the + * Bun.js runtime was initialized. The value is represented as a double + * precision floating point number. The value is monotonically increasing + * during the lifetime of the runtime. + * + */ + now: () => number; +}; + +/** + * Cancel a repeating timer by its timer ID. + * @param id timer id + */ +declare function clearInterval(id?: number): void; +/** + * Cancel a delayed function call by its timer ID. + * @param id timer id + */ +declare function clearTimeout(id?: number): void; +// declare function createImageBitmap(image: ImageBitmapSource, options?: ImageBitmapOptions): Promise<ImageBitmap>; +// declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise<ImageBitmap>; +/** + * Send a HTTP(s) request + * + * @param url URL string + * @param init A structured value that contains settings for the fetch() request. + * + * @returns A promise that resolves to {@link Response} object. + * + * + */ +declare function fetch( + url: string, + init?: RequestInit, + /** + * This is a custom property that is not part of the Fetch API specification. + * It exists mostly as a debugging tool + */ + bunOnlyOptions?: { + /** + * Log the raw HTTP request & response to stdout. This API may be + * removed in a future version of Bun without notice. + */ + verbose: boolean; + }, +): Promise<Response>; + +/** + * Send a HTTP(s) request + * + * @param request Request object + * @param init A structured value that contains settings for the fetch() request. + * + * @returns A promise that resolves to {@link Response} object. + * + * + */ +// tslint:disable-next-line:unified-signatures +declare function fetch( + request: Request, + init?: RequestInit, + /** + * This is a custom property that is not part of the Fetch API specification. + * It exists mostly as a debugging tool + */ + bunOnlyOptions?: { + /** + * Log the raw HTTP request & response to stdout. This API may be + * removed in a future version of Bun without notice. + */ + verbose: boolean; + }, +): Promise<Response>; + +declare function queueMicrotask(callback: (...args: any[]) => void): void; +/** + * Log an error using the default exception handler + * @param error Error or string + */ +declare function reportError(error: any): void; +/** + * Run a function every `interval` milliseconds + * @param handler function to call + * @param interval milliseconds to wait between calls + */ +declare function setInterval( + handler: TimerHandler, + interval?: number, + ...arguments: any[] +): number; +/** + * Run a function after `timeout` (milliseconds) + * @param handler function to call + * @param timeout milliseconds to wait between calls + */ +declare function setTimeout( + handler: TimerHandler, + timeout?: number, + ...arguments: any[] +): number; +declare function addEventListener<K extends keyof EventMap>( + type: K, + listener: (this: object, ev: EventMap[K]) => any, + options?: boolean | AddEventListenerOptions, +): void; +declare function addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, +): void; +declare function removeEventListener<K extends keyof EventMap>( + type: K, + listener: (this: object, ev: EventMap[K]) => any, + options?: boolean | EventListenerOptions, +): void; +declare function removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, +): void; + +// ----------------------- +// ----------------------- +// --- libdom.d.ts + +interface ErrorEventInit extends EventInit { + colno?: number; + error?: any; + filename?: string; + lineno?: number; + message?: string; +} + +interface CloseEventInit extends EventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} + +interface MessageEventInit<T = any> extends EventInit { + data?: T; + lastEventId?: string; + origin?: string; + source?: MessageEventSource; +} + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; +} + +interface UIEventInit extends EventInit { + detail?: number; + view?: null; + /** @deprecated */ + which?: number; +} + +interface EventModifierInit extends UIEventInit { + altKey?: boolean; + ctrlKey?: boolean; + metaKey?: boolean; + modifierAltGraph?: boolean; + modifierCapsLock?: boolean; + modifierFn?: boolean; + modifierFnLock?: boolean; + modifierHyper?: boolean; + modifierNumLock?: boolean; + modifierScrollLock?: boolean; + modifierSuper?: boolean; + modifierSymbol?: boolean; + modifierSymbolLock?: boolean; + shiftKey?: boolean; +} + +interface EventSourceInit { + withCredentials?: boolean; +} + +/** 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(): void; +} + +/** EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. */ +interface EventTarget { + /** + * Appends an event listener for events whose type attribute value is + * type. The callback argument sets the callback that will be invoked + * when the event is dispatched. + * + * The options argument sets listener-specific options. For + * compatibility this can be a boolean, in which case the method behaves + * exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being + * invoked when the event's eventPhase attribute value is + * BUBBLING_PHASE. When false (or not present), callback will not be + * invoked when event's eventPhase attribute value is CAPTURING_PHASE. + * Either way,callback will be invoked if event's eventPhase attribute + * value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will + * not cancel the event by invoking preventDefault(). This is used to + * enable performance optimizations described in § 2.8 Observing event + * listeners. + * + * When set to true, options's once indicates that the callback will + * only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event + * listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is + * not appended if it has the same type, callback, and capture. + */ + addEventListener( + type: string, + callback: EventListenerOrEventListenerObject | null, + 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, + callback: EventListenerOrEventListenerObject | null, + options?: EventListenerOptions | boolean, + ): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new (): EventTarget; +}; + +/** An event which takes place in the DOM. */ +interface Event { + /** + * Returns true or false depending on how event was initialized. True + * if event goes through its target's ancestors in reverse tree order, + * and false otherwise. + */ + readonly bubbles: boolean; + cancelBubble: boolean; + /** + * Returns true or false depending on how event was initialized. Its + * return value does not always carry meaning, but true can indicate + * that part of the operation during which event was dispatched, can be + * canceled by invoking the preventDefault() method. + */ + readonly cancelable: boolean; + /** + * Returns true or false depending on how event was initialized. True + * if event invokes listeners past a ShadowRoot node that is the root of + * its target, and false otherwise. + */ + readonly composed: boolean; + /** + * Returns the object whose event listener's callback is currently + * being invoked. + */ + readonly currentTarget: EventTarget | null; + /** + * Returns true if preventDefault() was invoked successfully to + * indicate cancelation, and false otherwise. + */ + readonly defaultPrevented: boolean; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, + * AT_TARGET, and BUBBLING_PHASE. + */ + readonly eventPhase: number; + /** + * Returns true if event was dispatched by the user agent, and false + * otherwise. + */ + readonly isTrusted: boolean; + /** + * @deprecated + */ + returnValue: boolean; + /** + * @deprecated + */ + readonly srcElement: EventTarget | null; + /** + * Returns the object to which event is dispatched (its target). + */ + readonly target: EventTarget | null; + /** + * Returns the event's timestamp as the number of milliseconds measured + * relative to the time origin. + */ + readonly timeStamp: DOMHighResTimeStamp; + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + */ + readonly type: string; + /** + * Returns the invocation target objects of event's path (objects on + * which listeners will be invoked), except for any nodes in shadow + * trees of which the shadow root's mode is "closed" that are not + * reachable from event's currentTarget. + */ + composedPath(): EventTarget[]; + /** + * @deprecated + */ + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + /** + * If invoked when the cancelable attribute value is true, and while + * executing a listener for the event with passive set to false, signals + * to the operation that caused event to be dispatched that it needs to + * be canceled. + */ + preventDefault(): void; + /** + * Invoking this method prevents event from reaching any registered + * event listeners after the current one finishes running and, when + * dispatched in a tree, also prevents event from reaching any other + * objects. + */ + stopImmediatePropagation(): void; + /** + * When dispatched in a tree, invoking this method prevents event from + * reaching any objects other than the current object. + */ + stopPropagation(): void; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +} + +declare var Event: { + prototype: Event; + new (type: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +}; + +/** + * Events providing information related to errors in scripts or in files. + */ +interface ErrorEvent extends Event { + readonly colno: number; + readonly error: any; + readonly filename: string; + readonly lineno: number; + readonly message: string; +} + +declare var ErrorEvent: { + prototype: ErrorEvent; + new (type: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +/** A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. */ +interface CloseEvent extends Event { + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new (type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +/** A message received by a target object. */ +interface MessageEvent<T = any> extends Event { + /** Returns the data of the message. */ + readonly data: T; + /** Returns the last event ID string, for server-sent events. */ + readonly lastEventId: string; + /** Returns the origin of the message, for server-sent events and cross-document messaging. */ + readonly origin: string; + readonly source: MessageEventSource; + /** @deprecated */ + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: null, + ): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new <T>(type: string, eventInitDict?: MessageEventInit<T>): MessageEvent<T>; +}; + +/** + * An implementation of the [WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) + */ +interface WebSocketEventMap { + close: CloseEvent; + error: Event; + message: MessageEvent; + open: Event; +} + +/** Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. */ +interface WebSocket extends EventTarget { + /** + * Returns a string that indicates how binary data from the WebSocket object is exposed to scripts: + * + * Can be set, to change how binary data is returned. The default is "blob". + */ + binaryType: BinaryType; + /** + * Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network. + * + * If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.) + */ + readonly bufferedAmount: number; + /** Returns the extensions selected by the server, if any. */ + readonly extensions: string; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; + /** Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. */ + readonly protocol: string; + /** Returns the state of the WebSocket object's connection. It can have the values described below. */ + readonly readyState: number; + /** Returns the URL that was used to establish the WebSocket connection. */ + readonly url: string; + /** Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. */ + close(code?: number, reason?: string): void; + /** Transmits data using the WebSocket connection. data can be a string, an ArrayBuffer, or an BufferSource. */ + send(data: string | ArrayBufferLike | BufferSource): void; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; + addEventListener<K extends keyof WebSocketEventMap>( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener<K extends keyof WebSocketEventMap>( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void; +} + +declare var WebSocket: { + prototype: WebSocket; + new (url: string | URL, protocols?: string | string[]): WebSocket; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; +}; + +/** + * The URL interface represents an object providing static methods used for + * creating object URLs. + */ +interface URL { + hash: string; + host: string; + hostname: string; + href: string; + toString(): string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toJSON(): string; +} + +interface URLSearchParams { + /** Appends a specified key/value pair as a new search parameter. */ + append(name: string, value: string): void; + /** Deletes the given search parameter, and its associated value, from the list of all search parameters. */ + delete(name: string): void; + /** Returns the first value associated to the given search parameter. */ + get(name: string): string | null; + /** Returns all the values association with a given search parameter. */ + getAll(name: string): string[]; + /** Returns a Boolean indicating if such a search parameter exists. */ + has(name: string): boolean; + /** Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. */ + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[string, string]>; + /** Returns an iterator allowing to go through all keys of the key/value pairs of this search parameter. */ + keys(): IterableIterator<string>; + /** Returns an iterator allowing to go through all values of the key/value pairs of this search parameter. */ + values(): IterableIterator<string>; + forEach( + callbackfn: (value: string, key: string, parent: URLSearchParams) => void, + thisArg?: any, + ): void; + /** Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */ + toString(): string; +} + +declare var URLSearchParams: { + prototype: URLSearchParams; + new ( + init?: string[][] | Record<string, string> | string | URLSearchParams, + ): URLSearchParams; + toString(): string; +}; + +declare var URL: { + prototype: URL; + new (url: string | URL, base?: string | URL): URL; + /** Not implemented yet */ + createObjectURL(obj: Blob): string; + /** Not implemented yet */ + revokeObjectURL(url: string): void; +}; + +type TimerHandler = (...args: any[]) => void; + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +declare var AbortController: { + prototype: AbortController; + new (): AbortController; +}; + +interface FetchEvent extends Event { + readonly request: Request; + readonly url: string; + + waitUntil(promise: Promise<any>): void; + respondWith(response: Response | Promise<Response>): void; +} + +interface EventMap { + fetch: FetchEvent; + // exit: Event; +} + +interface AbortSignalEventMap { + abort: Event; +} + +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; + signal?: AbortSignal; +} + +/** 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; + onabort: ((this: AbortSignal, ev: Event) => any) | null; + addEventListener<K extends keyof AbortSignalEventMap>( + type: K, + listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener<K extends keyof AbortSignalEventMap>( + type: K, + listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new (): AbortSignal; +}; + +// type AlgorithmIdentifier = Algorithm | string; +// type BodyInit = ReadableStream | XMLHttpRequestBodyInit; +type BufferSource = ArrayBufferView | ArrayBuffer | SharedArrayBuffer; +// type COSEAlgorithmIdentifier = number; +// type CSSNumberish = number; +// type CanvasImageSource = +// | HTMLOrSVGImageElement +// | HTMLVideoElement +// | HTMLCanvasElement +// | ImageBitmap; +type DOMHighResTimeStamp = number; +// type EpochTimeStamp = number; +type EventListenerOrEventListenerObject = EventListener | EventListenerObject; + +/** + * Low-level JavaScriptCore API for accessing the native ES Module loader (not a Bun API) + * + * Before using this, be aware of a few things: + * + * **Using this incorrectly will crash your application**. + * + * This API may change any time JavaScriptCore is updated. + * + * Bun may rewrite ESM import specifiers to point to bundled code. This will + * be confusing when using this API, as it will return a string like + * "/node_modules.server.bun". + * + * Bun may inject additional imports into your code. This usually has a `bun:` prefix. + * + */ +declare var Loader: { + /** + * ESM module registry + * + * This lets you implement live reload in Bun. If you + * delete a module specifier from this map, the next time it's imported, it + * will be re-transpiled and loaded again. + * + * The keys are the module specifiers and the + * values are metadata about the module. + * + * The keys are an implementation detail for Bun that will change between + * versions. + * + * - Userland modules are an absolute file path + * - Virtual modules have a `bun:` prefix or `node:` prefix + * - JS polyfills start with `"/bun-vfs/"`. `"buffer"` is an example of a JS polyfill + * - If you have a `node_modules.bun` file, many modules will point to that file + * + * Virtual modules and JS polyfills are embedded in bun's binary. They don't + * point to anywhere in your local filesystem. + * + * + */ + registry: Map< + string, + { + /** + * This refers to the state the ESM module is in + * + * TODO: make an enum for this number + * + * + */ + state: number; + dependencies: string[]; + /** + * Your application will probably crash if you mess with this. + */ + module: any; + } + >; + /** + * For an already-evaluated module, return the dependencies as module specifiers + * + * This list is already sorted and uniqued. + * + * @example + * + * For this code: + * ```js + * // /foo.js + * import classNames from 'classnames'; + * import React from 'react'; + * import {createElement} from 'react'; + * ``` + * + * This would return: + * ```js + * Loader.dependencyKeysIfEvaluated("/foo.js") + * ["bun:wrap", "/path/to/node_modules/classnames/index.js", "/path/to/node_modules/react/index.js"] + * ``` + * + * @param specifier - module specifier as it appears in transpiled source code + * + */ + dependencyKeysIfEvaluated: (specifier: string) => string[]; + /** + * The function JavaScriptCore internally calls when you use an import statement. + * + * This may return a path to `node_modules.server.bun`, which will be confusing. + * + * Consider {@link Bun.resolve} or {@link ImportMeta.resolve} + * instead. + * + * @param specifier - module specifier as it appears in transpiled source code + * @param referrer - module specifier that is resolving this specifier + */ + resolve: (specifier: string, referrer: string) => string; +}; + +/** This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. */ +interface ReadableStream<R = any> { + readonly locked: boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions, + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions, + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + forEach( + callbackfn: (value: any, key: number, parent: ReadableStream<R>) => void, + thisArg?: any, + ): void; + [Symbol.asyncIterator](): AsyncIterableIterator<R>; + values(options?: { preventCancel: boolean }): AsyncIterableIterator<R>; +} + +declare var ReadableStream: { + prototype: ReadableStream; + new <R = any>( + underlyingSource?: DirectUnderlyingSource<R> | UnderlyingSource<R>, + strategy?: QueuingStrategy<R>, + ): ReadableStream<R>; +}; + +interface QueuingStrategy<T = any> { + highWaterMark?: number; + size?: QueuingStrategySize<T>; +} + +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<BufferSource> { + readonly highWaterMark: number; + readonly size: QueuingStrategySize<BufferSource>; +} + +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new (init: QueuingStrategyInit): ByteLengthQueuingStrategy; +}; + +interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; +} + +interface ReadableStreamDirectController { + close(error?: Error): void; + write(data: BufferSource | ArrayBuffer | string): number | Promise<number>; + end(): number | Promise<number>; + flush(): number | Promise<number>; + start(): void; +} + +declare var ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new (): ReadableStreamDefaultController; +}; + +interface ReadableStreamDefaultReader<R = any> + extends ReadableStreamGenericReader { + read(): Promise<ReadableStreamDefaultReadResult<R>>; + releaseLock(): void; +} + +declare var ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new <R = any>(stream: ReadableStream<R>): ReadableStreamDefaultReader<R>; +}; + +interface ReadableStreamGenericReader { + readonly closed: Promise<undefined>; + cancel(reason?: any): Promise<void>; +} + +interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; +} + +interface ReadableStreamDefaultReadValueResult<T> { + done: false; + value: T; +} + +interface ReadableWritablePair<R = any, W = any> { + readable: ReadableStream<R>; + /** + * 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<W>; +} + +/** 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 backpressure and queuing. */ +interface WritableStream<W = any> { + readonly locked: boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} + +declare var WritableStream: { + prototype: WritableStream; + new <W = any>( + underlyingSink?: UnderlyingSink<W>, + strategy?: QueuingStrategy<W>, + ): WritableStream<W>; +}; + +/** 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; +} + +declare var WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new (): WritableStreamDefaultController; +}; + +/** 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<W = any> { + readonly closed: Promise<undefined>; + readonly desiredSize: number | null; + readonly ready: Promise<undefined>; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + releaseLock(): void; + write(chunk?: W): Promise<void>; +} + +declare var WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new <W = any>(stream: WritableStream<W>): WritableStreamDefaultWriter<W>; +}; + +interface ReadWriteStream extends ReadableStream, WritableStream {} + +interface TransformerFlushCallback<O> { + (controller: TransformStreamDefaultController<O>): void | PromiseLike<void>; +} + +interface TransformerStartCallback<O> { + (controller: TransformStreamDefaultController<O>): any; +} + +interface TransformerTransformCallback<I, O> { + ( + chunk: I, + controller: TransformStreamDefaultController<O>, + ): void | PromiseLike<void>; +} + +interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike<void>; +} + +interface UnderlyingSinkCloseCallback { + (): void | PromiseLike<void>; +} + +interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; +} + +interface UnderlyingSinkWriteCallback<W> { + ( + chunk: W, + controller: WritableStreamDefaultController, + ): void | PromiseLike<void>; +} + +interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike<void>; +} + +interface UnderlyingSink<W = any> { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined | "default" | "bytes"; + write?: UnderlyingSinkWriteCallback<W>; +} + +interface UnderlyingSource<R = any> { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback<R>; + start?: UnderlyingSourceStartCallback<R>; + type?: undefined; +} + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +interface DirectUnderlyingSource<R = any> { + cancel?: UnderlyingSourceCancelCallback; + pull: ( + controller: ReadableStreamDirectController, + ) => void | PromiseLike<void>; + type: "direct"; +} + +interface UnderlyingSourcePullCallback<R> { + (controller: ReadableStreamController<R>): void | PromiseLike<void>; +} + +interface UnderlyingSourceStartCallback<R> { + (controller: ReadableStreamController<R>): any; +} + +interface GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; +} + +interface TransformStream<I = any, O = any> { + readonly readable: ReadableStream<O>; + readonly writable: WritableStream<I>; +} + +declare var TransformStream: { + prototype: TransformStream; + new <I = any, O = any>( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O>, + ): TransformStream<I, O>; +}; + +interface TransformStreamDefaultController<O = any> { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; +} + +declare var TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new (): TransformStreamDefaultController; +}; + +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; +} + +/** 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; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new (init: QueuingStrategyInit): CountQueuingStrategy; +}; + +interface QueuingStrategySize<T = any> { + (chunk?: T): number; +} + +interface Transformer<I = any, O = any> { + flush?: TransformerFlushCallback<O>; + readableType?: undefined; + start?: TransformerStartCallback<O>; + transform?: TransformerTransformCallback<I, O>; + writableType?: undefined; +} + +interface Dict<T> { + [key: string]: T | undefined; +} + +interface ReadOnlyDict<T> { + readonly [key: string]: T | undefined; +} + +interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; +} + +declare function alert(message?: string): void; +declare function confirm(message?: string): boolean; +declare function prompt(message?: string, _default?: string): string | null; + +/* + + Web Crypto API + +*/ + +type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; +type KeyType = "private" | "public" | "secret"; +type KeyUsage = + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; +type HashAlgorithmIdentifier = AlgorithmIdentifier; +type NamedCurve = string; + +type BigInteger = Uint8Array; + +interface KeyAlgorithm { + name: string; +} + +interface Algorithm { + name: string; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} + +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + +interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} + +interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; +} + +interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +type AlgorithmIdentifier = Algorithm | string; + +/** + * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). + */ +interface SubtleCrypto { + decrypt( + algorithm: + | AlgorithmIdentifier + | RsaOaepParams + | AesCtrParams + | AesCbcParams + | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise<ArrayBuffer>; + deriveBits( + algorithm: + | AlgorithmIdentifier + | EcdhKeyDeriveParams + | HkdfParams + | Pbkdf2Params, + baseKey: CryptoKey, + length: number, + ): Promise<ArrayBuffer>; + deriveKey( + algorithm: + | AlgorithmIdentifier + | EcdhKeyDeriveParams + | HkdfParams + | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyType: + | AlgorithmIdentifier + | AesDerivedKeyParams + | HmacImportParams + | HkdfParams + | Pbkdf2Params, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise<CryptoKey>; + digest( + algorithm: AlgorithmIdentifier, + data: BufferSource, + ): Promise<ArrayBuffer>; + encrypt( + algorithm: + | AlgorithmIdentifier + | RsaOaepParams + | AesCtrParams + | AesCbcParams + | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise<ArrayBuffer>; + exportKey(format: "jwk", key: CryptoKey): Promise<JsonWebKey>; + exportKey( + format: Exclude<KeyFormat, "jwk">, + key: CryptoKey, + ): Promise<ArrayBuffer>; + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: ReadonlyArray<KeyUsage>, + ): Promise<CryptoKeyPair>; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, + extractable: boolean, + keyUsages: ReadonlyArray<KeyUsage>, + ): Promise<CryptoKey>; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise<CryptoKeyPair | CryptoKey>; + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: ReadonlyArray<KeyUsage>, + ): Promise<CryptoKey>; + importKey( + format: Exclude<KeyFormat, "jwk">, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise<CryptoKey>; + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, + key: CryptoKey, + data: BufferSource, + ): Promise<ArrayBuffer>; + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: + | AlgorithmIdentifier + | RsaOaepParams + | AesCtrParams + | AesCbcParams + | AesGcmParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise<CryptoKey>; + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise<boolean>; + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: + | AlgorithmIdentifier + | RsaOaepParams + | AesCtrParams + | AesCbcParams + | AesGcmParams, + ): Promise<ArrayBuffer>; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new (): SubtleCrypto; +}; + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + +/** + * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. + */ +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: KeyType; + readonly usages: KeyUsage[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new (): CryptoKey; +}; + +interface Position { + lineText: string; + file: string; + namespace: string; + line: number; + column: number; + length: number; + offset: number; +} + +interface ResolveError { + readonly position: Position | null; + readonly code: string; + readonly message: string; + readonly referrer: string; + readonly name: string; + readonly specifier: string; + readonly importKind: + | "entry_point" + | "stmt" + | "require" + | "import" + | "dynamic" + | "require_resolve" + | "at" + | "at_conditional" + | "url" + | "internal"; + + toString(): string; +} + +declare var ResolveError: { + readonly protoype: ResolveError; +}; + +interface BuildError { + readonly position: Position | null; + readonly message: string; + readonly name: string; +} + +declare var BuildError: { + readonly protoype: BuildError; +}; + +// 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: CallSite[]) => any) + | undefined; + + stackTraceLimit: number; +} + +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 | null; + + /** + * 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 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; +} diff --git a/packages/bun-types/header.txt b/packages/bun-types/header.txt new file mode 100644 index 000000000..0488d730a --- /dev/null +++ b/packages/bun-types/header.txt @@ -0,0 +1,8 @@ +// Type definitions for bun {version} +// Project: https://github.com/oven-sh/bun +// Definitions by: Jarred Sumner <https://github.com/Jarred-Sumner> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// <reference no-default-lib="true" /> +/// <reference lib="esnext" /> + +// This file is bundled so that your TypeScript editor integration loads it faster. diff --git a/packages/bun-types/html-rewriter.d.ts b/packages/bun-types/html-rewriter.d.ts new file mode 100644 index 000000000..7f260fd5a --- /dev/null +++ b/packages/bun-types/html-rewriter.d.ts @@ -0,0 +1,113 @@ +declare namespace HTMLRewriterTypes { + interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + } + + interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; + } + + interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: Content, options?: ContentOptions): Text; + after(content: Content, options?: ContentOptions): Text; + replace(content: Content, options?: ContentOptions): Text; + remove(): Text; + } + + interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; + } + + interface DocumentEnd { + append(content: Content, options?: ContentOptions): DocumentEnd; + } + + interface ContentOptions { + html?: boolean; + } + type Content = string; + + interface Comment { + text: string; + readonly removed: boolean; + before(content: Content, options?: ContentOptions): Comment; + after(content: Content, options?: ContentOptions): Comment; + replace(content: Content, options?: ContentOptions): Comment; + remove(): Comment; + } + + interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: Content, options?: ContentOptions): Element; + after(content: Content, options?: ContentOptions): Element; + prepend(content: Content, options?: ContentOptions): Element; + append(content: Content, options?: ContentOptions): Element; + replace(content: Content, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: Content, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; + } + + interface EndTag { + name: string; + before(content: Content, options?: ContentOptions): EndTag; + after(content: Content, options?: ContentOptions): EndTag; + remove(): EndTag; + } +} + +/** + * [HTMLRewriter](https://developers.cloudflare.com/workers/runtime-apis/html-rewriter?bun) is a fast API for transforming HTML. + * + * Bun leverages a native implementation powered by [lol-html](https://github.com/cloudflare/lol-html). + * + * HTMLRewriter can be used to transform HTML in a variety of ways, including: + * * Rewriting URLs + * * Adding meta tags + * * Removing elements + * * Adding elements to the head + * + * @example + * ```ts + * const rewriter = new HTMLRewriter().on('a[href]', { + * element(element: Element) { + * // Rewrite all the URLs to this youtube video + * element.setAttribute('href', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'); + * } + * }); + * rewriter.transform(await fetch("https://remix.run")); + * ``` + */ +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterTypes.HTMLRewriterElementContentHandlers, + ): HTMLRewriter; + onDocument( + handlers: HTMLRewriterTypes.HTMLRewriterDocumentContentHandlers, + ): HTMLRewriter; + /** + * @param input - The HTML to transform + * @returns A new {@link Response} with the transformed HTML + */ + transform(input: Response): Response; +} diff --git a/packages/bun-types/http.d.ts b/packages/bun-types/http.d.ts new file mode 100644 index 000000000..a282b621d --- /dev/null +++ b/packages/bun-types/http.d.ts @@ -0,0 +1,902 @@ +/** + * To use the HTTP server and client one must `require('http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'example.com', + * 'accept': '*' } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders`list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends Dict<string | string[]> { + accept?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends Dict<OutgoingHttpHeader> {} + interface ClientRequestArgs { + signal?: AbortSignal | undefined; + protocol?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + family?: number | undefined; + port?: number | string | null | undefined; + defaultPort?: number | string | undefined; + localAddress?: string | undefined; + socketPath?: string | undefined; + /** + * @default 8192 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + headers?: OutgoingHttpHeaders | undefined; + auth?: string | null | undefined; + timeout?: number | undefined; + setHost?: boolean | undefined; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + */ + class ClientRequest { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @deprecated Since v17.0.0,v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + */ + host: string; + /** + * The request protocol. + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * const http = require('http'); + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * const http = require('http'); + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor( + url: string | URL | ClientRequestArgs, + cb?: (res: IncomingMessage) => void, + ); + /** + * The request method. + */ + method: string; + /** + * The request path. + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Sets a single header value for the header object. + * @param name Header name + * @param value Header value + */ + setHeader( + name: string, + value: number | string | ReadonlyArray<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`. + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Compulsorily flushes the message headers + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + */ + flushHeaders(): void; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", 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: "timeout", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener( + event: "unpipe", + listener: (src: stream.Readable) => void, + ): this; + addListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once(event: "continue", listener: () => void): this; + once( + event: "information", + listener: (info: InformationEvent) => void, + ): this; + once( + event: "response", + listener: (response: IncomingMessage) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener(event: "continue", listener: () => void): this; + prependListener( + event: "information", + listener: (info: InformationEvent) => void, + ): this; + prependListener( + event: "response", + listener: (response: IncomingMessage) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener( + event: "pipe", + listener: (src: stream.Readable) => void, + ): this; + prependListener( + event: "unpipe", + listener: (src: stream.Readable) => void, + ): this; + prependListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener( + event: "information", + listener: (info: InformationEvent) => void, + ): this; + prependOnceListener( + event: "response", + listener: (response: IncomingMessage) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener( + event: "pipe", + listener: (src: stream.Readable) => void, + ): this; + prependOnceListener( + event: "unpipe", + listener: (src: stream.Readable) => void, + ): this; + prependOnceListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + */ + class IncomingMessage extends stream.Readable { + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from <a href="stream.html#class-streamreadable" class="type">stream.Readable</a>. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST' + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + */ + complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.getHeaders()); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with '; '. + * * For all other headers, the values are joined together with ', '. + */ + headers: IncomingHttpHeaders; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + */ + trailers: Dict<string>; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(request.url, `http://${request.getHeaders().host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.getHeaders().host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.getHeaders().host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + */ + destroy(error?: Error): this; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const http = require('http'); + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!' + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData) + * } + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request itself. + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the + * response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!' + * })); + * }); + * + * server.listen(8000); + * ``` + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; +} +declare module "node:http" { + export * from "http"; +} +// XXX: temporary types till theres a proper http(s) module +declare module "https" { + export * from "http"; +} +declare module "node:https" { + export * from "http"; +} diff --git a/packages/bun-types/images/README.md b/packages/bun-types/images/README.md new file mode 100644 index 000000000..c300d46cf --- /dev/null +++ b/packages/bun-types/images/README.md @@ -0,0 +1,15 @@ +Can reference images included here in code comments, ex + +```ts +/** + * ## Large headline + * + * + * **Images** are relative to images/ directory + * + * + */ +export class MyUtil<T = { BOT_TOKEN: string }> { + constructor(public config: T) {} +} +``` diff --git a/packages/bun-types/index.d.ts b/packages/bun-types/index.d.ts new file mode 100644 index 000000000..ea734ffef --- /dev/null +++ b/packages/bun-types/index.d.ts @@ -0,0 +1,36 @@ +/* eslint-disable */ +// Type definitions for bun 0.0 +// Project: https://github.com/oven-sh/bun +// Definitions by: Jarred Sumner <https://github.com/Jarred-Sumner> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// <reference no-default-lib="true" /> +/// <reference lib="esnext" /> +/// <reference path="./bun.d.ts" /> +/// <reference path="./buffer.d.ts" /> +/// <reference path="./sqlite.d.ts" /> +/// <reference path="./ffi.d.ts" /> +/// <reference path="./fs.d.ts" /> +/// <reference path="./fs/promises.d.ts" /> +/// <reference path="./html-rewriter.d.ts" /> +/// <reference path="./globals.d.ts" /> +/// <reference path="./path.d.ts" /> +/// <reference path="./bun-test.d.ts" /> +/// <reference path="./jsc.d.ts" /> +/// <reference path="./assert.d.ts" /> +/// <reference path="./events.d.ts" /> +/// <reference path="./os.d.ts" /> +/// <reference path="./domain.d.ts" /> +/// <reference path="./util.d.ts" /> +/// <reference path="./querystring.d.ts" /> +/// <reference path="./string_decoder.d.ts" /> +/// <reference path="./timers.d.ts" /> +/// <reference path="./stream.d.ts" /> +/// <reference path="./crypto.d.ts" /> +/// <reference path="./child_process.d.ts" /> +/// <reference path="./constants.d.ts" /> +/// <reference path="./url.d.ts" /> +/// <reference path="./tty.d.ts" /> +/// <reference path="./http.d.ts" /> +/// <reference path="./punycode.d.ts" /> +/// <reference path="./zlib.d.ts" /> +/// <reference path="./supports-color.d.ts" /> diff --git a/packages/bun-types/index.js b/packages/bun-types/index.js new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/packages/bun-types/index.js diff --git a/packages/bun-types/jsc.d.ts b/packages/bun-types/jsc.d.ts new file mode 100644 index 000000000..c4dce65df --- /dev/null +++ b/packages/bun-types/jsc.d.ts @@ -0,0 +1,60 @@ +declare module "bun:jsc" { + export function describe(value: any): string; + export function describeArray(args: any[]): string; + export function gcAndSweep(): void; + export function fullGC(): void; + export function edenGC(): void; + export function heapSize(): number; + export function heapStats(): { + heapSize: number; + heapCapacity: number; + extraMemorySize: number; + objectCount: number; + protectedObjectCount: number; + globalObjectCount: number; + protectedGlobalObjectCount: number; + objectTypeCounts: Record<string, number>; + protectedObjectTypeCounts: Record<string, number>; + }; + export function memoryUsage(): { + current: number; + peak: number; + currentCommit: number; + peakCommit: number; + pageFaults: number; + }; + export function getRandomSeed(): number; + export function setRandomSeed(value: number): void; + export function isRope(input: string): boolean; + export function callerSourceOrigin(): string; + export function noFTL(func: Function): Function; + export function noOSRExitFuzzing(func: Function): Function; + export function optimizeNextInvocation(func: Function): Function; + export function numberOfDFGCompiles(func: Function): number; + export function releaseWeakRefs(): void; + export function totalCompileTime(func: Function): number; + export function reoptimizationRetryCount(func: Function): number; + export function drainMicrotasks(): void; + + /** + * This returns objects which native code has explicitly protected from being + * garbage collected + * + * By calling this function you create another reference to the object, which + * will further prevent it from being garbage collected + * + * This function is mostly a debugging tool for bun itself. + * + * Warning: not all objects returned are supposed to be observable from JavaScript + */ + export function getProtectedObjects(): any[]; + + /** + * Start a remote debugging socket server on the given port. + * + * This exposes JavaScriptCore's built-in debugging server. + * + * This is untested. May not be supported yet on macOS + */ + export function startRemoteDebugger(host?: string, port?: number): void; +} diff --git a/packages/bun-types/module.d.ts b/packages/bun-types/module.d.ts new file mode 100644 index 000000000..4a39e0164 --- /dev/null +++ b/packages/bun-types/module.d.ts @@ -0,0 +1,16 @@ +declare module "node:module" { + export * from "module"; +} + +declare module "module" { + export function createRequire(filename: string): NodeJS.Require; + export function _resolveFileName( + path: string, + parent: string, + isMain: boolean, + ): string; + /** + * Bun's module cache is not exposed but this property exists for compatibility. + */ + export var _cache: {}; +} diff --git a/packages/bun-types/os.d.ts b/packages/bun-types/os.d.ts new file mode 100644 index 000000000..a35779000 --- /dev/null +++ b/packages/bun-types/os.d.ts @@ -0,0 +1,437 @@ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo<T> { + username: T; + uid: number; + gid: number; + shell: T; + homedir: T; + } + type NetworkInterfaceInfo = + | NetworkInterfaceInfoIPv4 + | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20 + * } + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + */ + function cpus(): CpuInfo[]; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + */ + function networkInterfaces(): Dict<NetworkInterfaceInfo[]>; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a `SystemError` if a user has no `username` or `homedir`. + */ + function userInfo(options: { encoding: "buffer" }): UserInfo<Buffer>; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo<string>; + type SignalConstants = { + [key in Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to `process.arch`. + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + */ + function platform(): Platform; + /** + * Returns the operating system's default directory for temporary files as a + * string. + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + */ + 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. + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/packages/bun-types/package.json b/packages/bun-types/package.json new file mode 100644 index 000000000..85efdcd56 --- /dev/null +++ b/packages/bun-types/package.json @@ -0,0 +1,18 @@ +{ + "name": "bun-types", + "types": "index.d.ts", + "private": true, + "repository": "https://github.com/oven-sh/bun-types", + "scripts": { + "build": "rm -rf ./dist && bun scripts/bundle.ts ./dist && bun run fmt", + "docs": "bun run build && typedoc", + "test": "tsd" + }, + "devDependencies": { + "tsd": "^0.22.0", + "typedoc": "^0.23.9" + }, + "tsd": { + "directory": "tests" + } +} diff --git a/packages/bun-types/path.d.ts b/packages/bun-types/path.d.ts new file mode 100644 index 000000000..796521b61 --- /dev/null +++ b/packages/bun-types/path.d.ts @@ -0,0 +1,204 @@ +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * import path from 'path'; + * ``` + */ +declare module "path/posix" { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + export function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + export function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + export function resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + export function isAbsolute(p: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + export function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + export function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + export function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + export var sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + export var delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(p: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pP: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + export function toNamespacedPath(path: string): string; +} + +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * import path from 'path'; + * ``` + */ +declare module "path/win32" { + export * from "path/posix"; +} + +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * import path from 'path'; + * ``` + */ +declare module "path" { + export * from "path/posix"; + export * as posix from "path/posix"; + export * as win32 from "path/win32"; +} + +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * import path from 'path'; + * ``` + */ +declare module "node:path" { + export * from "path"; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * import path from 'path'; + * ``` + */ +declare module "node:path/posix" { + export * from "path/posix"; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * import path from 'path'; + * ``` + */ +declare module "node:path/win32" { + export * from "path/win32"; +} diff --git a/packages/bun-types/punycode.d.ts b/packages/bun-types/punycode.d.ts new file mode 100644 index 000000000..14628386c --- /dev/null +++ b/packages/bun-types/punycode.d.ts @@ -0,0 +1,113 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + */ + function toASCII(domain: string): string; + /** + * @deprecated + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: ReadonlyArray<number>): string; + } + /** + * @deprecated + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/packages/bun-types/querystring.d.ts b/packages/bun-types/querystring.d.ts new file mode 100644 index 000000000..429a9ab6a --- /dev/null +++ b/packages/bun-types/querystring.d.ts @@ -0,0 +1,148 @@ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('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/v18.0.0/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends Dict<string | string[]> {} + interface ParsedUrlQueryInput + extends Dict< + | string + | number + | boolean + | ReadonlyArray<string> + | ReadonlyArray<number> + | ReadonlyArray<boolean> + | null + > {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify( + obj?: ParsedUrlQueryInput, + sep?: string, + eq?: string, + options?: StringifyOptions, + ): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```js + * { + * foo: 'bar', + * abc: ['xyz', '123'] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function parse( + str: string, + sep?: string, + eq?: string, + options?: ParseOptions, + ): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + */ + // FIXME: querystring.escape is typed, but not in the polyfill + // function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + */ + // FIXME: querystring.unescape is typed, but not in the polyfill + // function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/packages/bun-types/scripts/bundle.ts b/packages/bun-types/scripts/bundle.ts new file mode 100644 index 000000000..9733352e6 --- /dev/null +++ b/packages/bun-types/scripts/bundle.ts @@ -0,0 +1,72 @@ +import { file, write } from "bun"; +import { mkdirSync } from "fs"; +import { join, resolve } from "path"; +import { getDotTsFiles } from "./utils/getDotTsFiles"; + +// Combine all the .d.ts files into a single .d.ts file +// so that your editor loads the types faster +const BUN_VERSION = ( + process.env.BUN_VERSION || + Bun.version || + process.versions.bun +).replace(/^v/, ""); +const folder = resolve(process.argv.at(-1)!); +if (folder.endsWith("bundle.ts")) { + throw new Error("Pass a folder"); +} + +try { + mkdirSync(folder, { recursive: true }); +} catch (err) { + err; +} + +const header = await file(join(import.meta.dir, "..", "header.txt")).text(); +const filesToCat = (await getDotTsFiles("./")).filter( + (f) => !["./index.d.ts"].some((tf) => f === tf), +); + +const fileContents: string[] = []; + +for (let i = 0; i < filesToCat.length; i++) { + const name = filesToCat[i]; + fileContents.push( + "// " + + name + + "\n\n" + + (await file(resolve(import.meta.dir, "..", name)).text()) + + "\n", + ); +} + +const text = header.replace("{version}", BUN_VERSION) + fileContents.join("\n"); + +const destination = resolve(folder, "types.d.ts"); +await write(destination, text); + +const packageJSON = { + name: process.env.PACKAGE_NAME || "bun-types", + version: BUN_VERSION, + description: + "Type definitions for Bun, an incredibly fast JavaScript runtime", + types: "types.d.ts", + files: ["types.d.ts", "README.md"], + private: false, + keywords: ["bun", "bun.js", "types"], + repository: "https://github.com/oven-sh/bun-types", + homepage: "https://bun.sh", +}; + +await write( + resolve(folder, "package.json"), + JSON.stringify(packageJSON, null, 2) + "\n", +); + +await write( + resolve(folder, "README.md"), + file(resolve(import.meta.dir, "..", "README.md")), +); + +export {}; + +import "../index"; diff --git a/packages/bun-types/scripts/gpr.ts b/packages/bun-types/scripts/gpr.ts new file mode 100644 index 000000000..a17cab4d5 --- /dev/null +++ b/packages/bun-types/scripts/gpr.ts @@ -0,0 +1,11 @@ +/// <reference path="../index.d.ts" /> +import { join } from "path"; +import pkg from "../dist/package.json"; + +const __dirname = new URL(".", import.meta.url).pathname; + +pkg.name = `@oven-sh/${pkg.name}`; +await Bun.write( + join(__dirname, "..", "dist", "package.json"), + JSON.stringify(pkg), +); diff --git a/packages/bun-types/scripts/utils/getDotTsFiles.ts b/packages/bun-types/scripts/utils/getDotTsFiles.ts new file mode 100644 index 000000000..ea9580a9c --- /dev/null +++ b/packages/bun-types/scripts/utils/getDotTsFiles.ts @@ -0,0 +1,25 @@ +import { readdir } from "node:fs/promises"; +import { join } from "node:path"; + +const allDotTsFiles: string[] = []; +export const getDotTsFiles = async ( + prefix = "", + folder: string = join(import.meta.dir, "..", ".."), + folderName?: string, +) => { + const files = await readdir(folder, { withFileTypes: true }); + for await (const file of files) { + if ( + file.isDirectory() && + (file.name === "node_modules" || file.name === "tests") + ) + continue; + + if (file.isDirectory()) + await getDotTsFiles(prefix, join(folder, file.name), file.name); + else if (file.name.endsWith(".d.ts")) + allDotTsFiles.push(prefix + join(folderName || "", file.name)); + } + + return allDotTsFiles; +}; diff --git a/packages/bun-types/sqlite.d.ts b/packages/bun-types/sqlite.d.ts new file mode 100644 index 000000000..e908f0281 --- /dev/null +++ b/packages/bun-types/sqlite.d.ts @@ -0,0 +1,747 @@ +/** + * Fast SQLite3 driver for Bun.js + * @since v0.0.83 + * + * @example + * ```ts + * import { Database } from 'bun:sqlite'; + * + * var db = new Database('app.db'); + * db.query('SELECT * FROM users WHERE name = ?').all('John'); + * // => [{ id: 1, name: 'John' }] + * ``` + * + * The following types can be used when binding parameters: + * + * | JavaScript type | SQLite type | + * | -------------- | ----------- | + * | `string` | `TEXT` | + * | `number` | `INTEGER` or `DECIMAL` | + * | `boolean` | `INTEGER` (1 or 0) | + * | `Uint8Array` | `BLOB` | + * | `Buffer` | `BLOB` | + * | `bigint` | `INTEGER` | + * | `null` | `NULL` | + */ +declare module "bun:sqlite" { + export class Database { + /** + * Open or create a SQLite3 database + * + * @param filename The filename of the database to open. Pass an empty string (`""`) or `":memory:"` or undefined for an in-memory database. + * @param options defaults to `{readwrite: true, create: true}`. If a number, then it's treated as `SQLITE_OPEN_*` constant flags. + * + * @example + * + * ```ts + * const db = new Database("mydb.sqlite"); + * db.run("CREATE TABLE foo (bar TEXT)"); + * db.run("INSERT INTO foo VALUES (?)", "baz"); + * console.log(db.query("SELECT * FROM foo").all()); + * ``` + * + * @example + * + * Open an in-memory database + * + * ```ts + * const db = new Database(":memory:"); + * db.run("CREATE TABLE foo (bar TEXT)"); + * db.run("INSERT INTO foo VALUES (?)", "hiiiiii"); + * console.log(db.query("SELECT * FROM foo").all()); + * ``` + * + * @example + * + * Open read-only + * + * ```ts + * const db = new Database("mydb.sqlite", {readonly: true}); + * ``` + */ + constructor( + filename?: string, + options?: + | number + | { + /** + * Open the database as read-only (no write operations, no create). + * + * Equivalent to {@link constants.SQLITE_OPEN_READONLY} + */ + readonly?: boolean; + /** + * Allow creating a new database + * + * Equivalent to {@link constants.SQLITE_OPEN_CREATE} + */ + create?: boolean; + /** + * Open the database as read-write + * + * Equivalent to {@link constants.SQLITE_OPEN_READWRITE} + */ + readwrite?: boolean; + }, + ); + + /** + * This is an alias of `new Database()` + * + * See {@link Database} + */ + static open( + filename: string, + options?: + | number + | { + /** + * Open the database as read-only (no write operations, no create). + * + * Equivalent to {@link constants.SQLITE_OPEN_READONLY} + */ + readonly?: boolean; + /** + * Allow creating a new database + * + * Equivalent to {@link constants.SQLITE_OPEN_CREATE} + */ + create?: boolean; + /** + * Open the database as read-write + * + * Equivalent to {@link constants.SQLITE_OPEN_READWRITE} + */ + readwrite?: boolean; + }, + ): Database; + + /** + * Execute a SQL query **without returning any results**. + * + * This does not cache the query, so if you want to run a query multiple times, you should use {@link prepare} instead. + * + * @example + * ```ts + * db.run("CREATE TABLE foo (bar TEXT)"); + * db.run("INSERT INTO foo VALUES (?)", "baz"); + * ``` + * + * Useful for queries like: + * - `CREATE TABLE` + * - `INSERT INTO` + * - `UPDATE` + * - `DELETE FROM` + * - `DROP TABLE` + * - `PRAGMA` + * - `ATTACH DATABASE` + * - `DETACH DATABASE` + * - `REINDEX` + * - `VACUUM` + * - `EXPLAIN ANALYZE` + * - `CREATE INDEX` + * - `CREATE TRIGGER` + * - `CREATE VIEW` + * - `CREATE VIRTUAL TABLE` + * - `CREATE TEMPORARY TABLE` + * + * @param sql The SQL query to run + * + * @param bindings Optional bindings for the query + * + * @returns `Database` instance + * + * Under the hood, this calls `sqlite3_prepare_v3` followed by `sqlite3_step` and `sqlite3_finalize`. + * + * * The following types can be used when binding parameters: + * + * | JavaScript type | SQLite type | + * | -------------- | ----------- | + * | `string` | `TEXT` | + * | `number` | `INTEGER` or `DECIMAL` | + * | `boolean` | `INTEGER` (1 or 0) | + * | `Uint8Array` | `BLOB` | + * | `Buffer` | `BLOB` | + * | `bigint` | `INTEGER` | + * | `null` | `NULL` | + */ + run<ParamsType = SQLQueryBindings>( + sqlQuery: string, + ...bindings: ParamsType[] + ): void; + /** + This is an alias of {@link Database.prototype.run} + */ + exec<ParamsType = SQLQueryBindings>( + sqlQuery: string, + ...bindings: ParamsType[] + ): void; + + /** + * Compile a SQL query and return a {@link Statement} object. This is the + * same as {@link prepare} except that it caches the compiled query. + * + * This **does not execute** the query, but instead prepares it for later + * execution and caches the compiled query if possible. + * + * @example + * ```ts + * // compile the query + * const stmt = db.query("SELECT * FROM foo WHERE bar = ?"); + * // run the query + * stmt.all("baz"); + * + * // run the query again + * stmt.all(); + * ``` + * + * @param sql The SQL query to compile + * + * @returns `Statment` instance + * + * Under the hood, this calls `sqlite3_prepare_v3`. + * + */ + query<ParamsType = SQLQueryBindings, ReturnType = any>( + sqlQuery: string, + ): Statement<ParamsType, ReturnType>; + + /** + * Compile a SQL query and return a {@link Statement} object. + * + * This does not cache the compiled query and does not execute the query. + * + * @example + * ```ts + * // compile the query + * const stmt = db.query("SELECT * FROM foo WHERE bar = ?"); + * // run the query + * stmt.all("baz"); + * ``` + * + * @param sql The SQL query to compile + * @param params Optional bindings for the query + * + * @returns `Statment` instance + * + * Under the hood, this calls `sqlite3_prepare_v3`. + * + */ + prepare<ParamsType = SQLQueryBindings, ReturnType = any>( + sql: string, + ...params: ParamsType[] + ): Statement<ParamsType, ReturnType>; + + /** + * Is the database in a transaction? + * + * @returns `true` if the database is in a transaction, `false` otherwise + * + * @example + * ```ts + * db.run("CREATE TABLE foo (bar TEXT)"); + * db.run("INSERT INTO foo VALUES (?)", "baz"); + * db.run("BEGIN"); + * db.run("INSERT INTO foo VALUES (?)", "qux"); + * console.log(db.inTransaction()); + * ``` + */ + get inTransaction(): boolean; + + /** + * Close the database connection. + * + * It is safe to call this method multiple times. If the database is already + * closed, this is a no-op. Running queries after the database has been + * closed will throw an error. + * + * @example + * ```ts + * db.close(); + * ``` + * This is called automatically when the database instance is garbage collected. + * + * Internally, this calls `sqlite3_close_v2`. + */ + close(): void; + + /** + * The filename passed when `new Database()` was called + * @example + * ```ts + * const db = new Database("mydb.sqlite"); + * console.log(db.filename); + * // => "mydb.sqlite" + * ``` + */ + readonly filename: string; + + /** + * The underlying `sqlite3` database handle + * + * In native code, this is not a file descriptor, but an index into an array of database handles + */ + readonly handle: number; + + /** + * Load a SQLite3 extension + * + * macOS requires a custom SQLite3 library to be linked because the Apple build of SQLite for macOS disables loading extensions. See {@link Database.setCustomSQLite} + * + * Bun chooses the Apple build of SQLite on macOS because it brings a ~50% performance improvement. + * + * @param extension name/path of the extension to load + * @param entryPoint optional entry point of the extension + */ + loadExtension(extension: string, entryPoint?: string): void; + + /** + * Change the dynamic library path to SQLite + * + * @note macOS-only + * + * This only works before SQLite is loaded, so + * that's before you call `new Database()`. + * + * It can only be run once because this will load + * the SQLite library into the process. + * + * @param path The path to the SQLite library + * + */ + static setCustomSQLite(path: string): boolean; + + /** + * Creates a function that always runs inside a transaction. When the + * function is invoked, it will begin a new transaction. When the function + * returns, the transaction will be committed. If an exception is thrown, + * the transaction will be rolled back (and the exception will propagate as + * usual). + * + * @param insideTransaction The callback which runs inside a transaction + * + * @example + * ```ts + * // setup + * import { Database } from "bun:sqlite"; + * const db = Database.open(":memory:"); + * db.exec( + * "CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)" + * ); + * + * const insert = db.prepare("INSERT INTO cats (name, age) VALUES ($name, $age)"); + * const insertMany = db.transaction((cats) => { + * for (const cat of cats) insert.run(cat); + * }); + * + * insertMany([ + * { $name: "Joey", $age: 2 }, + * { $name: "Sally", $age: 4 }, + * { $name: "Junior", $age: 1 }, + * ]); + * ``` + */ + transaction(insideTransaction: (...args: any) => void): CallableFunction & { + /** + * uses "BEGIN DEFERRED" + */ + deferred: (...args: any) => void; + /** + * uses "BEGIN IMMEDIATE" + */ + immediate: (...args: any) => void; + /** + * uses "BEGIN EXCLUSIVE" + */ + exclusive: (...args: any) => void; + }; + } + + /** + * A prepared statement. + * + * This is returned by {@link Database.prepare} and {@link Database.query}. + * + * @example + * ```ts + * const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?"); + * stmt.all("baz"); + * // => [{bar: "baz"}] + * ``` + * + * @example + * ```ts + * const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?"); + * stmt.get("baz"); + * // => {bar: "baz"} + * ``` + * + * @example + * ```ts + * const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?"); + * stmt.run("baz"); + * // => undefined + * ``` + */ + export class Statement<ParamsType = SQLQueryBindings, ReturnType = any> { + /** + * Creates a new prepared statement from native code. + * + * This is used internally by the {@link Database} class. Probably you don't need to call this yourself. + */ + constructor(nativeHandle: any); + + /** + * Execute the prepared statement and return all results as objects. + * + * @param params optional values to bind to the statement. If omitted, the statement is run with the last bound values or no parameters if there are none. + * + * @example + * ```ts + * const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?"); + * + * stmt.all("baz"); + * // => [{bar: "baz"}] + * + * stmt.all(); + * // => [{bar: "baz"}] + * + * stmt.all("foo"); + * // => [{bar: "foo"}] + * ``` + */ + all(...params: ParamsType[]): ReturnType[]; + + /** + * Execute the prepared statement and return **the first** result. + * + * If no result is returned, this returns `null`. + * + * @param params optional values to bind to the statement. If omitted, the statement is run with the last bound values or no parameters if there are none. + * + * @example + * ```ts + * const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?"); + * + * stmt.all("baz"); + * // => [{bar: "baz"}] + * + * stmt.all(); + * // => [{bar: "baz"}] + * + * stmt.all("foo"); + * // => [{bar: "foo"}] + * ``` + * + * The following types can be used when binding parameters: + * + * | JavaScript type | SQLite type | + * | -------------- | ----------- | + * | `string` | `TEXT` | + * | `number` | `INTEGER` or `DECIMAL` | + * | `boolean` | `INTEGER` (1 or 0) | + * | `Uint8Array` | `BLOB` | + * | `Buffer` | `BLOB` | + * | `bigint` | `INTEGER` | + * | `null` | `NULL` | + * + */ + get(...params: ParamsType[]): ReturnType | null; + + /** + * Execute the prepared statement. This returns `undefined`. + * + * @param params optional values to bind to the statement. If omitted, the statement is run with the last bound values or no parameters if there are none. + * + * @example + * ```ts + * const stmt = db.prepare("UPDATE foo SET bar = ?"); + * stmt.run("baz"); + * // => undefined + * + * stmt.run(); + * // => undefined + * + * stmt.run("foo"); + * // => undefined + * ``` + * + * The following types can be used when binding parameters: + * + * | JavaScript type | SQLite type | + * | -------------- | ----------- | + * | `string` | `TEXT` | + * | `number` | `INTEGER` or `DECIMAL` | + * | `boolean` | `INTEGER` (1 or 0) | + * | `Uint8Array` | `BLOB` | + * | `Buffer` | `BLOB` | + * | `bigint` | `INTEGER` | + * | `null` | `NULL` | + * + */ + run(...params: ParamsType[]): void; + + /** + * Execute the prepared statement and return the results as an array of arrays. + * + * This is a little faster than {@link all}. + * + * @param params optional values to bind to the statement. If omitted, the statement is run with the last bound values or no parameters if there are none. + * + * @example + * ```ts + * const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?"); + * + * stmt.values("baz"); + * // => [['baz']] + * + * stmt.values(); + * // => [['baz']] + * + * stmt.values("foo"); + * // => [['foo']] + * ``` + * + * The following types can be used when binding parameters: + * + * | JavaScript type | SQLite type | + * | -------------- | ----------- | + * | `string` | `TEXT` | + * | `number` | `INTEGER` or `DECIMAL` | + * | `boolean` | `INTEGER` (1 or 0) | + * | `Uint8Array` | `BLOB` | + * | `Buffer` | `BLOB` | + * | `bigint` | `INTEGER` | + * | `null` | `NULL` | + * + */ + values( + ...params: ParamsType[] + ): Array<Array<string | bigint | number | boolean | Uint8Array>>; + + /** + * The names of the columns returned by the prepared statement. + * @example + * ```ts + * const stmt = db.prepare("SELECT bar FROM foo WHERE bar = ?"); + * + * console.log(stmt.columnNames); + * // => ["bar"] + * ``` + */ + readonly columnNames: string[]; + + /** + * The number of parameters expected in the prepared statement. + * @example + * ```ts + * const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?"); + * console.log(stmt.paramsCount); + * // => 1 + * ``` + * @example + * ```ts + * const stmt = db.prepare("SELECT * FROM foo WHERE bar = ? AND baz = ?"); + * console.log(stmt.paramsCount); + * // => 2 + * ``` + * + */ + readonly paramsCount: number; + + /** + * Finalize the prepared statement, freeing the resources used by the + * statement and preventing it from being executed again. + * + * This is called automatically when the prepared statement is garbage collected. + * + * It is safe to call this multiple times. Calling this on a finalized + * statement has no effect. + * + * Internally, this calls `sqlite3_finalize`. + */ + finalize(): void; + + /** + * Return the expanded SQL string for the prepared statement. + * + * Internally, this calls `sqlite3_expanded_sql()` on the underlying `sqlite3_stmt`. + * + * @example + * ```ts + * const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?", "baz"); + * console.log(stmt.toString()); + * // => "SELECT * FROM foo WHERE bar = 'baz'" + * console.log(stmt); + * // => "SELECT * FROM foo WHERE bar = 'baz'" + * ``` + */ + toString(): string; + + /** + * Native object representing the underlying `sqlite3_stmt` + * + * This is left untyped because the ABI of the native bindings may change at any time. + */ + readonly native: any; + } + + /** + * Constants from `sqlite3.h` + * + * This list isn't exhaustive, but some of the ones which are relevant + */ + export const constants: { + /** + * Open the database as read-only (no write operations, no create). + * @value 0x00000001 + */ + SQLITE_OPEN_READONLY: number; + /** + * Open the database for reading and writing + * @value 0x00000002 + */ + SQLITE_OPEN_READWRITE: number; + /** + * Allow creating a new database + * @value 0x00000004 + */ + SQLITE_OPEN_CREATE: number; + /** + * + * @value 0x00000008 + */ + SQLITE_OPEN_DELETEONCLOSE: number; + /** + * + * @value 0x00000010 + */ + SQLITE_OPEN_EXCLUSIVE: number; + /** + * + * @value 0x00000020 + */ + SQLITE_OPEN_AUTOPROXY: number; + /** + * + * @value 0x00000040 + */ + SQLITE_OPEN_URI: number; + /** + * + * @value 0x00000080 + */ + SQLITE_OPEN_MEMORY: number; + /** + * + * @value 0x00000100 + */ + SQLITE_OPEN_MAIN_DB: number; + /** + * + * @value 0x00000200 + */ + SQLITE_OPEN_TEMP_DB: number; + /** + * + * @value 0x00000400 + */ + SQLITE_OPEN_TRANSIENT_DB: number; + /** + * + * @value 0x00000800 + */ + SQLITE_OPEN_MAIN_JOURNAL: number; + /** + * + * @value 0x00001000 + */ + SQLITE_OPEN_TEMP_JOURNAL: number; + /** + * + * @value 0x00002000 + */ + SQLITE_OPEN_SUBJOURNAL: number; + /** + * + * @value 0x00004000 + */ + SQLITE_OPEN_SUPER_JOURNAL: number; + /** + * + * @value 0x00008000 + */ + SQLITE_OPEN_NOMUTEX: number; + /** + * + * @value 0x00010000 + */ + SQLITE_OPEN_FULLMUTEX: number; + /** + * + * @value 0x00020000 + */ + SQLITE_OPEN_SHAREDCACHE: number; + /** + * + * @value 0x00040000 + */ + SQLITE_OPEN_PRIVATECACHE: number; + /** + * + * @value 0x00080000 + */ + SQLITE_OPEN_WAL: number; + /** + * + * @value 0x01000000 + */ + SQLITE_OPEN_NOFOLLOW: number; + /** + * + * @value 0x02000000 + */ + SQLITE_OPEN_EXRESCODE: number; + /** + * + * @value 0x01 + */ + SQLITE_PREPARE_PERSISTENT: number; + /** + * + * @value 0x02 + */ + SQLITE_PREPARE_NORMALIZE: number; + /** + * + * @value 0x04 + */ + SQLITE_PREPARE_NO_VTAB: number; + }; + + /** + * The native module implementing the sqlite3 C bindings + * + * It is lazily-initialized, so this will return `undefined` until the first + * call to new Database(). + * + * The native module makes no gurantees about ABI stability, so it is left + * untyped + * + * If you need to use it directly for some reason, please let us know because + * that probably points to a deficiency in this API. + * + */ + export var native: any; + + export type SQLQueryBindings = + | string + | bigint + | TypedArray + | number + | boolean + | null + | Record<string, string | bigint | TypedArray | number | boolean | null>; + + export default Database; +} diff --git a/packages/bun-types/stream.d.ts b/packages/bun-types/stream.d.ts new file mode 100644 index 000000000..5962692a0 --- /dev/null +++ b/packages/bun-types/stream.d.ts @@ -0,0 +1,1482 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/stream.js) + */ +declare module "stream" { + import { EventEmitter, Abortable } from "node:events"; + class internal extends EventEmitter { + pipe<T extends WritableStream>( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions<T extends Stream> 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<Readable> { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + class Readable<R = any> extends Stream implements ReadableStream { + // TODO: improve type later + values: any; + + readonly locked: boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions, + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions, + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + forEach( + callbackfn: ( + value: any, + key: number, + parent: ReadableStream<R>, + ) => void, + thisArg?: any, + ): void; + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from( + iterable: Iterable<any> | AsyncIterable<any>, + options?: ReadableOptions, + ): Readable; + /** + * Returns whether the stream has been read from or cancelled. + */ + static isDisturbed(stream: Readable | ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + */ + readable: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + */ + 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`. + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + */ + destroyed: boolean; + 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. + * @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); + * }); + * ``` + * @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. + */ + 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. + */ + 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 + * ``` + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `stream` module API + * as it is currently defined. (See `Compatibility` for more information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @param stream An "old style" readable stream + */ + wrap(stream: ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + _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()`. + * @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<any>; + } + interface WritableOptions extends StreamOptions<Writable> { + 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; + } + class Writable<W = any> extends Stream implements WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored or ended. + */ + 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. + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + */ + 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`. + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + */ + destroyed: 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. + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write( + chunk: any, + callback?: (error: Error | null | undefined) => void, + ): boolean; + write( + chunk: any, + encoding: BufferEncoding, + callback?: (error: Error | null | undefined) => void, + ): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + */ + 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()`. + */ + 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()`. + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener( + event: "pipe", + listener: (src: Readable) => void, + ): this; + prependOnceListener( + event: "unpipe", + listener: (src: Readable) => void, + ): this; + prependOnceListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?( + this: Duplex, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?( + this: Duplex, + error: Error | null, + callback: (error: Error | null) => void, + ): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + */ + class Duplex extends Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `false`. + * + * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is + * emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<any>; + /** + * 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 + | Blob + | ArrayBuffer + | string + | Iterable<any> + | AsyncIterable<any> + | AsyncGeneratorFunction + | Promise<any> + | 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; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?( + this: Transform, + callback: (error?: Error | null) => void, + ): void; + read?(this: Transform, size: number): void; + write?( + this: Transform, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?( + this: Transform, + error: Error | null, + callback: (error: Error | null) => void, + ): void; + transform?( + this: Transform, + chunk: any, + encoding: BufferEncoding, + callback: TransformCallback, + ): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform( + chunk: any, + encoding: BufferEncoding, + callback: TransformCallback, + ): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + * + * ```js + * const fs = require('fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * @param signal A signal representing possible cancellation + * @param stream a stream to attach a signal to + */ + function addAbortSignal<T extends Stream>( + signal: AbortSignal, + stream: T, + ): T; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('stream'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * + * The `finished` API provides promise version: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @return A cleanup function which removes all registered listeners. + */ + function finished( + stream: ReadableStream | WritableStream | ReadWriteStream, + options: FinishedOptions, + callback: (err?: ErrnoException | null) => void, + ): () => void; + function finished( + stream: ReadableStream | WritableStream | ReadWriteStream, + callback: (err?: ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: ReadableStream | WritableStream | ReadWriteStream, + options?: FinishedOptions, + ): Promise<void>; + } + type PipelineSourceFunction<T> = () => Iterable<T> | AsyncIterable<T>; + type PipelineSource<T> = + | Iterable<T> + | AsyncIterable<T> + | ReadableStream + | PipelineSourceFunction<T>; + type PipelineTransform<S extends PipelineTransformSource<any>, U> = + | ReadWriteStream + | (( + source: S extends ( + ...args: any[] + ) => Iterable<infer ST> | AsyncIterable<infer ST> + ? AsyncIterable<ST> + : S, + ) => AsyncIterable<U>); + type PipelineTransformSource<T> = + | PipelineSource<T> + | PipelineTransform<any, T>; + type PipelineDestinationIterableFunction<T> = ( + source: AsyncIterable<T>, + ) => AsyncIterable<any>; + type PipelineDestinationPromiseFunction<T, P> = ( + source: AsyncIterable<T>, + ) => Promise<P>; + type PipelineDestination< + S extends PipelineTransformSource<any>, + P, + > = S extends PipelineTransformSource<infer ST> + ? + | WritableStream + | PipelineDestinationIterableFunction<ST> + | PipelineDestinationPromiseFunction<ST, P> + : never; + type PipelineCallback<S extends PipelineDestination<any, any>> = + S extends PipelineDestinationPromiseFunction<any, infer P> + ? (err: ErrnoException | null, value: P) => void + : (err: ErrnoException | null) => void; + type PipelinePromise<S extends PipelineDestination<any, any>> = + S extends PipelineDestinationPromiseFunction<any, infer P> + ? Promise<P> + : Promise<void>; + interface PipelineOptions { + signal: AbortSignal; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('stream'); + * const fs = require('fs'); + * const zlib = require('zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * } + * ); + * ``` + * + * The `pipeline` API provides a promise version, which can also + * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const signal = ac.signal; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source, { signal }) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * async function* ({ signal }) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * const fs = require('fs'); + * const http = require('http'); + * const { pipeline } = require('stream'); + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @param callback Called when the pipeline is fully done. + */ + function pipeline< + A extends PipelineSource<any>, + B extends PipelineDestination<A, any>, + >( + source: A, + destination: B, + callback?: PipelineCallback<B>, + ): B extends WritableStream ? B : WritableStream; + function pipeline< + A extends PipelineSource<any>, + T1 extends PipelineTransform<A, any>, + B extends PipelineDestination<T1, any>, + >( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback<B>, + ): B extends WritableStream ? B : WritableStream; + function pipeline< + A extends PipelineSource<any>, + T1 extends PipelineTransform<A, any>, + T2 extends PipelineTransform<T1, any>, + B extends PipelineDestination<T2, any>, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback<B>, + ): B extends WritableStream ? B : WritableStream; + function pipeline< + A extends PipelineSource<any>, + T1 extends PipelineTransform<A, any>, + T2 extends PipelineTransform<T1, any>, + T3 extends PipelineTransform<T2, any>, + B extends PipelineDestination<T3, any>, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback?: PipelineCallback<B>, + ): B extends WritableStream ? B : WritableStream; + function pipeline< + A extends PipelineSource<any>, + T1 extends PipelineTransform<A, any>, + T2 extends PipelineTransform<T1, any>, + T3 extends PipelineTransform<T2, any>, + T4 extends PipelineTransform<T3, any>, + B extends PipelineDestination<T4, any>, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback?: PipelineCallback<B>, + ): B extends WritableStream ? B : WritableStream; + function pipeline( + streams: ReadonlyArray<ReadableStream | WritableStream | ReadWriteStream>, + callback?: (err: ErrnoException | null) => void, + ): WritableStream; + function pipeline( + stream1: ReadableStream, + stream2: ReadWriteStream | WritableStream, + ...streams: Array< + | ReadWriteStream + | WritableStream + | ((err: ErrnoException | null) => void) + > + ): WritableStream; + namespace pipeline { + function __promisify__< + A extends PipelineSource<any>, + B extends PipelineDestination<A, any>, + >( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise<B>; + function __promisify__< + A extends PipelineSource<any>, + T1 extends PipelineTransform<A, any>, + B extends PipelineDestination<T1, any>, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise<B>; + function __promisify__< + A extends PipelineSource<any>, + T1 extends PipelineTransform<A, any>, + T2 extends PipelineTransform<T1, any>, + B extends PipelineDestination<T2, any>, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise<B>; + function __promisify__< + A extends PipelineSource<any>, + T1 extends PipelineTransform<A, any>, + T2 extends PipelineTransform<T1, any>, + T3 extends PipelineTransform<T2, any>, + B extends PipelineDestination<T3, any>, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise<B>; + function __promisify__< + A extends PipelineSource<any>, + T1 extends PipelineTransform<A, any>, + T2 extends PipelineTransform<T1, any>, + T3 extends PipelineTransform<T2, any>, + T4 extends PipelineTransform<T3, any>, + B extends PipelineDestination<T4, any>, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise<B>; + function __promisify__( + streams: ReadonlyArray< + ReadableStream | WritableStream | ReadWriteStream + >, + options?: PipelineOptions, + ): Promise<void>; + function __promisify__( + stream1: ReadableStream, + stream2: ReadWriteStream | WritableStream, + ...streams: Array<ReadWriteStream | WritableStream | PipelineOptions> + ): Promise<void>; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + + /** + * Returns whether the stream has encountered an error. + */ + function isErrored( + stream: Readable | Writable | ReadableStream | WritableStream, + ): boolean; + + /** + * Returns whether the stream is readable. + */ + function isReadable(stream: Readable | ReadableStream): boolean; + } + export = internal; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/packages/bun-types/string_decoder.d.ts b/packages/bun-types/string_decoder.d.ts new file mode 100644 index 000000000..a40fa287d --- /dev/null +++ b/packages/bun-types/string_decoder.d.ts @@ -0,0 +1,65 @@ +/** + * 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 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + write(buffer: Buffer): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/packages/bun-types/supports-color.d.ts b/packages/bun-types/supports-color.d.ts new file mode 100644 index 000000000..7f4323b02 --- /dev/null +++ b/packages/bun-types/supports-color.d.ts @@ -0,0 +1,55 @@ +declare module "supports-color" { + export interface Options { + /** + Whether `process.argv` should be sniffed for `--color` and `--no-color` flags. + @default true + */ + readonly sniffFlags?: boolean; + } + + /** + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + export type ColorSupportLevel = 0 | 1 | 2 | 3; + + /** + Detect whether the terminal supports color. + */ + export interface ColorSupport { + /** + The color level. + */ + level: ColorSupportLevel; + + /** + Whether basic 16 colors are supported. + */ + hasBasic: boolean; + + /** + Whether ANSI 256 colors are supported. + */ + has256: boolean; + + /** + Whether Truecolor 16 million colors are supported. + */ + has16m: boolean; + } + + export type ColorInfo = ColorSupport | false; + + export const supportsColor: { + stdout: ColorInfo; + stderr: ColorInfo; + }; + + export const stdout: ColorInfo; + export const stderr: ColorInfo; + + export default supportsColor; +} diff --git a/packages/bun-types/tests/index.d.ts b/packages/bun-types/tests/index.d.ts new file mode 100644 index 000000000..45e52ec7d --- /dev/null +++ b/packages/bun-types/tests/index.d.ts @@ -0,0 +1,5 @@ +/// <reference path="../index.d.ts" /> + +export * as fs from "fs"; +export * as fsPromises from "fs/promises"; +export default Bun; diff --git a/packages/bun-types/tests/index.test-d.ts b/packages/bun-types/tests/index.test-d.ts new file mode 100644 index 000000000..7a2390638 --- /dev/null +++ b/packages/bun-types/tests/index.test-d.ts @@ -0,0 +1,71 @@ +import { ZlibCompressionOptions } from "bun"; +import { expectAssignable, expectType } from "tsd"; +import Bun, { fs, fsPromises } from "."; +// import Bun from "bun"; +// import fs from "fs"; +// import fsPromises from "fs/promises"; + +// Testing ../bun.d.ts + +// FileBlob +expectType<ReadableStream<Uint8Array>>(Bun.file("index.test-d.ts").stream()); +expectType<Promise<ArrayBuffer>>(Bun.file("index.test-d.ts").arrayBuffer()); +expectType<Promise<string>>(Bun.file("index.test-d.ts").text()); + +expectType<number>(Bun.file("index.test-d.ts").size); +expectType<string>(Bun.file("index.test-d.ts").type); + +// Hash +expectType<string>(new Bun.MD4().update("test").digest("hex")); +expectType<string>(new Bun.MD5().update("test").digest("hex")); +expectType<string>(new Bun.SHA1().update("test").digest("hex")); +expectType<string>(new Bun.SHA224().update("test").digest("hex")); +expectType<string>(new Bun.SHA256().update("test").digest("hex")); +expectType<string>(new Bun.SHA384().update("test").digest("hex")); +expectType<string>(new Bun.SHA512().update("test").digest("hex")); +expectType<string>(new Bun.SHA512_256().update("test").digest("hex")); + +// Zlib Functions +expectType<Uint8Array>(Bun.deflateSync(new Uint8Array(128))); +expectType<Uint8Array>(Bun.gzipSync(new Uint8Array(128))); +expectType<Uint8Array>( + Bun.deflateSync(new Uint8Array(128), { + level: -1, + memLevel: 8, + strategy: 0, + windowBits: 15, + }), +); +expectType<Uint8Array>( + Bun.gzipSync(new Uint8Array(128), { level: 9, memLevel: 6, windowBits: 27 }), +); +expectType<Uint8Array>(Bun.inflateSync(new Uint8Array(64))); // Pretend this is DEFLATE compressed data +expectType<Uint8Array>(Bun.gunzipSync(new Uint8Array(64))); // Pretend this is GZIP compressed data +expectAssignable<ZlibCompressionOptions>({ windowBits: -11 }); + +// Other +expectType<Promise<number>>(Bun.write("test.json", "lol")); +expectType<Promise<number>>(Bun.write("test.json", new ArrayBuffer(32))); +expectType<URL>(Bun.pathToFileURL("/foo/bar.txt")); +expectType<string>(Bun.fileURLToPath(new URL("file:///foo/bar.txt"))); + +// Testing ../fs.d.ts +expectType<string>( + fs.readFileSync("./index.d.ts", { encoding: "utf-8" }).toString(), +); +expectType<boolean>(fs.existsSync("./index.d.ts")); +expectType<void>(fs.accessSync("./index.d.ts")); +expectType<void>(fs.appendFileSync("./index.d.ts", "test")); +expectType<void>(fs.mkdirSync("./index.d.ts")); + +// Testing ^promises.d.ts +expectType<string>( + (await fsPromises.readFile("./index.d.ts", { encoding: "utf-8" })).toString(), +); +expectType<Promise<void>>(fsPromises.access("./index.d.ts")); +expectType<Promise<void>>(fsPromises.appendFile("./index.d.ts", "test")); +expectType<Promise<void>>(fsPromises.mkdir("./index.d.ts")); + +Bun.env; + +Bun.version; diff --git a/packages/bun-types/tests/tcp.test-d.ts b/packages/bun-types/tests/tcp.test-d.ts new file mode 100644 index 000000000..9cfcbebda --- /dev/null +++ b/packages/bun-types/tests/tcp.test-d.ts @@ -0,0 +1,132 @@ +import * as Bun from "bun"; + +await Bun.connect({ + data: { arg: "asdf" }, + socket: { + data(socket) { + socket.data.arg.toLocaleLowerCase(); + }, + open() { + console.log("asdf"); + }, + }, + hostname: "adsf", + port: 324, +}); + +await Bun.connect({ + data: { arg: "asdf" }, + socket: { + data(socket) { + socket.data.arg.toLowerCase(); + }, + open() { + console.log("asdf"); + }, + }, + hostname: "adsf", + port: 324, + tls: { + certFile: "asdf", + keyFile: "adsf", + }, +}); + +await Bun.connect({ + data: { arg: "asdf" }, + socket: { + data(socket) { + socket.data.arg.toLowerCase(); + }, + open() { + console.log("asdf"); + }, + }, + unix: "asdf", +}); + +await Bun.connect({ + data: { arg: "asdf" }, + socket: { + data(socket) { + socket.data.arg.toLowerCase(); + }, + open() { + console.log("asdf"); + }, + }, + unix: "asdf", +}); + +Bun.listen({ + data: { arg: "asdf" }, + socket: { + data(socket) { + socket.data.arg.toLowerCase(); + }, + open() { + console.log("asdf"); + }, + }, + hostname: "adsf", + port: 324, +}); + +Bun.listen({ + data: { arg: "asdf" }, + socket: { + data(socket) { + socket.data.arg.toLowerCase(); + }, + open() { + console.log("asdf"); + }, + }, + hostname: "adsf", + port: 324, + tls: { + certFile: "asdf", + keyFile: "adsf", + }, +}); + +Bun.listen({ + data: { arg: "asdf" }, + socket: { + data(socket) { + socket.data.arg.toLowerCase(); + }, + open() { + console.log("asdf"); + }, + }, + unix: "asdf", +}); + +const listener = Bun.listen({ + data: { arg: "asdf" }, + socket: { + data(socket) { + socket.data.arg.toLowerCase(); + }, + open() { + console.log("asdf"); + }, + }, + unix: "asdf", +}); + +listener.data.arg = "asdf"; +// @ts-expect-error arg is string +listener.data.arg = 234; + +// listener.reload({ +// data: {arg: 'asdf'}, +// }); + +listener.reload({ + socket: { + open() {}, + // ...listener. + }, +}); diff --git a/packages/bun-types/timers.d.ts b/packages/bun-types/timers.d.ts new file mode 100644 index 000000000..522ae6a18 --- /dev/null +++ b/packages/bun-types/timers.d.ts @@ -0,0 +1,24 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/timers.js) + */ + +declare module "timers" { + const _exported: { + clearTimeout: typeof clearTimeout; + clearInterval: typeof clearInterval; + setTimeout: typeof setTimeout; + setInterval: typeof setInterval; + }; + export = _exported; +} +declare module "node:timers" { + import timers = require("timers"); + export = timers; +} diff --git a/packages/bun-types/tsconfig.docs.json b/packages/bun-types/tsconfig.docs.json new file mode 100644 index 000000000..05b4cb10b --- /dev/null +++ b/packages/bun-types/tsconfig.docs.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "composite": true, + "emitDeclarationOnly": true, + "lib": [ + "ESNext" + ], + "baseUrl": ".", + "rootDir": ".", + "outFile": "./types.d.ts", + "skipLibCheck": true, + "target": "esnext", + "disableSolutionSearching": true + }, + "include": [ + "./*.d.ts", + "dist" + ], + "exclude": [ + "node_modules", + "./node_modules", + "./node_modules/*", + "./node_modules/@types/node/index.d.ts" + ] +}
\ No newline at end of file diff --git a/packages/bun-types/tsconfig.json b/packages/bun-types/tsconfig.json new file mode 100644 index 000000000..f88d23096 --- /dev/null +++ b/packages/bun-types/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "lib": [ + "ESNext" + ], + "skipLibCheck": true, + "strict": true, + "target": "esnext", + "module": "esnext", + "moduleResolution": "node", + "allowSyntheticDefaultImports": true, + "disableSolutionSearching": true + }, + "exclude": [ + "dist", + "node_modules", + "./node_modules", + "./node_modules/*", + "./node_modules/@types/node/index.d.ts" + ] +}
\ No newline at end of file diff --git a/packages/bun-types/tty.d.ts b/packages/bun-types/tty.d.ts new file mode 100644 index 000000000..49f78fa2c --- /dev/null +++ b/packages/bun-types/tty.d.ts @@ -0,0 +1,17 @@ +declare module "tty" { + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + + // TODO: tty-browserify only polyfills functions that throws errors, wouldn't make sense to have types at the moment + var ReadStream: Function; + var WriteStream: Function; +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/packages/bun-types/typedoc.json b/packages/bun-types/typedoc.json new file mode 100644 index 000000000..0fc79d111 --- /dev/null +++ b/packages/bun-types/typedoc.json @@ -0,0 +1,8 @@ +{ + "media": "images", + "tsconfig": "./tsconfig.docs.json", + "entryPoints": ["./dist/types.d.ts"], + "out": "docs", + "exclude": ["**/node_modules/**"], + "disableSources": true +} diff --git a/packages/bun-types/url.d.ts b/packages/bun-types/url.d.ts new file mode 100644 index 000000000..c63a91174 --- /dev/null +++ b/packages/bun-types/url.d.ts @@ -0,0 +1,347 @@ +/** + * The `url` module provides utilities for URL resolution and parsing. It can be + * accessed using: + * + * ```js + * import url from 'url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/url.js) + */ +declare module "url" { + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * Use of the legacy `url.parse()` method is discouraged. Users should + * use the WHATWG `URL` API. Because the `url.parse()` method uses a + * lenient, non-standard algorithm for parsing URL strings, security + * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and + * incorrect handling of usernames and passwords have been identified. + * + * Deprecation of this API has been shelved for now primarily due to the the + * inability of the [WHATWG API to parse relative URLs](https://github.com/nodejs/node/issues/12682#issuecomment-1154492373). + * [Discussions are ongoing](https://github.com/whatwg/url/issues/531) for the best way to resolve this. + * + * @since v0.1.25 + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: true, + slashesDenoteHost?: boolean, + ): UrlWithParsedQuery; + function parse( + urlString: string, + parseQueryString: boolean, + slashesDenoteHost?: boolean, + ): Url; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('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 + * @deprecated 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('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 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * const url = require('url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @deprecated 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; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string): URL; + interface URLFormatOptions { + auth?: boolean | undefined; + fragment?: boolean | undefined; + search?: boolean | undefined; + unicode?: boolean | undefined; + } + + /** + * The URL interface represents an object providing static methods used for + * creating object URLs. + */ + interface URL { + hash: string; + host: string; + hostname: string; + href: string; + toString(): string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toJSON(): string; + } + + interface URLSearchParams { + /** Appends a specified key/value pair as a new search parameter. */ + append(name: string, value: string): void; + /** Deletes the given search parameter, and its associated value, from the list of all search parameters. */ + delete(name: string): void; + /** Returns the first value associated to the given search parameter. */ + get(name: string): string | null; + /** Returns all the values association with a given search parameter. */ + getAll(name: string): string[]; + /** Returns a Boolean indicating if such a search parameter exists. */ + has(name: string): boolean; + /** Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. */ + set(name: string, value: string): void; + sort(): void; + /** Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */ + toString(): string; + forEach( + callbackfn: (value: string, key: string, parent: URLSearchParams) => void, + thisArg?: any, + ): void; + } +} + +declare module "node:url" { + export * from "url"; +} diff --git a/packages/bun-types/util.d.ts b/packages/bun-types/util.d.ts new file mode 100644 index 000000000..0f9359b10 --- /dev/null +++ b/packages/bun-types/util.d.ts @@ -0,0 +1,1183 @@ +/** + * The `util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/util.js) + */ +declare module "util" { + 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` + */ + getters?: "get" | "set" | boolean | undefined; + showHidden?: boolean | undefined; + /** + * @default 2 + */ + depth?: number | null | undefined; + colors?: boolean | undefined; + customInspect?: boolean | undefined; + showProxy?: boolean | undefined; + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number | undefined; + sorted?: boolean | ((a: string, b: string) => number) | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = ( + depth: number, + options: InspectOptionsStylized, + ) => string; + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`\-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()`returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + */ + // FIXME: util.formatWithOptions is typed, but is not defined in the polyfill + // export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + */ + // FIXME: util.getSystemErrorName is typed, but is not defined in the polyfill + // export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + */ + // FIXME: util.getSystemErrorMap is typed, but is not defined in the polyfill + // export function getSystemErrorMap(): Map<number, [string, string]>; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('util'); + * + * util.log('Timestamped message.'); + * ``` + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + */ + // FIXME: util.toUSVString is typed, but is not defined in the polyfill + // export function toUSVString(string: string): string; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result.`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // <ref *1> { + * // a: [ [Circular *1] ], + * // b: <ref *2> { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]) + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('util'); + * const assert = require('assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]) + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1] + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }) + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * const { inspect } = require('util'); + * + * const thousand = 1_000; + * const million = 1_000_000; + * const bigNumber = 123_456_789n; + * const bigDecimal = 1_234.123_45; + * + * console.log(thousand, million, bigNumber, bigDecimal); + * // 1_000 1_000_000 123_456_789n 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MB. Inputs that result in longer output will + * be truncated. + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect( + object: any, + showHidden?: boolean, + depth?: number | null, + color?: boolean, + ): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * + * ```js + * const util = require('util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and`extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from`superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('util'); + * const EventEmitter = require('events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @deprecated Legacy: Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits( + constructor: unknown, + superConstructor: unknown, + ): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog( + section: string, + callback?: (fn: DebugLoggerFunction) => void, + ): DebugLogger; + export const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined( + object: unknown, + ): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a`DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the`process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation`property take precedence over `--trace-deprecation` and`process.traceDeprecation`. + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate<T extends Function>( + fn: T, + msg: string, + code?: string, + ): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + */ + // FIXME: util.stripVTControlCharacters is typed, but is not defined in the polyfill + // export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named`reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @param original An `async` function + * @return a callback style function + */ + export function callbackify( + fn: () => Promise<void>, + ): (callback: (err: ErrnoException) => void) => void; + export function callbackify<TResult>( + fn: () => Promise<TResult>, + ): (callback: (err: ErrnoException, result: TResult) => void) => void; + export function callbackify<T1>( + fn: (arg1: T1) => Promise<void>, + ): (arg1: T1, callback: (err: ErrnoException) => void) => void; + export function callbackify<T1, TResult>( + fn: (arg1: T1) => Promise<TResult>, + ): ( + arg1: T1, + callback: (err: ErrnoException, result: TResult) => void, + ) => void; + export function callbackify<T1, T2>( + fn: (arg1: T1, arg2: T2) => Promise<void>, + ): (arg1: T1, arg2: T2, callback: (err: ErrnoException) => void) => void; + export function callbackify<T1, T2, TResult>( + fn: (arg1: T1, arg2: T2) => Promise<TResult>, + ): ( + arg1: T1, + arg2: T2, + callback: (err: ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify<T1, T2, T3>( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<void>, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + callback: (err: ErrnoException) => void, + ) => void; + export function callbackify<T1, T2, T3, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + callback: (err: ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify<T1, T2, T3, T4>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: ErrnoException) => void, + ) => void; + export function callbackify<T1, T2, T3, T4, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify<T1, T2, T3, T4, T5>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: ErrnoException) => void, + ) => void; + export function callbackify<T1, T2, T3, T4, T5, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify<T1, T2, T3, T4, T5, T6>( + fn: ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + ) => Promise<void>, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: ErrnoException) => void, + ) => void; + export function callbackify<T1, T2, T3, T4, T5, T6, TResult>( + fn: ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + ) => Promise<TResult>, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy<TCustom extends Function> + extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol<TCustom extends Function> + extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify<TCustom extends Function> = + | CustomPromisifySymbol<TCustom> + | CustomPromisifyLegacy<TCustom>; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()`will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + */ + export function promisify<TCustom extends Function>( + fn: CustomPromisify<TCustom>, + ): TCustom; + export function promisify<TResult>( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise<TResult>; + export function promisify( + fn: (callback: (err?: any) => void) => void, + ): () => Promise<void>; + export function promisify<T1, TResult>( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise<TResult>; + export function promisify<T1>( + fn: (arg1: T1, callback: (err?: any) => void) => void, + ): (arg1: T1) => Promise<void>; + export function promisify<T1, T2, TResult>( + fn: ( + arg1: T1, + arg2: T2, + callback: (err: any, result: TResult) => void, + ) => void, + ): (arg1: T1, arg2: T2) => Promise<TResult>; + export function promisify<T1, T2>( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise<void>; + export function promisify<T1, T2, T3, TResult>( + fn: ( + arg1: T1, + arg2: T2, + arg3: T3, + callback: (err: any, result: TResult) => void, + ) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>; + export function promisify<T1, T2, T3>( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise<void>; + export function promisify<T1, T2, T3, T4, TResult>( + 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<TResult>; + export function promisify<T1, T2, T3, T4>( + fn: ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err?: any) => void, + ) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>; + export function promisify<T1, T2, T3, T4, T5, TResult>( + 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<TResult>; + export function promisify<T1, T2, T3, T4, T5>( + 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<void>; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } +} +declare module "node:util" { + export * from "util"; +} +declare module "sys" { + export * from "util"; +} +declare module "node:sys" { + export * from "util"; +} diff --git a/packages/bun-types/zlib.d.ts b/packages/bun-types/zlib.d.ts new file mode 100644 index 000000000..877350b93 --- /dev/null +++ b/packages/bun-types/zlib.d.ts @@ -0,0 +1,554 @@ +/** + * The `zlib` module provides compression functionality implemented using Gzip, + * Deflate/Inflate, and Brotli. + * + * To access it: + * + * ```js + * const zlib = require('zlib'); + * ``` + * + * Compression and decompression are built around the Node.js `Streams API`. + * + * Compressing or decompressing a stream (such as a file) can be accomplished by + * piping the source stream through a `zlib` `Transform` stream into a destination + * stream: + * + * ```js + * const { createGzip } = require('zlib'); + * const { pipeline } = require('stream'); + * const { + * createReadStream, + * createWriteStream + * } = require('fs'); + * + * const gzip = createGzip(); + * const source = createReadStream('input.txt'); + * const destination = createWriteStream('input.txt.gz'); + * + * pipeline(source, gzip, destination, (err) => { + * if (err) { + * console.error('An error occurred:', err); + * process.exitCode = 1; + * } + * }); + * + * // Or, Promisified + * + * const { promisify } = require('util'); + * const pipe = promisify(pipeline); + * + * async function do_gzip(input, output) { + * const gzip = createGzip(); + * const source = createReadStream(input); + * const destination = createWriteStream(output); + * await pipe(source, gzip, destination); + * } + * + * do_gzip('input.txt', 'input.txt.gz') + * .catch((err) => { + * console.error('An error occurred:', err); + * process.exitCode = 1; + * }); + * ``` + * + * It is also possible to compress or decompress data in a single step: + * + * ```js + * const { deflate, unzip } = require('zlib'); + * + * const input = '.................................'; + * deflate(input, (err, buffer) => { + * if (err) { + * console.error('An error occurred:', err); + * process.exitCode = 1; + * } + * console.log(buffer.toString('base64')); + * }); + * + * const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64'); + * unzip(buffer, (err, buffer) => { + * if (err) { + * console.error('An error occurred:', err); + * process.exitCode = 1; + * } + * console.log(buffer.toString()); + * }); + * + * // Or, Promisified + * + * const { promisify } = require('util'); + * const do_unzip = promisify(unzip); + * + * do_unzip(buffer) + * .then((buf) => console.log(buf.toString())) + * .catch((err) => { + * console.error('An error occurred:', err); + * process.exitCode = 1; + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/zlib.js) + */ +declare module "zlib" { + import * as stream from "node:stream"; + interface ZlibOptions { + /** + * @default constants.Z_NO_FLUSH + */ + flush?: number | undefined; + /** + * @default constants.Z_FINISH + */ + finishFlush?: number | undefined; + /** + * @default 16*1024 + */ + chunkSize?: number | undefined; + windowBits?: number | undefined; + level?: number | undefined; // compression only + memLevel?: number | undefined; // compression only + strategy?: number | undefined; // compression only + dictionary?: ArrayBufferView | ArrayBuffer | undefined; // deflate/inflate only, empty dictionary by default + info?: boolean | undefined; + maxOutputLength?: number | undefined; + } + interface BrotliOptions { + /** + * @default constants.BROTLI_OPERATION_PROCESS + */ + flush?: number | undefined; + /** + * @default constants.BROTLI_OPERATION_FINISH + */ + finishFlush?: number | undefined; + /** + * @default 16*1024 + */ + chunkSize?: number | undefined; + params?: + | { + /** + * Each key is a `constants.BROTLI_*` constant. + */ + [key: number]: boolean | number; + } + | undefined; + maxOutputLength?: number | undefined; + } + interface Zlib { + /** @deprecated Use bytesWritten instead. */ + readonly bytesRead: number; + readonly bytesWritten: number; + shell?: boolean | string | undefined; + flush(kind?: number, callback?: () => void): void; + flush(callback?: () => void): void; + } + interface ZlibParams { + params(level: number, strategy: number, callback: () => void): void; + } + interface ZlibReset { + reset(): void; + } + interface BrotliCompress extends stream.Transform, Zlib {} + interface BrotliDecompress extends stream.Transform, Zlib {} + interface Gzip extends stream.Transform, Zlib {} + interface Gunzip extends stream.Transform, Zlib {} + interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams {} + interface Inflate extends stream.Transform, Zlib, ZlibReset {} + interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams {} + interface InflateRaw extends stream.Transform, Zlib, ZlibReset {} + interface Unzip extends stream.Transform, Zlib {} + /** + * Creates and returns a new `BrotliCompress` object. + */ + function createBrotliCompress(options?: BrotliOptions): BrotliCompress; + /** + * Creates and returns a new `BrotliDecompress` object. + */ + function createBrotliDecompress(options?: BrotliOptions): BrotliDecompress; + /** + * Creates and returns a new `Gzip` object. + * See `example`. + */ + function createGzip(options?: ZlibOptions): Gzip; + /** + * Creates and returns a new `Gunzip` object. + */ + function createGunzip(options?: ZlibOptions): Gunzip; + /** + * Creates and returns a new `Deflate` object. + */ + function createDeflate(options?: ZlibOptions): Deflate; + /** + * Creates and returns a new `Inflate` object. + */ + function createInflate(options?: ZlibOptions): Inflate; + /** + * Creates and returns a new `DeflateRaw` object. + * + * An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when `windowBits`is set to 8 for raw deflate streams. zlib would automatically set `windowBits`to 9 if was initially set to 8\. Newer + * versions of zlib will throw an exception, + * so Node.js restored the original behavior of upgrading a value of 8 to 9, + * since passing `windowBits = 9` to zlib actually results in a compressed stream + * that effectively uses an 8-bit window only. + */ + function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + /** + * Creates and returns a new `InflateRaw` object. + */ + function createInflateRaw(options?: ZlibOptions): InflateRaw; + /** + * Creates and returns a new `Unzip` object. + */ + function createUnzip(options?: ZlibOptions): Unzip; + type InputType = string | ArrayBuffer | ArrayBufferView; + type CompressCallback = (error: Error | null, result: Buffer) => void; + /** + */ + function brotliCompress( + buf: InputType, + options: BrotliOptions, + callback: CompressCallback, + ): void; + function brotliCompress(buf: InputType, callback: CompressCallback): void; + namespace brotliCompress { + function __promisify__( + buffer: InputType, + options?: BrotliOptions, + ): Promise<Buffer>; + } + /** + * Compress a chunk of data with `BrotliCompress`. + */ + function brotliCompressSync(buf: InputType, options?: BrotliOptions): Buffer; + /** + */ + function brotliDecompress( + buf: InputType, + options: BrotliOptions, + callback: CompressCallback, + ): void; + function brotliDecompress(buf: InputType, callback: CompressCallback): void; + namespace brotliDecompress { + function __promisify__( + buffer: InputType, + options?: BrotliOptions, + ): Promise<Buffer>; + } + /** + * Decompress a chunk of data with `BrotliDecompress`. + */ + function brotliDecompressSync( + buf: InputType, + options?: BrotliOptions, + ): Buffer; + /** + */ + function deflate(buf: InputType, callback: CompressCallback): void; + function deflate( + buf: InputType, + options: ZlibOptions, + callback: CompressCallback, + ): void; + namespace deflate { + function __promisify__( + buffer: InputType, + options?: ZlibOptions, + ): Promise<Buffer>; + } + /** + * Compress a chunk of data with `Deflate`. + */ + function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; + /** + */ + function deflateRaw(buf: InputType, callback: CompressCallback): void; + function deflateRaw( + buf: InputType, + options: ZlibOptions, + callback: CompressCallback, + ): void; + namespace deflateRaw { + function __promisify__( + buffer: InputType, + options?: ZlibOptions, + ): Promise<Buffer>; + } + /** + * Compress a chunk of data with `DeflateRaw`. + */ + function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + /** + */ + function gzip(buf: InputType, callback: CompressCallback): void; + function gzip( + buf: InputType, + options: ZlibOptions, + callback: CompressCallback, + ): void; + namespace gzip { + function __promisify__( + buffer: InputType, + options?: ZlibOptions, + ): Promise<Buffer>; + } + /** + * Compress a chunk of data with `Gzip`. + */ + function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; + /** + */ + function gunzip(buf: InputType, callback: CompressCallback): void; + function gunzip( + buf: InputType, + options: ZlibOptions, + callback: CompressCallback, + ): void; + namespace gunzip { + function __promisify__( + buffer: InputType, + options?: ZlibOptions, + ): Promise<Buffer>; + } + /** + * Decompress a chunk of data with `Gunzip`. + */ + function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; + /** + */ + function inflate(buf: InputType, callback: CompressCallback): void; + function inflate( + buf: InputType, + options: ZlibOptions, + callback: CompressCallback, + ): void; + namespace inflate { + function __promisify__( + buffer: InputType, + options?: ZlibOptions, + ): Promise<Buffer>; + } + /** + * Decompress a chunk of data with `Inflate`. + */ + function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; + /** + */ + function inflateRaw(buf: InputType, callback: CompressCallback): void; + function inflateRaw( + buf: InputType, + options: ZlibOptions, + callback: CompressCallback, + ): void; + namespace inflateRaw { + function __promisify__( + buffer: InputType, + options?: ZlibOptions, + ): Promise<Buffer>; + } + /** + * Decompress a chunk of data with `InflateRaw`. + */ + function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + /** + */ + function unzip(buf: InputType, callback: CompressCallback): void; + function unzip( + buf: InputType, + options: ZlibOptions, + callback: CompressCallback, + ): void; + namespace unzip { + function __promisify__( + buffer: InputType, + options?: ZlibOptions, + ): Promise<Buffer>; + } + /** + * Decompress a chunk of data with `Unzip`. + */ + function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; + namespace constants { + const BROTLI_DECODE: number; + const BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: number; + const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: number; + const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: number; + const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: number; + const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: number; + const BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: number; + const BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: number; + const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: number; + const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: number; + const BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: number; + const BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: number; + const BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: number; + const BROTLI_DECODER_ERROR_FORMAT_DISTANCE: number; + const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: number; + const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: number; + const BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: number; + const BROTLI_DECODER_ERROR_FORMAT_PADDING_1: number; + const BROTLI_DECODER_ERROR_FORMAT_PADDING_2: number; + const BROTLI_DECODER_ERROR_FORMAT_RESERVED: number; + const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: number; + const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: number; + const BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: number; + const BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: number; + const BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: number; + const BROTLI_DECODER_ERROR_UNREACHABLE: number; + const BROTLI_DECODER_NEEDS_MORE_INPUT: number; + const BROTLI_DECODER_NEEDS_MORE_OUTPUT: number; + const BROTLI_DECODER_NO_ERROR: number; + const BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: number; + const BROTLI_DECODER_PARAM_LARGE_WINDOW: number; + const BROTLI_DECODER_RESULT_ERROR: number; + const BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: number; + const BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: number; + const BROTLI_DECODER_RESULT_SUCCESS: number; + const BROTLI_DECODER_SUCCESS: number; + const BROTLI_DEFAULT_MODE: number; + const BROTLI_DEFAULT_QUALITY: number; + const BROTLI_DEFAULT_WINDOW: number; + const BROTLI_ENCODE: number; + const BROTLI_LARGE_MAX_WINDOW_BITS: number; + const BROTLI_MAX_INPUT_BLOCK_BITS: number; + const BROTLI_MAX_QUALITY: number; + const BROTLI_MAX_WINDOW_BITS: number; + const BROTLI_MIN_INPUT_BLOCK_BITS: number; + const BROTLI_MIN_QUALITY: number; + const BROTLI_MIN_WINDOW_BITS: number; + const BROTLI_MODE_FONT: number; + const BROTLI_MODE_GENERIC: number; + const BROTLI_MODE_TEXT: number; + const BROTLI_OPERATION_EMIT_METADATA: number; + const BROTLI_OPERATION_FINISH: number; + const BROTLI_OPERATION_FLUSH: number; + const BROTLI_OPERATION_PROCESS: number; + const BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: number; + const BROTLI_PARAM_LARGE_WINDOW: number; + const BROTLI_PARAM_LGBLOCK: number; + const BROTLI_PARAM_LGWIN: number; + const BROTLI_PARAM_MODE: number; + const BROTLI_PARAM_NDIRECT: number; + const BROTLI_PARAM_NPOSTFIX: number; + const BROTLI_PARAM_QUALITY: number; + const BROTLI_PARAM_SIZE_HINT: number; + const DEFLATE: number; + const DEFLATERAW: number; + const GUNZIP: number; + const GZIP: number; + const INFLATE: number; + const INFLATERAW: number; + const UNZIP: number; + // Allowed flush values. + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + // Return codes for the compression/decompression functions. + // Negative values are errors, positive values are used for special but normal events. + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + // Compression levels. + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + // Compression strategy. + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + const Z_DEFAULT_WINDOWBITS: number; + const Z_MIN_WINDOWBITS: number; + const Z_MAX_WINDOWBITS: number; + const Z_MIN_CHUNK: number; + const Z_MAX_CHUNK: number; + const Z_DEFAULT_CHUNK: number; + const Z_MIN_MEMLEVEL: number; + const Z_MAX_MEMLEVEL: number; + const Z_DEFAULT_MEMLEVEL: number; + const Z_MIN_LEVEL: number; + const Z_MAX_LEVEL: number; + const Z_DEFAULT_LEVEL: number; + const ZLIB_VERNUM: number; + } + // Allowed flush values. + /** @deprecated Use `constants.Z_NO_FLUSH` */ + const Z_NO_FLUSH: number; + /** @deprecated Use `constants.Z_PARTIAL_FLUSH` */ + const Z_PARTIAL_FLUSH: number; + /** @deprecated Use `constants.Z_SYNC_FLUSH` */ + const Z_SYNC_FLUSH: number; + /** @deprecated Use `constants.Z_FULL_FLUSH` */ + const Z_FULL_FLUSH: number; + /** @deprecated Use `constants.Z_FINISH` */ + const Z_FINISH: number; + /** @deprecated Use `constants.Z_BLOCK` */ + const Z_BLOCK: number; + /** @deprecated Use `constants.Z_TREES` */ + const Z_TREES: number; + // Return codes for the compression/decompression functions. + // Negative values are errors, positive values are used for special but normal events. + /** @deprecated Use `constants.Z_OK` */ + const Z_OK: number; + /** @deprecated Use `constants.Z_STREAM_END` */ + const Z_STREAM_END: number; + /** @deprecated Use `constants.Z_NEED_DICT` */ + const Z_NEED_DICT: number; + /** @deprecated Use `constants.Z_ERRNO` */ + const Z_ERRNO: number; + /** @deprecated Use `constants.Z_STREAM_ERROR` */ + const Z_STREAM_ERROR: number; + /** @deprecated Use `constants.Z_DATA_ERROR` */ + const Z_DATA_ERROR: number; + /** @deprecated Use `constants.Z_MEM_ERROR` */ + const Z_MEM_ERROR: number; + /** @deprecated Use `constants.Z_BUF_ERROR` */ + const Z_BUF_ERROR: number; + /** @deprecated Use `constants.Z_VERSION_ERROR` */ + const Z_VERSION_ERROR: number; + // Compression levels. + /** @deprecated Use `constants.Z_NO_COMPRESSION` */ + const Z_NO_COMPRESSION: number; + /** @deprecated Use `constants.Z_BEST_SPEED` */ + const Z_BEST_SPEED: number; + /** @deprecated Use `constants.Z_BEST_COMPRESSION` */ + const Z_BEST_COMPRESSION: number; + /** @deprecated Use `constants.Z_DEFAULT_COMPRESSION` */ + const Z_DEFAULT_COMPRESSION: number; + // Compression strategy. + /** @deprecated Use `constants.Z_FILTERED` */ + const Z_FILTERED: number; + /** @deprecated Use `constants.Z_HUFFMAN_ONLY` */ + const Z_HUFFMAN_ONLY: number; + /** @deprecated Use `constants.Z_RLE` */ + const Z_RLE: number; + /** @deprecated Use `constants.Z_FIXED` */ + const Z_FIXED: number; + /** @deprecated Use `constants.Z_DEFAULT_STRATEGY` */ + const Z_DEFAULT_STRATEGY: number; + /** @deprecated */ + const Z_BINARY: number; + /** @deprecated */ + const Z_TEXT: number; + /** @deprecated */ + const Z_ASCII: number; + /** @deprecated */ + const Z_UNKNOWN: number; + /** @deprecated */ + const Z_DEFLATED: number; +} +declare module "node:zlib" { + export * from "zlib"; +} diff --git a/packages/bun-wasm/bun.lockb b/packages/bun-wasm/bun.lockb Binary files differindex ff9d2fad6..5785108fc 100755 --- a/packages/bun-wasm/bun.lockb +++ b/packages/bun-wasm/bun.lockb diff --git a/packages/bun-wasm/index.ts b/packages/bun-wasm/index.ts index d886a2cda..b72400661 100644 --- a/packages/bun-wasm/index.ts +++ b/packages/bun-wasm/index.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { ByteBuffer } from "peechy/bb"; import { decodeScanResult, @@ -189,7 +190,7 @@ export class Bun { if (globalThis?.WebAssembly?.instantiateStreaming) { Bun.wasm_source = await globalThis.WebAssembly.instantiateStreaming( fetch(url), - { env: env, wasi_snapshot_preview1: Wasi } + { env: env, wasi_snapshot_preview1: Wasi }, ); } else if (typeof window !== "undefined") { const resp = await fetch(url); @@ -198,7 +199,7 @@ export class Bun { { env: env, wasi_snapshot_preview1: Wasi, - } + }, ); // is it node? } else { @@ -210,7 +211,7 @@ export class Bun { { env: env, wasi_snapshot_preview1: Wasi, - } + }, ); } @@ -225,7 +226,7 @@ export class Bun { static transformSync( content: Uint8Array | string, file_name: string, - loader?: Loader + loader?: Loader, ): TransformResponse { if (!Bun.has_initialized) { throw "Please run await Bun.init(wasm_url) before using this."; @@ -264,7 +265,7 @@ export class Bun { // @ts-ignore loader: normalizeLoader(file_name, loader), }, - bb + bb, ); const data = bb.toUint8Array(); @@ -285,7 +286,7 @@ export class Bun { static scan( content: Uint8Array | string, file_name: string, - loader?: Loader + loader?: Loader, ): ScanResult { if (!Bun.has_initialized) { throw "Please run await Bun.init(wasm_url) before using this."; @@ -316,7 +317,7 @@ export class Bun { // @ts-ignore loader: normalizeLoader(file_name, loader), }, - bb + bb, ); const data = bb.toUint8Array(); diff --git a/src/.prettierignore b/src/.prettierignore deleted file mode 100644 index b50b4c262..000000000 --- a/src/.prettierignore +++ /dev/null @@ -1 +0,0 @@ -fallback.html
\ No newline at end of file diff --git a/src/api/bun.lockb b/src/api/bun.lockb Binary files differindex 90a1dd4c9..7d9cafc34 100755 --- a/src/api/bun.lockb +++ b/src/api/bun.lockb diff --git a/src/api/demo/bun.lockb b/src/api/demo/bun.lockb Binary files differindex 7d3f87eb3..1c5c6e269 100755 --- a/src/api/demo/bun.lockb +++ b/src/api/demo/bun.lockb diff --git a/src/api/demo/lib/api.ts b/src/api/demo/lib/api.ts index 455c73290..d06bfd35b 100644 --- a/src/api/demo/lib/api.ts +++ b/src/api/demo/lib/api.ts @@ -152,7 +152,7 @@ export class Bun { Bun.wasm_source = await globalThis.WebAssembly.instantiateStreaming( fetch(url), - { env: Bun[wasm_imports_sym], wasi_snapshot_preview1: Wasi } + { env: Bun[wasm_imports_sym], wasi_snapshot_preview1: Wasi }, ); const res = Bun.wasm_exports.init(); @@ -209,7 +209,7 @@ export class Bun { ".json": Loader.json, }[path.extname(file_name)], }, - bb + bb, ); const data = bb.toUint8Array(); @@ -225,7 +225,11 @@ export class Bun { return response; } - static scan(content: Uint8Array | string, file_name: string, loader: Loader) { + static scan( + content: Uint8Array | string, + file_name: string, + loader?: Loader, + ) { if (!Bun.has_initialized) { throw "Please run await Bun.init(wasm_url) before using this."; } @@ -262,7 +266,7 @@ export class Bun { ".json": Loader.json, }[path.extname(file_name)], }, - bb + bb, ); const data = bb.toUint8Array(); diff --git a/src/api/demo/lib/run.ts b/src/api/demo/lib/run.ts index 8337eb2c9..87d703556 100644 --- a/src/api/demo/lib/run.ts +++ b/src/api/demo/lib/run.ts @@ -27,7 +27,7 @@ const swcOptions = { }; export async function transform(contents, file) { - var result = { + var result: any = { timings: { esbuild: 0, bun: 0, @@ -59,7 +59,7 @@ export async function transform(contents, file) { } result.timings.swc = performance.now(); - result.swc = transformSyncSWC(contents, swcOptions); + result.swc = transformSyncSWC(contents, swcOptions as any); result.timings.swc = performance.now() - result.timings.swc; console.log("esbuild:", result.timings.esbuild, "ms"); diff --git a/src/api/demo/lib/scan.ts b/src/api/demo/lib/scan.ts index 4d16d5b8c..c2fd7bb12 100644 --- a/src/api/demo/lib/scan.ts +++ b/src/api/demo/lib/scan.ts @@ -23,7 +23,7 @@ const swcOptions = { }; export async function transform(contents, file) { - var result = { + var result: any = { timings: { lexer: 0, bun: 0, diff --git a/src/api/demo/next-env.d.ts b/src/api/demo/next-env.d.ts index 7b7aa2c77..4f11a03dc 100644 --- a/src/api/demo/next-env.d.ts +++ b/src/api/demo/next-env.d.ts @@ -1,2 +1,5 @@ /// <reference types="next" /> -/// <reference types="next/types/global" /> +/// <reference types="next/image-types/global" /> + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/src/api/demo/package-lock.json b/src/api/demo/package-lock.json index 9b83211cb..bf3924fb5 100644 --- a/src/api/demo/package-lock.json +++ b/src/api/demo/package-lock.json @@ -4378,6 +4378,201 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/@next/swc-android-arm-eabi": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-android-arm-eabi/-/swc-android-arm-eabi-12.3.2.tgz", + "integrity": "sha512-r2rrz+DZ8YYGqzVrbRrpP6GKzwozpOrnFbErc4k36vUTSFMag9yQahZfaBe06JYdqu/e5yhm/saIDEaSVPRP4g==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-android-arm64": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-android-arm64/-/swc-android-arm64-12.3.2.tgz", + "integrity": "sha512-B+TINJhCf+CrY1+b3/JWQlkecv53rAGa/gA7gi5B1cnBa/2Uvoe+Ue0JeCefTjfiyl1ScsyNx+NcESY8Ye2Ngg==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-darwin-arm64": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-12.3.2.tgz", + "integrity": "sha512-PTUfe1ZrwjsiuTmr3bOM9lsoy5DCmfYsLOUF9ZVhtbi5MNJVmUTy4VZ06GfrvnCO5hGCr48z3vpFE9QZ0qLcPw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-darwin-x64": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-12.3.2.tgz", + "integrity": "sha512-1HkjmS9awwlaeEY8Y01nRSNkSv3y+qnC/mjMPe/W66hEh3QKa/LQHqHeS7NOdEs19B2mhZ7w+EgMRXdLQ0Su8w==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-freebsd-x64": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-freebsd-x64/-/swc-freebsd-x64-12.3.2.tgz", + "integrity": "sha512-h5Mx0BKDCJ5Vu/U8e07esF6PjPv1EJgmRbYWTUZMAflu13MQpCJkKEJir7+BeRfTXRfgFf+llc7uocrpd7mcrg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm-gnueabihf": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm-gnueabihf/-/swc-linux-arm-gnueabihf-12.3.2.tgz", + "integrity": "sha512-EuRZAamoxfe/WoWRaC0zsCAoE4gs/mEhilcloNM4J5Mnb3PLY8PZV394W7t5tjBjItMCF7l2Ebwjwtm46tq2RA==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-gnu": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-12.3.2.tgz", + "integrity": "sha512-T9GCFyOIb4S3acA9LqflUYD+QZ94iZketHCqKdoO0Nx0OCHIgGJV5rotDe8TDXwh/goYpIfyHU4j1qqw4w4VnA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-musl": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-12.3.2.tgz", + "integrity": "sha512-hxNVZS6L3c2z3l9EH2GP0MGQ9exu6O8cohYNZyqC9WUl6C03sEn8xzDH1y+NgD3fVurvYkGU5F0PDddJJLfDIw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-gnu": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-12.3.2.tgz", + "integrity": "sha512-fCPkLuwDwY8/QeXxciJJjDHG09liZym/Bhb4A+RLFQ877wUkwFsNWDUTSdUx0YXlYK/1gf67BKauqKkOKp6CYw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-musl": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-12.3.2.tgz", + "integrity": "sha512-o+GifBIQ2K+/MEFxHsxUZoU3bsuVFLXZYWd3idimFHiVdDCVYiKsY6mYMmKDlucX+9xRyOCkKL9Tjf+3tuXJpw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-arm64-msvc": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-12.3.2.tgz", + "integrity": "sha512-crii66irzGGMSUR0L8r9+A06eTv7FTXqw4rgzJ33M79EwQJOdpY7RVKXLQMurUhniEeQEEOfamiEdPIi/qxisw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-ia32-msvc": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-12.3.2.tgz", + "integrity": "sha512-5hRUSvn3MdQ4nVRu1rmKxq5YJzpTtZfaC/NyGw6wa4NSF1noUn/pdQGUr+I5Qz3CZkd1gZzzC0eaXQHlrk0E2g==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-x64-msvc": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-12.3.2.tgz", + "integrity": "sha512-tpQJYUH+TzPMIsdVl9fH8uDg47iwiNjKY+8e9da3dXqlkztKzjSw0OwSADoqh3KrifplXeKSta+BBGLdBqg3sg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } } }, "dependencies": { @@ -7575,6 +7770,84 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==" + }, + "@next/swc-android-arm-eabi": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-android-arm-eabi/-/swc-android-arm-eabi-12.3.2.tgz", + "integrity": "sha512-r2rrz+DZ8YYGqzVrbRrpP6GKzwozpOrnFbErc4k36vUTSFMag9yQahZfaBe06JYdqu/e5yhm/saIDEaSVPRP4g==", + "optional": true + }, + "@next/swc-android-arm64": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-android-arm64/-/swc-android-arm64-12.3.2.tgz", + "integrity": "sha512-B+TINJhCf+CrY1+b3/JWQlkecv53rAGa/gA7gi5B1cnBa/2Uvoe+Ue0JeCefTjfiyl1ScsyNx+NcESY8Ye2Ngg==", + "optional": true + }, + "@next/swc-darwin-arm64": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-12.3.2.tgz", + "integrity": "sha512-PTUfe1ZrwjsiuTmr3bOM9lsoy5DCmfYsLOUF9ZVhtbi5MNJVmUTy4VZ06GfrvnCO5hGCr48z3vpFE9QZ0qLcPw==", + "optional": true + }, + "@next/swc-darwin-x64": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-12.3.2.tgz", + "integrity": "sha512-1HkjmS9awwlaeEY8Y01nRSNkSv3y+qnC/mjMPe/W66hEh3QKa/LQHqHeS7NOdEs19B2mhZ7w+EgMRXdLQ0Su8w==", + "optional": true + }, + "@next/swc-freebsd-x64": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-freebsd-x64/-/swc-freebsd-x64-12.3.2.tgz", + "integrity": "sha512-h5Mx0BKDCJ5Vu/U8e07esF6PjPv1EJgmRbYWTUZMAflu13MQpCJkKEJir7+BeRfTXRfgFf+llc7uocrpd7mcrg==", + "optional": true + }, + "@next/swc-linux-arm-gnueabihf": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm-gnueabihf/-/swc-linux-arm-gnueabihf-12.3.2.tgz", + "integrity": "sha512-EuRZAamoxfe/WoWRaC0zsCAoE4gs/mEhilcloNM4J5Mnb3PLY8PZV394W7t5tjBjItMCF7l2Ebwjwtm46tq2RA==", + "optional": true + }, + "@next/swc-linux-arm64-gnu": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-12.3.2.tgz", + "integrity": "sha512-T9GCFyOIb4S3acA9LqflUYD+QZ94iZketHCqKdoO0Nx0OCHIgGJV5rotDe8TDXwh/goYpIfyHU4j1qqw4w4VnA==", + "optional": true + }, + "@next/swc-linux-arm64-musl": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-12.3.2.tgz", + "integrity": "sha512-hxNVZS6L3c2z3l9EH2GP0MGQ9exu6O8cohYNZyqC9WUl6C03sEn8xzDH1y+NgD3fVurvYkGU5F0PDddJJLfDIw==", + "optional": true + }, + "@next/swc-linux-x64-gnu": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-12.3.2.tgz", + "integrity": "sha512-fCPkLuwDwY8/QeXxciJJjDHG09liZym/Bhb4A+RLFQ877wUkwFsNWDUTSdUx0YXlYK/1gf67BKauqKkOKp6CYw==", + "optional": true + }, + "@next/swc-linux-x64-musl": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-12.3.2.tgz", + "integrity": "sha512-o+GifBIQ2K+/MEFxHsxUZoU3bsuVFLXZYWd3idimFHiVdDCVYiKsY6mYMmKDlucX+9xRyOCkKL9Tjf+3tuXJpw==", + "optional": true + }, + "@next/swc-win32-arm64-msvc": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-12.3.2.tgz", + "integrity": "sha512-crii66irzGGMSUR0L8r9+A06eTv7FTXqw4rgzJ33M79EwQJOdpY7RVKXLQMurUhniEeQEEOfamiEdPIi/qxisw==", + "optional": true + }, + "@next/swc-win32-ia32-msvc": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-12.3.2.tgz", + "integrity": "sha512-5hRUSvn3MdQ4nVRu1rmKxq5YJzpTtZfaC/NyGw6wa4NSF1noUn/pdQGUr+I5Qz3CZkd1gZzzC0eaXQHlrk0E2g==", + "optional": true + }, + "@next/swc-win32-x64-msvc": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-12.3.2.tgz", + "integrity": "sha512-tpQJYUH+TzPMIsdVl9fH8uDg47iwiNjKY+8e9da3dXqlkztKzjSw0OwSADoqh3KrifplXeKSta+BBGLdBqg3sg==", + "optional": true } } } diff --git a/src/api/demo/package.json b/src/api/demo/package.json index ac452254a..59e70aed1 100644 --- a/src/api/demo/package.json +++ b/src/api/demo/package.json @@ -14,13 +14,14 @@ "esbuild": "^0.14.23", "esbuild-wasm": "^0.14.23", "next": "12", - "peechy": "latest", + "peechy": "0.4.32", "react": "17.0.2", "react-dom": "17.0.2", "sucrase": "^3.18.1" }, "devDependencies": { "@types/react": "^17.0.8", + "bun-types": "^0.2.2", "typescript": "^4.3.2", "webpack": "^5.38.1", "webpack-cli": "^4.7.0" diff --git a/src/api/demo/pages/_app.js b/src/api/demo/pages/_app.js index 1e1cec924..2fc3e0700 100644 --- a/src/api/demo/pages/_app.js +++ b/src/api/demo/pages/_app.js @@ -1,7 +1,7 @@ -import '../styles/globals.css' +import "../styles/globals.css"; function MyApp({ Component, pageProps }) { - return <Component {...pageProps} /> + return <Component {...pageProps} />; } -export default MyApp +export default MyApp; diff --git a/src/api/demo/pages/api/hello.js b/src/api/demo/pages/api/hello.js index 9987aff4c..e963280fa 100644 --- a/src/api/demo/pages/api/hello.js +++ b/src/api/demo/pages/api/hello.js @@ -1,5 +1,5 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction export default (req, res) => { - res.status(200).json({ name: 'John Doe' }) -} + res.status(200).json({ name: "John Doe" }); +}; diff --git a/src/api/demo/pages/index.tsx b/src/api/demo/pages/index.tsx index 7274b3d39..24577acb3 100644 --- a/src/api/demo/pages/index.tsx +++ b/src/api/demo/pages/index.tsx @@ -1,19 +1,22 @@ import Head from "next/head"; import Image from "next/image"; import styles from "../styles/Home.module.css"; +import { readFile } from "fs/promises"; import React from "react"; if (typeof window !== "undefined") { globalThis.Run = await import("../lib/run"); - await import("../lib/api.ts"); + await import("../lib/api"); } export async function getStaticProps(ctx) { return { props: { - code: Bun.readFile( - "/Users/jarred/Build/es-module-lexer/test/samples/magic-string.js" + // not tested + code: readFile( + "/Users/jarred/Build/es-module-lexer/test/samples/magic-string.js", + { encoding: "utf-8" }, ), }, }; @@ -21,7 +24,7 @@ export async function getStaticProps(ctx) { var textDecoder = new TextDecoder(); export default function Home({ code }) { - const fileNameRef = React.useRef(); + const fileNameRef = React.useRef<HTMLInputElement>(null); const [esbuildResult, setEsbuildResult] = React.useState(""); const [bunResult, setBunResult] = React.useState(""); const [swcResult, setSWCResult] = React.useState(""); @@ -33,14 +36,14 @@ export default function Home({ code }) { (event) => { globalThis.Run.transform( event.target.value, - fileNameRef.current.value + fileNameRef?.current?.value, ).then((result) => { setEsbuildResult(result.esbuild.code); setBunResult(textDecoder.decode(result.bun.files[0].data)); setSWCResult(result.swc.code); }, console.error); }, - [fileNameRef, setEsbuildResult, setBunResult, setSWCResult] + [fileNameRef, setEsbuildResult, setBunResult, setSWCResult], ); return ( <div className={styles.container}> diff --git a/src/api/demo/pages/scan.tsx b/src/api/demo/pages/scan.tsx index 819a597b9..87cebd64d 100644 --- a/src/api/demo/pages/scan.tsx +++ b/src/api/demo/pages/scan.tsx @@ -1,19 +1,21 @@ import Head from "next/head"; -import Image from "next/image"; +import { readFile } from "fs/promises"; import styles from "../styles/Home.module.css"; import React from "react"; if (typeof window !== "undefined") { globalThis.Scan = await import("../lib/scan"); - await import("../lib/api.ts"); + await import("../lib/api"); } export async function getStaticProps(ctx) { return { props: { - code: Bun.readFile( - "/Users/jarred/Build/es-module-lexer/test/samples/magic-string.js" + // not tested + code: readFile( + "/Users/jarred/Build/es-module-lexer/test/samples/magic-string.js", + { encoding: "utf-8" }, ), defaultFile: "magic-string.js", }, @@ -22,7 +24,7 @@ export async function getStaticProps(ctx) { var textDecoder = new TextDecoder(); export default function Home({ code, defaultFile }) { - const fileNameRef = React.useRef(); + const fileNameRef = React.useRef<HTMLInputElement>(null); const [lexer, setLexer] = React.useState(""); const [bunResult, setBunResult] = React.useState(""); const [file, setFile] = React.useState(defaultFile); @@ -34,13 +36,13 @@ export default function Home({ code, defaultFile }) { (event) => { globalThis.Scan.transform( event.target.value, - fileNameRef.current.value + fileNameRef?.current?.value, ).then((result) => { setLexer(JSON.stringify(result.lexer, null, 2)); setBunResult(JSON.stringify(result.bun, null, 2)); }, console.error); }, - [fileNameRef, setBunResult, setLexer] + [fileNameRef, setBunResult, setLexer], ); return ( <div className={styles.container}> diff --git a/src/api/demo/pages/two.tsx b/src/api/demo/pages/two.tsx index e69de29bb..cb0ff5c3b 100644 --- a/src/api/demo/pages/two.tsx +++ b/src/api/demo/pages/two.tsx @@ -0,0 +1 @@ +export {}; diff --git a/src/api/demo/schema.d.ts b/src/api/demo/schema.d.ts index 0a7ed3b9b..ae4551128 100644 --- a/src/api/demo/schema.d.ts +++ b/src/api/demo/schema.d.ts @@ -685,29 +685,29 @@ export interface BunInstall { export declare function encodeStackFrame( message: StackFrame, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeStackFrame(buffer: ByteBuffer): StackFrame; export declare function encodeStackFramePosition( message: StackFramePosition, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeStackFramePosition( - buffer: ByteBuffer + buffer: ByteBuffer, ): StackFramePosition; export declare function encodeSourceLine( message: SourceLine, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeSourceLine(buffer: ByteBuffer): SourceLine; export declare function encodeStackTrace( message: StackTrace, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeStackTrace(buffer: ByteBuffer): StackTrace; export declare function encodeJSException( message: JSException, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeJSException(buffer: ByteBuffer): JSException; export declare function encodeProblems(message: Problems, bb: ByteBuffer): void; @@ -716,175 +716,175 @@ export declare function encodeRouter(message: Router, bb: ByteBuffer): void; export declare function decodeRouter(buffer: ByteBuffer): Router; export declare function encodeFallbackMessageContainer( message: FallbackMessageContainer, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFallbackMessageContainer( - buffer: ByteBuffer + buffer: ByteBuffer, ): FallbackMessageContainer; export declare function encodeJSX(message: JSX, bb: ByteBuffer): void; export declare function decodeJSX(buffer: ByteBuffer): JSX; export declare function encodeStringPointer( message: StringPointer, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeStringPointer(buffer: ByteBuffer): StringPointer; export declare function encodeJavascriptBundledModule( message: JavascriptBundledModule, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeJavascriptBundledModule( - buffer: ByteBuffer + buffer: ByteBuffer, ): JavascriptBundledModule; export declare function encodeJavascriptBundledPackage( message: JavascriptBundledPackage, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeJavascriptBundledPackage( - buffer: ByteBuffer + buffer: ByteBuffer, ): JavascriptBundledPackage; export declare function encodeJavascriptBundle( message: JavascriptBundle, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeJavascriptBundle( - buffer: ByteBuffer + buffer: ByteBuffer, ): JavascriptBundle; export declare function encodeJavascriptBundleContainer( message: JavascriptBundleContainer, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeJavascriptBundleContainer( - buffer: ByteBuffer + buffer: ByteBuffer, ): JavascriptBundleContainer; export declare function encodeModuleImportRecord( message: ModuleImportRecord, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeModuleImportRecord( - buffer: ByteBuffer + buffer: ByteBuffer, ): ModuleImportRecord; export declare function encodeModule(message: Module, bb: ByteBuffer): void; export declare function decodeModule(buffer: ByteBuffer): Module; export declare function encodeStringMap( message: StringMap, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeStringMap(buffer: ByteBuffer): StringMap; export declare function encodeLoaderMap( message: LoaderMap, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeLoaderMap(buffer: ByteBuffer): LoaderMap; export declare function encodeEnvConfig( message: EnvConfig, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeEnvConfig(buffer: ByteBuffer): EnvConfig; export declare function encodeLoadedEnvConfig( message: LoadedEnvConfig, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeLoadedEnvConfig( - buffer: ByteBuffer + buffer: ByteBuffer, ): LoadedEnvConfig; export declare function encodeFrameworkConfig( message: FrameworkConfig, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFrameworkConfig( - buffer: ByteBuffer + buffer: ByteBuffer, ): FrameworkConfig; export declare function encodeFrameworkEntryPoint( message: FrameworkEntryPoint, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFrameworkEntryPoint( - buffer: ByteBuffer + buffer: ByteBuffer, ): FrameworkEntryPoint; export declare function encodeFrameworkEntryPointMap( message: FrameworkEntryPointMap, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFrameworkEntryPointMap( - buffer: ByteBuffer + buffer: ByteBuffer, ): FrameworkEntryPointMap; export declare function encodeFrameworkEntryPointMessage( message: FrameworkEntryPointMessage, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFrameworkEntryPointMessage( - buffer: ByteBuffer + buffer: ByteBuffer, ): FrameworkEntryPointMessage; export declare function encodeLoadedFramework( message: LoadedFramework, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeLoadedFramework( - buffer: ByteBuffer + buffer: ByteBuffer, ): LoadedFramework; export declare function encodeLoadedRouteConfig( message: LoadedRouteConfig, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeLoadedRouteConfig( - buffer: ByteBuffer + buffer: ByteBuffer, ): LoadedRouteConfig; export declare function encodeRouteConfig( message: RouteConfig, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeRouteConfig(buffer: ByteBuffer): RouteConfig; export declare function encodeTransformOptions( message: TransformOptions, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeTransformOptions( - buffer: ByteBuffer + buffer: ByteBuffer, ): TransformOptions; export declare function encodeFileHandle( message: FileHandle, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFileHandle(buffer: ByteBuffer): FileHandle; export declare function encodeTransform( message: Transform, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeTransform(buffer: ByteBuffer): Transform; export declare function encodeScan(message: Scan, bb: ByteBuffer): void; export declare function decodeScan(buffer: ByteBuffer): Scan; export declare function encodeScanResult( message: ScanResult, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeScanResult(buffer: ByteBuffer): ScanResult; export declare function encodeScannedImport( message: ScannedImport, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeScannedImport(buffer: ByteBuffer): ScannedImport; export declare function encodeOutputFile( message: OutputFile, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeOutputFile(buffer: ByteBuffer): OutputFile; export declare function encodeTransformResponse( message: TransformResponse, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeTransformResponse( - buffer: ByteBuffer + buffer: ByteBuffer, ): TransformResponse; export declare function encodeLocation(message: Location, bb: ByteBuffer): void; export declare function decodeLocation(buffer: ByteBuffer): Location; export declare function encodeMessageData( message: MessageData, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeMessageData(buffer: ByteBuffer): MessageData; export declare function encodeMessageMeta( message: MessageMeta, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeMessageMeta(buffer: ByteBuffer): MessageMeta; export declare function encodeMessage(message: Message, bb: ByteBuffer): void; @@ -893,88 +893,88 @@ export declare function encodeLog(message: Log, bb: ByteBuffer): void; export declare function decodeLog(buffer: ByteBuffer): Log; export declare function encodeWebsocketMessage( message: WebsocketMessage, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessage( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessage; export declare function encodeWebsocketMessageWelcome( message: WebsocketMessageWelcome, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessageWelcome( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessageWelcome; export declare function encodeWebsocketMessageFileChangeNotification( message: WebsocketMessageFileChangeNotification, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessageFileChangeNotification( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessageFileChangeNotification; export declare function encodeWebsocketCommand( message: WebsocketCommand, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketCommand( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketCommand; export declare function encodeWebsocketCommandBuild( message: WebsocketCommandBuild, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketCommandBuild( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketCommandBuild; export declare function encodeWebsocketCommandManifest( message: WebsocketCommandManifest, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketCommandManifest( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketCommandManifest; export declare function encodeWebsocketMessageBuildSuccess( message: WebsocketMessageBuildSuccess, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessageBuildSuccess( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessageBuildSuccess; export declare function encodeWebsocketMessageBuildFailure( message: WebsocketMessageBuildFailure, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessageBuildFailure( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessageBuildFailure; export declare function encodeWebsocketCommandBuildWithFilePath( message: WebsocketCommandBuildWithFilePath, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketCommandBuildWithFilePath( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketCommandBuildWithFilePath; export declare function encodeWebsocketMessageResolveID( message: WebsocketMessageResolveID, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessageResolveID( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessageResolveID; export declare function encodeNPMRegistry( message: NPMRegistry, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeNPMRegistry(buffer: ByteBuffer): NPMRegistry; export declare function encodeNPMRegistryMap( message: NPMRegistryMap, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeNPMRegistryMap( - buffer: ByteBuffer + buffer: ByteBuffer, ): NPMRegistryMap; export declare function encodeBunInstall( message: BunInstall, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeBunInstall(buffer: ByteBuffer): BunInstall; diff --git a/src/api/demo/schema.js b/src/api/demo/schema.js index b89ed4a08..2c31d9512 100644 --- a/src/api/demo/schema.js +++ b/src/api/demo/schema.js @@ -120,7 +120,9 @@ function encodeStackFrame(message, bb) { var encoded = StackFrameScope[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "StackFrameScope"' + "Invalid value " + + JSON.stringify(value) + + ' for enum "StackFrameScope"', ); bb.writeByte(encoded); } else { @@ -500,7 +502,7 @@ function encodeFallbackMessageContainer(message, bb) { var encoded = FallbackStep[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "FallbackStep"' + "Invalid value " + JSON.stringify(value) + ' for enum "FallbackStep"', ); bb.writeByte(encoded); } @@ -612,7 +614,7 @@ function encodeJSX(message, bb) { var encoded = JSXRuntime[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "JSXRuntime"' + "Invalid value " + JSON.stringify(value) + ' for enum "JSXRuntime"', ); bb.writeByte(encoded); } else { @@ -833,7 +835,7 @@ function encodeJavascriptBundle(message, bb) { bb.writeByteArray(value); } else { throw new Error( - 'Missing required field "app_package_json_dependencies_hash"' + 'Missing required field "app_package_json_dependencies_hash"', ); } @@ -960,7 +962,7 @@ function encodeModuleImportRecord(message, bb) { throw new Error( "Invalid value " + JSON.stringify(value) + - ' for enum "ModuleImportType"' + ' for enum "ModuleImportType"', ); bb.writeByte(encoded); } else { @@ -1090,7 +1092,7 @@ function encodeLoaderMap(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } @@ -1167,7 +1169,7 @@ function encodeLoadedEnvConfig(message, bb) { var encoded = DotEnvBehavior[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "DotEnvBehavior"' + "Invalid value " + JSON.stringify(value) + ' for enum "DotEnvBehavior"', ); bb.writeVarUint(encoded); } else { @@ -1272,7 +1274,9 @@ function encodeFrameworkConfig(message, bb) { var encoded = CSSInJSBehavior[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "CSSInJSBehavior"' + "Invalid value " + + JSON.stringify(value) + + ' for enum "CSSInJSBehavior"', ); bb.writeByte(encoded); } @@ -1308,7 +1312,7 @@ function encodeFrameworkEntryPoint(message, bb) { throw new Error( "Invalid value " + JSON.stringify(value) + - ' for enum "FrameworkEntryPointType"' + ' for enum "FrameworkEntryPointType"', ); bb.writeByte(encoded); } else { @@ -1460,7 +1464,9 @@ function encodeLoadedFramework(message, bb) { var encoded = CSSInJSBehavior[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "CSSInJSBehavior"' + "Invalid value " + + JSON.stringify(value) + + ' for enum "CSSInJSBehavior"', ); bb.writeByte(encoded); } else { @@ -1743,7 +1749,7 @@ function encodeTransformOptions(message, bb) { var encoded = ResolveMode[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "ResolveMode"' + "Invalid value " + JSON.stringify(value) + ' for enum "ResolveMode"', ); bb.writeByte(encoded); } @@ -1844,7 +1850,7 @@ function encodeTransformOptions(message, bb) { var encoded = Platform[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Platform"' + "Invalid value " + JSON.stringify(value) + ' for enum "Platform"', ); bb.writeByte(encoded); } @@ -1921,7 +1927,7 @@ function encodeTransformOptions(message, bb) { var encoded = MessageLevel[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"' + "Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"', ); bb.writeVarUint(encoded); } @@ -2019,7 +2025,7 @@ function encodeTransform(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } @@ -2077,7 +2083,7 @@ function encodeScan(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } @@ -2145,7 +2151,7 @@ function encodeScannedImport(message, bb) { var encoded = ImportKind[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "ImportKind"' + "Invalid value " + JSON.stringify(value) + ' for enum "ImportKind"', ); bb.writeByte(encoded); } else { @@ -2246,7 +2252,7 @@ function encodeTransformResponse(message, bb) { throw new Error( "Invalid value " + JSON.stringify(value) + - ' for enum "TransformResponseStatus"' + ' for enum "TransformResponseStatus"', ); bb.writeVarUint(encoded); } else { @@ -2460,7 +2466,7 @@ function encodeMessage(message, bb) { var encoded = MessageLevel[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"' + "Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"', ); bb.writeVarUint(encoded); } else { @@ -2626,7 +2632,7 @@ function encodeWebsocketMessage(message, bb) { throw new Error( "Invalid value " + JSON.stringify(value) + - ' for enum "WebsocketMessageKind"' + ' for enum "WebsocketMessageKind"', ); bb.writeByte(encoded); } else { @@ -2656,7 +2662,7 @@ function encodeWebsocketMessageWelcome(message, bb) { var encoded = Reloader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Reloader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Reloader"', ); bb.writeByte(encoded); } else { @@ -2692,7 +2698,7 @@ function encodeWebsocketMessageFileChangeNotification(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } else { @@ -2716,7 +2722,7 @@ function encodeWebsocketCommand(message, bb) { throw new Error( "Invalid value " + JSON.stringify(value) + - ' for enum "WebsocketCommandKind"' + ' for enum "WebsocketCommandKind"', ); bb.writeByte(encoded); } else { @@ -2794,7 +2800,7 @@ function encodeWebsocketMessageBuildSuccess(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } else { @@ -2847,7 +2853,7 @@ function encodeWebsocketMessageBuildFailure(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } else { diff --git a/src/api/demo/tsconfig.json b/src/api/demo/tsconfig.json index 35d51eac9..4fa2cd009 100644 --- a/src/api/demo/tsconfig.json +++ b/src/api/demo/tsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "target": "es5", + "target": "ES2020", "lib": [ "dom", "dom.iterable", @@ -8,7 +8,8 @@ ], "allowJs": true, "skipLibCheck": true, - "strict": false, + "strict": true, + "noImplicitAny": false, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, @@ -16,7 +17,11 @@ "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, - "jsx": "preserve" + "jsx": "preserve", + "types": [ + "bun-types" + ], + "incremental": true }, "include": [ "next-env.d.ts", @@ -26,4 +31,4 @@ "exclude": [ "node_modules" ] -} +}
\ No newline at end of file diff --git a/src/api/package.json b/src/api/package.json index 9df4297df..8a9f3064a 100644 --- a/src/api/package.json +++ b/src/api/package.json @@ -2,6 +2,6 @@ "name": "bun-api", "private": true, "dependencies": { - "peechy": "latest" + "peechy": "0.4.32" } } diff --git a/src/api/schema.d.ts b/src/api/schema.d.ts index d9713fdd2..8eb7a77f2 100644 --- a/src/api/schema.d.ts +++ b/src/api/schema.d.ts @@ -704,29 +704,29 @@ export interface BunInstall { export declare function encodeStackFrame( message: StackFrame, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeStackFrame(buffer: ByteBuffer): StackFrame; export declare function encodeStackFramePosition( message: StackFramePosition, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeStackFramePosition( - buffer: ByteBuffer + buffer: ByteBuffer, ): StackFramePosition; export declare function encodeSourceLine( message: SourceLine, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeSourceLine(buffer: ByteBuffer): SourceLine; export declare function encodeStackTrace( message: StackTrace, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeStackTrace(buffer: ByteBuffer): StackTrace; export declare function encodeJSException( message: JSException, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeJSException(buffer: ByteBuffer): JSException; export declare function encodeProblems(message: Problems, bb: ByteBuffer): void; @@ -735,175 +735,175 @@ export declare function encodeRouter(message: Router, bb: ByteBuffer): void; export declare function decodeRouter(buffer: ByteBuffer): Router; export declare function encodeFallbackMessageContainer( message: FallbackMessageContainer, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFallbackMessageContainer( - buffer: ByteBuffer + buffer: ByteBuffer, ): FallbackMessageContainer; export declare function encodeJSX(message: JSX, bb: ByteBuffer): void; export declare function decodeJSX(buffer: ByteBuffer): JSX; export declare function encodeStringPointer( message: StringPointer, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeStringPointer(buffer: ByteBuffer): StringPointer; export declare function encodeJavascriptBundledModule( message: JavascriptBundledModule, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeJavascriptBundledModule( - buffer: ByteBuffer + buffer: ByteBuffer, ): JavascriptBundledModule; export declare function encodeJavascriptBundledPackage( message: JavascriptBundledPackage, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeJavascriptBundledPackage( - buffer: ByteBuffer + buffer: ByteBuffer, ): JavascriptBundledPackage; export declare function encodeJavascriptBundle( message: JavascriptBundle, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeJavascriptBundle( - buffer: ByteBuffer + buffer: ByteBuffer, ): JavascriptBundle; export declare function encodeJavascriptBundleContainer( message: JavascriptBundleContainer, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeJavascriptBundleContainer( - buffer: ByteBuffer + buffer: ByteBuffer, ): JavascriptBundleContainer; export declare function encodeModuleImportRecord( message: ModuleImportRecord, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeModuleImportRecord( - buffer: ByteBuffer + buffer: ByteBuffer, ): ModuleImportRecord; export declare function encodeModule(message: Module, bb: ByteBuffer): void; export declare function decodeModule(buffer: ByteBuffer): Module; export declare function encodeStringMap( message: StringMap, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeStringMap(buffer: ByteBuffer): StringMap; export declare function encodeLoaderMap( message: LoaderMap, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeLoaderMap(buffer: ByteBuffer): LoaderMap; export declare function encodeEnvConfig( message: EnvConfig, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeEnvConfig(buffer: ByteBuffer): EnvConfig; export declare function encodeLoadedEnvConfig( message: LoadedEnvConfig, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeLoadedEnvConfig( - buffer: ByteBuffer + buffer: ByteBuffer, ): LoadedEnvConfig; export declare function encodeFrameworkConfig( message: FrameworkConfig, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFrameworkConfig( - buffer: ByteBuffer + buffer: ByteBuffer, ): FrameworkConfig; export declare function encodeFrameworkEntryPoint( message: FrameworkEntryPoint, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFrameworkEntryPoint( - buffer: ByteBuffer + buffer: ByteBuffer, ): FrameworkEntryPoint; export declare function encodeFrameworkEntryPointMap( message: FrameworkEntryPointMap, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFrameworkEntryPointMap( - buffer: ByteBuffer + buffer: ByteBuffer, ): FrameworkEntryPointMap; export declare function encodeFrameworkEntryPointMessage( message: FrameworkEntryPointMessage, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFrameworkEntryPointMessage( - buffer: ByteBuffer + buffer: ByteBuffer, ): FrameworkEntryPointMessage; export declare function encodeLoadedFramework( message: LoadedFramework, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeLoadedFramework( - buffer: ByteBuffer + buffer: ByteBuffer, ): LoadedFramework; export declare function encodeLoadedRouteConfig( message: LoadedRouteConfig, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeLoadedRouteConfig( - buffer: ByteBuffer + buffer: ByteBuffer, ): LoadedRouteConfig; export declare function encodeRouteConfig( message: RouteConfig, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeRouteConfig(buffer: ByteBuffer): RouteConfig; export declare function encodeTransformOptions( message: TransformOptions, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeTransformOptions( - buffer: ByteBuffer + buffer: ByteBuffer, ): TransformOptions; export declare function encodeFileHandle( message: FileHandle, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeFileHandle(buffer: ByteBuffer): FileHandle; export declare function encodeTransform( message: Transform, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeTransform(buffer: ByteBuffer): Transform; export declare function encodeScan(message: Scan, bb: ByteBuffer): void; export declare function decodeScan(buffer: ByteBuffer): Scan; export declare function encodeScanResult( message: ScanResult, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeScanResult(buffer: ByteBuffer): ScanResult; export declare function encodeScannedImport( message: ScannedImport, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeScannedImport(buffer: ByteBuffer): ScannedImport; export declare function encodeOutputFile( message: OutputFile, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeOutputFile(buffer: ByteBuffer): OutputFile; export declare function encodeTransformResponse( message: TransformResponse, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeTransformResponse( - buffer: ByteBuffer + buffer: ByteBuffer, ): TransformResponse; export declare function encodeLocation(message: Location, bb: ByteBuffer): void; export declare function decodeLocation(buffer: ByteBuffer): Location; export declare function encodeMessageData( message: MessageData, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeMessageData(buffer: ByteBuffer): MessageData; export declare function encodeMessageMeta( message: MessageMeta, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeMessageMeta(buffer: ByteBuffer): MessageMeta; export declare function encodeMessage(message: Message, bb: ByteBuffer): void; @@ -912,88 +912,88 @@ export declare function encodeLog(message: Log, bb: ByteBuffer): void; export declare function decodeLog(buffer: ByteBuffer): Log; export declare function encodeWebsocketMessage( message: WebsocketMessage, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessage( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessage; export declare function encodeWebsocketMessageWelcome( message: WebsocketMessageWelcome, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessageWelcome( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessageWelcome; export declare function encodeWebsocketMessageFileChangeNotification( message: WebsocketMessageFileChangeNotification, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessageFileChangeNotification( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessageFileChangeNotification; export declare function encodeWebsocketCommand( message: WebsocketCommand, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketCommand( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketCommand; export declare function encodeWebsocketCommandBuild( message: WebsocketCommandBuild, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketCommandBuild( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketCommandBuild; export declare function encodeWebsocketCommandManifest( message: WebsocketCommandManifest, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketCommandManifest( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketCommandManifest; export declare function encodeWebsocketMessageBuildSuccess( message: WebsocketMessageBuildSuccess, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessageBuildSuccess( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessageBuildSuccess; export declare function encodeWebsocketMessageBuildFailure( message: WebsocketMessageBuildFailure, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessageBuildFailure( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessageBuildFailure; export declare function encodeWebsocketCommandBuildWithFilePath( message: WebsocketCommandBuildWithFilePath, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketCommandBuildWithFilePath( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketCommandBuildWithFilePath; export declare function encodeWebsocketMessageResolveID( message: WebsocketMessageResolveID, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeWebsocketMessageResolveID( - buffer: ByteBuffer + buffer: ByteBuffer, ): WebsocketMessageResolveID; export declare function encodeNPMRegistry( message: NPMRegistry, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeNPMRegistry(buffer: ByteBuffer): NPMRegistry; export declare function encodeNPMRegistryMap( message: NPMRegistryMap, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeNPMRegistryMap( - buffer: ByteBuffer + buffer: ByteBuffer, ): NPMRegistryMap; export declare function encodeBunInstall( message: BunInstall, - bb: ByteBuffer + bb: ByteBuffer, ): void; export declare function decodeBunInstall(buffer: ByteBuffer): BunInstall; diff --git a/src/api/schema.js b/src/api/schema.js index ac28f56ab..c78693df8 100644 --- a/src/api/schema.js +++ b/src/api/schema.js @@ -124,7 +124,9 @@ function encodeStackFrame(message, bb) { var encoded = StackFrameScope[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "StackFrameScope"' + "Invalid value " + + JSON.stringify(value) + + ' for enum "StackFrameScope"', ); bb.writeByte(encoded); } else { @@ -504,7 +506,7 @@ function encodeFallbackMessageContainer(message, bb) { var encoded = FallbackStep[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "FallbackStep"' + "Invalid value " + JSON.stringify(value) + ' for enum "FallbackStep"', ); bb.writeByte(encoded); } @@ -620,7 +622,7 @@ function encodeJSX(message, bb) { var encoded = JSXRuntime[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "JSXRuntime"' + "Invalid value " + JSON.stringify(value) + ' for enum "JSXRuntime"', ); bb.writeByte(encoded); } else { @@ -841,7 +843,7 @@ function encodeJavascriptBundle(message, bb) { bb.writeByteArray(value); } else { throw new Error( - 'Missing required field "app_package_json_dependencies_hash"' + 'Missing required field "app_package_json_dependencies_hash"', ); } @@ -968,7 +970,7 @@ function encodeModuleImportRecord(message, bb) { throw new Error( "Invalid value " + JSON.stringify(value) + - ' for enum "ModuleImportType"' + ' for enum "ModuleImportType"', ); bb.writeByte(encoded); } else { @@ -1098,7 +1100,7 @@ function encodeLoaderMap(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } @@ -1175,7 +1177,7 @@ function encodeLoadedEnvConfig(message, bb) { var encoded = DotEnvBehavior[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "DotEnvBehavior"' + "Invalid value " + JSON.stringify(value) + ' for enum "DotEnvBehavior"', ); bb.writeVarUint(encoded); } else { @@ -1280,7 +1282,9 @@ function encodeFrameworkConfig(message, bb) { var encoded = CSSInJSBehavior[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "CSSInJSBehavior"' + "Invalid value " + + JSON.stringify(value) + + ' for enum "CSSInJSBehavior"', ); bb.writeByte(encoded); } @@ -1316,7 +1320,7 @@ function encodeFrameworkEntryPoint(message, bb) { throw new Error( "Invalid value " + JSON.stringify(value) + - ' for enum "FrameworkEntryPointType"' + ' for enum "FrameworkEntryPointType"', ); bb.writeByte(encoded); } else { @@ -1468,7 +1472,9 @@ function encodeLoadedFramework(message, bb) { var encoded = CSSInJSBehavior[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "CSSInJSBehavior"' + "Invalid value " + + JSON.stringify(value) + + ' for enum "CSSInJSBehavior"', ); bb.writeByte(encoded); } else { @@ -1755,7 +1761,7 @@ function encodeTransformOptions(message, bb) { var encoded = ResolveMode[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "ResolveMode"' + "Invalid value " + JSON.stringify(value) + ' for enum "ResolveMode"', ); bb.writeByte(encoded); } @@ -1856,7 +1862,7 @@ function encodeTransformOptions(message, bb) { var encoded = Platform[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Platform"' + "Invalid value " + JSON.stringify(value) + ' for enum "Platform"', ); bb.writeByte(encoded); } @@ -1933,7 +1939,7 @@ function encodeTransformOptions(message, bb) { var encoded = MessageLevel[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"' + "Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"', ); bb.writeVarUint(encoded); } @@ -1944,7 +1950,7 @@ function encodeTransformOptions(message, bb) { var encoded = SourceMapMode[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "SourceMapMode"' + "Invalid value " + JSON.stringify(value) + ' for enum "SourceMapMode"', ); bb.writeByte(encoded); } @@ -2054,7 +2060,7 @@ function encodeTransform(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } @@ -2112,7 +2118,7 @@ function encodeScan(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } @@ -2180,7 +2186,7 @@ function encodeScannedImport(message, bb) { var encoded = ImportKind[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "ImportKind"' + "Invalid value " + JSON.stringify(value) + ' for enum "ImportKind"', ); bb.writeByte(encoded); } else { @@ -2281,7 +2287,7 @@ function encodeTransformResponse(message, bb) { throw new Error( "Invalid value " + JSON.stringify(value) + - ' for enum "TransformResponseStatus"' + ' for enum "TransformResponseStatus"', ); bb.writeVarUint(encoded); } else { @@ -2495,7 +2501,7 @@ function encodeMessage(message, bb) { var encoded = MessageLevel[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"' + "Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"', ); bb.writeVarUint(encoded); } else { @@ -2661,7 +2667,7 @@ function encodeWebsocketMessage(message, bb) { throw new Error( "Invalid value " + JSON.stringify(value) + - ' for enum "WebsocketMessageKind"' + ' for enum "WebsocketMessageKind"', ); bb.writeByte(encoded); } else { @@ -2692,7 +2698,7 @@ function encodeWebsocketMessageWelcome(message, bb) { var encoded = Reloader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Reloader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Reloader"', ); bb.writeByte(encoded); } else { @@ -2735,7 +2741,7 @@ function encodeWebsocketMessageFileChangeNotification(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } else { @@ -2759,7 +2765,7 @@ function encodeWebsocketCommand(message, bb) { throw new Error( "Invalid value " + JSON.stringify(value) + - ' for enum "WebsocketCommandKind"' + ' for enum "WebsocketCommandKind"', ); bb.writeByte(encoded); } else { @@ -2837,7 +2843,7 @@ function encodeWebsocketMessageBuildSuccess(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } else { @@ -2890,7 +2896,7 @@ function encodeWebsocketMessageBuildFailure(message, bb) { var encoded = Loader[value]; if (encoded === void 0) throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"' + "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', ); bb.writeByte(encoded); } else { diff --git a/src/bun.js/assert.exports.js b/src/bun.js/assert.exports.js index 92efee5be..9e82fa72b 100644 --- a/src/bun.js/assert.exports.js +++ b/src/bun.js/assert.exports.js @@ -32,10 +32,10 @@ var __reExport = (target, module2, desc) => { "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: !0 } - : { value: module2, enumerable: !0 } - ) + : { value: module2, enumerable: !0 }, + ), ), - module2 + module2, ); var require = (path) => import.meta.require(path); @@ -73,7 +73,7 @@ var require_errors = __commonJS({ function _assertThisInitialized(self) { if (self === void 0) throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" + "this hasn't been initialised - super() hasn't been called", ); return self; } @@ -90,7 +90,7 @@ var require_errors = __commonJS({ function _inherits(subClass, superClass) { if (typeof superClass != "function" && superClass !== null) throw new TypeError( - "Super expression must either be null or a function" + "Super expression must either be null or a function", ); (subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: !0, configurable: !0 }, @@ -125,8 +125,8 @@ var require_errors = __commonJS({ this, _getPrototypeOf(NodeError2).call( this, - getMessage(arg1, arg2, arg3) - ) + getMessage(arg1, arg2, arg3), + ), )), (_this.code = code), _this @@ -178,7 +178,7 @@ var require_errors = __commonJS({ createErrorType( "ERR_AMBIGUOUS_ARGUMENT", 'The "%s" argument is ambiguous. %s', - TypeError + TypeError, ); createErrorType( "ERR_INVALID_ARG_TYPE", @@ -206,7 +206,7 @@ var require_errors = __commonJS({ } return (msg += ". Received type ".concat(_typeof(actual))), msg; }, - TypeError + TypeError, ); createErrorType( "ERR_INVALID_ARG_VALUE", @@ -227,7 +227,7 @@ var require_errors = __commonJS({ ); }, TypeError, - RangeError + RangeError, ); createErrorType( "ERR_INVALID_RETURN_VALUE", @@ -242,7 +242,7 @@ var require_errors = __commonJS({ .concat(name, '"') + " function but got ".concat(type, ".") ); }, - TypeError + TypeError, ); createErrorType( "ERR_MISSING_ARGS", @@ -276,7 +276,7 @@ var require_errors = __commonJS({ } return "".concat(msg, " must be specified"); }, - TypeError + TypeError, ); module2.exports.codes = codes; }, @@ -294,7 +294,7 @@ var require_assertion_error = __commonJS({ (ownKeys = ownKeys.concat( Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; - }) + }), )), ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); @@ -343,14 +343,14 @@ var require_assertion_error = __commonJS({ function _assertThisInitialized(self) { if (self === void 0) throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" + "this hasn't been initialised - super() hasn't been called", ); return self; } function _inherits(subClass, superClass) { if (typeof superClass != "function" && superClass !== null) throw new TypeError( - "Super expression must either be null or a function" + "Super expression must either be null or a function", ); (subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: !0, configurable: !0 }, @@ -364,7 +364,7 @@ var require_assertion_error = __commonJS({ if (Class2 === null || !_isNativeFunction(Class2)) return Class2; if (typeof Class2 != "function") throw new TypeError( - "Super expression must either be null or a function" + "Super expression must either be null or a function", ); if (typeof _cache != "undefined") { if (_cache.has(Class2)) return _cache.get(Class2); @@ -374,7 +374,7 @@ var require_assertion_error = __commonJS({ return _construct( Class2, arguments, - _getPrototypeOf(this).constructor + _getPrototypeOf(this).constructor, ); } return ( @@ -403,7 +403,7 @@ var require_assertion_error = __commonJS({ try { return ( Date.prototype.toString.call( - Reflect.construct(Date, [], function () {}) + Reflect.construct(Date, [], function () {}), ), !0 ); @@ -569,12 +569,12 @@ var require_assertion_error = __commonJS({ kReadableOperator[operator], ` -` +`, ) + "".concat(actualLines[0], " !== ").concat( expectedLines[0], ` -` +`, ) ); } else if (operator !== "strictEqualObject") { @@ -624,13 +624,13 @@ var require_assertion_error = __commonJS({ kReadableOperator.notIdentical, ` -` +`, ) .concat( _actualLines.join(` `), ` -` +`, ); } i > 3 && @@ -757,19 +757,19 @@ var require_assertion_error = __commonJS({ .concat( skippedMsg, ` -` +`, ) .concat( res, ` -` +`, ) .concat(blue, "...") .concat(white) .concat( other, ` -` +`, ) + "".concat(blue, "...").concat(white) ); } @@ -778,7 +778,7 @@ var require_assertion_error = __commonJS({ .concat( skipped ? skippedMsg : "", ` -` +`, ) .concat(res) .concat(other) @@ -803,7 +803,7 @@ var require_assertion_error = __commonJS({ if (((Error.stackTraceLimit = 0), message != null)) _this = _possibleConstructorReturn( this, - _getPrototypeOf(AssertionError2).call(this, String(message)) + _getPrototypeOf(AssertionError2).call(this, String(message)), ); else if ( (process.stderr && @@ -828,8 +828,8 @@ var require_assertion_error = __commonJS({ this, _getPrototypeOf(AssertionError2).call( this, - createErrDiff(actual, expected, operator) - ) + createErrDiff(actual, expected, operator), + ), ); else if ( operator === "notDeepStrictEqual" || @@ -856,8 +856,8 @@ var require_assertion_error = __commonJS({ this, _getPrototypeOf(AssertionError2).call( this, - "".concat(base, " ").concat(res[0]) - ) + "".concat(base, " ").concat(res[0]), + ), )) : (_this = _possibleConstructorReturn( this, @@ -868,15 +868,15 @@ var require_assertion_error = __commonJS({ base, ` -` +`, ) .concat( res.join(` `), ` -` - ) - ) +`, + ), + ), )); } else { var _res = inspectValue(actual), @@ -888,7 +888,7 @@ var require_assertion_error = __commonJS({ kReadableOperator[operator], ` -` +`, ) .concat(_res)), _res.length > 1024 && @@ -904,7 +904,7 @@ var require_assertion_error = __commonJS({ knownOperators, ` -` +`, ) .concat( _res, @@ -912,15 +912,15 @@ var require_assertion_error = __commonJS({ should equal -` +`, )) : (other = " ".concat(operator, " ").concat(other))), (_this = _possibleConstructorReturn( this, _getPrototypeOf(AssertionError2).call( this, - "".concat(_res).concat(other) - ) + "".concat(_res).concat(other), + ), )); } return ( @@ -939,7 +939,7 @@ should equal Error.captureStackTrace && Error.captureStackTrace( _assertThisInitialized(_this), - stackStartFn + stackStartFn, ), _this.stack, (_this.name = "AssertionError"), @@ -965,7 +965,7 @@ should equal _objectSpread({}, ctx, { customInspect: !1, depth: 0, - }) + }), ); }, }, @@ -1280,7 +1280,7 @@ var require_implementation2 = __commonJS({ if (this instanceof bound) { var result = target.apply( this, - args.concat(slice.call(arguments)) + args.concat(slice.call(arguments)), ); return Object(result) === result ? result : this; } else @@ -1298,7 +1298,7 @@ var require_implementation2 = __commonJS({ "binder", "return function (" + boundArgs.join(",") + - "){ return binder.apply(this,arguments); }" + "){ return binder.apply(this,arguments); }", )(binder)), target.prototype) ) { @@ -1341,7 +1341,7 @@ var require_get_intrinsic = __commonJS({ getEvalledConstructor = function (expressionSyntax) { try { return $Function( - '"use strict"; return (' + expressionSyntax + ").constructor;" + '"use strict"; return (' + expressionSyntax + ").constructor;", )(); } catch {} }, @@ -1562,11 +1562,11 @@ var require_get_intrinsic = __commonJS({ last = $strSlice(string, -1); if (first === "%" && last !== "%") throw new $SyntaxError( - "invalid intrinsic syntax, expected closing `%`" + "invalid intrinsic syntax, expected closing `%`", ); if (last === "%" && first !== "%") throw new $SyntaxError( - "invalid intrinsic syntax, expected opening `%`" + "invalid intrinsic syntax, expected opening `%`", ); var result = []; return ( @@ -1577,7 +1577,7 @@ var require_get_intrinsic = __commonJS({ result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match; - } + }, ), result ); @@ -1599,7 +1599,7 @@ var require_get_intrinsic = __commonJS({ throw new $TypeError( "intrinsic " + name + - " exists, but is not available. Please file an issue!" + " exists, but is not available. Please file an issue!", ); return { alias, @@ -1616,13 +1616,13 @@ var require_get_intrinsic = __commonJS({ throw new $TypeError('"allowMissing" argument must be a boolean'); if ($exec(/^%?[^%]*%?$/g, name) === null) throw new $SyntaxError( - "`%` may not be present anywhere but at the beginning and end of the intrinsic name" + "`%` may not be present anywhere but at the beginning and end of the intrinsic name", ); var parts = stringToPath(name), intrinsicBaseName = parts.length > 0 ? parts[0] : "", intrinsic = getBaseIntrinsic( "%" + intrinsicBaseName + "%", - allowMissing + allowMissing, ), intrinsicRealName = intrinsic.name, value = intrinsic.value, @@ -1645,7 +1645,7 @@ var require_get_intrinsic = __commonJS({ first !== last ) throw new $SyntaxError( - "property names with quotes must have matching quotes" + "property names with quotes must have matching quotes", ); if ( ((part === "constructor" || !isOwn) && (skipFurtherCaching = !0), @@ -1660,7 +1660,7 @@ var require_get_intrinsic = __commonJS({ throw new $TypeError( "base intrinsic for " + name + - " exists, but the property is not available." + " exists, but the property is not available.", ); return; } @@ -1831,7 +1831,7 @@ var require_shim = __commonJS({ is: function () { return Object.is !== polyfill; }, - } + }, ), polyfill ); @@ -1897,7 +1897,7 @@ var require_shim2 = __commonJS({ isNaN: function () { return Number.isNaN !== polyfill; }, - } + }, ), polyfill ); @@ -1937,7 +1937,7 @@ var require_comparisons = __commonJS({ } function _nonIterableRest() { throw new TypeError( - "Invalid attempt to destructure non-iterable instance" + "Invalid attempt to destructure non-iterable instance", ); } function _iterableToArrayLimit(arr, i) { @@ -2044,8 +2044,8 @@ var require_comparisons = __commonJS({ .filter(isNonIndex) .concat( objectGetOwnPropertySymbols(value).filter( - Object.prototype.propertyIsEnumerable.bind(value) - ) + Object.prototype.propertyIsEnumerable.bind(value), + ), ); } function compare(a, b) { @@ -2085,7 +2085,7 @@ var require_comparisons = __commonJS({ ? !1 : compare( new Uint8Array(a.buffer, a.byteOffset, a.byteLength), - new Uint8Array(b.buffer, b.byteOffset, b.byteLength) + new Uint8Array(b.buffer, b.byteOffset, b.byteLength), ) === 0; } function areEqualArrayBuffers(buf1, buf2) { @@ -2099,7 +2099,7 @@ var require_comparisons = __commonJS({ ? isNumberObject(val2) && objectIs( Number.prototype.valueOf.call(val1), - Number.prototype.valueOf.call(val2) + Number.prototype.valueOf.call(val2), ) : isStringObject(val1) ? isStringObject(val2) && @@ -2503,7 +2503,7 @@ var require_assert = __commonJS({ warn( "assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.", "DeprecationWarning", - "DEP0094" + "DEP0094", ); } argsLen === 2 && (operator = "!="); @@ -2605,7 +2605,7 @@ var require_assert = __commonJS({ assert.deepStrictEqual = function deepStrictEqual( actual, expected, - message + message, ) { if (arguments.length < 2) throw new ERR_MISSING_ARGS("actual", "expected"); @@ -2704,7 +2704,7 @@ var require_assert = __commonJS({ throw new ERR_INVALID_ARG_TYPE( "expected", ["Function", "RegExp"], - expected + expected, ); if (_typeof(actual) !== "object" || actual === null) { var err = new AssertionError({ @@ -2722,7 +2722,7 @@ var require_assert = __commonJS({ throw new ERR_INVALID_ARG_VALUE( "error", expected, - "may not be an empty object" + "may not be an empty object", ); return ( isDeepEqual === void 0 && lazyLoadComparison(), @@ -2768,14 +2768,14 @@ var require_assert = __commonJS({ throw new ERR_INVALID_RETURN_VALUE( "instance of Promise", "promiseFn", - resultPromise + resultPromise, ); } else if (checkIsPromise(promiseFn)) resultPromise = promiseFn; else throw new ERR_INVALID_ARG_TYPE( "promiseFn", ["Function", "Promise"], - promiseFn + promiseFn, ); return Promise.resolve() .then(function () { @@ -2795,7 +2795,7 @@ var require_assert = __commonJS({ throw new ERR_INVALID_ARG_TYPE( "error", ["Object", "Error", "Function", "RegExp"], - error + error, ); if (_typeof(actual) === "object" && actual !== null) { if (actual.message === error) @@ -2803,13 +2803,13 @@ var require_assert = __commonJS({ "error/message", 'The error message "'.concat( actual.message, - '" is identical to the message.' - ) + '" is identical to the message.', + ), ); } else if (actual === error) throw new ERR_AMBIGUOUS_ARGUMENT( "error/message", - 'The error "'.concat(actual, '" is identical to the message.') + 'The error "'.concat(actual, '" is identical to the message.'), ); (message = error), (error = void 0); } else if ( @@ -2820,7 +2820,7 @@ var require_assert = __commonJS({ throw new ERR_INVALID_ARG_TYPE( "error", ["Object", "Error", "Function", "RegExp"], - error + error, ); if (actual === NO_EXCEPTION_SENTINEL) { var details = ""; @@ -2856,7 +2856,7 @@ var require_assert = __commonJS({ "Got unwanted ".concat(fnType).concat( details, ` -` +`, ) + 'Actual message: "'.concat(actual && actual.message, '"'), stackStartFn, }); @@ -2911,7 +2911,7 @@ var require_assert = __commonJS({ return waitForActual(fn).then(function (result) { return expectsNoError.apply( void 0, - [doesNotReject, result].concat(args) + [doesNotReject, result].concat(args), ); }); }; @@ -2953,11 +2953,11 @@ var require_assert = __commonJS({ tmp1.join(` `), ` -` +`, ) .concat( tmp2.join(` -`) +`), ); } throw newErr; diff --git a/src/bun.js/bindings/sqlite/sqlite.exports.js b/src/bun.js/bindings/sqlite/sqlite.exports.js index 6c1bf803d..875e28ff1 100644 --- a/src/bun.js/bindings/sqlite/sqlite.exports.js +++ b/src/bun.js/bindings/sqlite/sqlite.exports.js @@ -3,7 +3,7 @@ var symbolFor = Symbol.for; const lazy = globalThis[symbolFor("Bun.lazy")]; if (!lazy || typeof lazy !== "function") { throw new Error( - "Something went wrong while loading Bun. Expected 'Bun.lazy' to be defined." + "Something went wrong while loading Bun. Expected 'Bun.lazy' to be defined.", ); } @@ -185,14 +185,14 @@ export class Database { filenameGiven, typeof options === "object" && options ? !!options.readonly - : ((options | 0) & constants.SQLITE_OPEN_READONLY) != 0 + : ((options | 0) & constants.SQLITE_OPEN_READONLY) != 0, ); this.filename = ":memory:"; return; } throw new TypeError( - `Expected 'filename' to be a string, got '${typeof filenameGiven}'` + `Expected 'filename' to be a string, got '${typeof filenameGiven}'`, ); } @@ -208,7 +208,7 @@ export class Database { if ("readOnly" in options) throw new TypeError( - 'Misspelled option "readOnly" should be "readonly"' + 'Misspelled option "readOnly" should be "readonly"', ); if (options.create) { @@ -316,7 +316,7 @@ export class Database { query(query) { if (typeof query !== "string") { throw new TypeError( - `Expected 'query' to be a string, got '${typeof query}'` + `Expected 'query' to be a string, got '${typeof query}'`, ); } @@ -337,7 +337,7 @@ export class Database { return (this.#cachedQueriesValues[index] = this.prepare( query, undefined, - willCache ? constants.SQLITE_PREPARE_PERSISTENT : 0 + willCache ? constants.SQLITE_PREPARE_PERSISTENT : 0, )); } return stmt; @@ -349,7 +349,7 @@ export class Database { var stmt = this.prepare( query, undefined, - willCache ? constants.SQLITE_PREPARE_PERSISTENT : 0 + willCache ? constants.SQLITE_PREPARE_PERSISTENT : 0, ); if (willCache) { @@ -413,21 +413,21 @@ const getController = (db, self) => { (controller = { default: Object.assign( { begin: db.prepare("BEGIN", undefined, 0) }, - shared + shared, ), deferred: Object.assign( { begin: db.prepare("BEGIN DEFERRED", undefined, 0) }, - shared + shared, ), immediate: Object.assign( { begin: db.prepare("BEGIN IMMEDIATE", undefined, 0) }, - shared + shared, ), exclusive: Object.assign( { begin: db.prepare("BEGIN EXCLUSIVE", undefined, 0) }, - shared + shared, ), - }) + }), ); } return controller; @@ -437,7 +437,7 @@ const getController = (db, self) => { const wrapTransaction = ( fn, db, - { begin, commit, rollback, savepoint, release, rollbackTo } + { begin, commit, rollback, savepoint, release, rollbackTo }, ) => function transaction(...args) { let before, after, undo; diff --git a/src/bun.js/child_process.exports.js b/src/bun.js/child_process.exports.js index eff7bfca0..5295152dc 100644 --- a/src/bun.js/child_process.exports.js +++ b/src/bun.js/child_process.exports.js @@ -137,7 +137,7 @@ export function spawn(file, args, options) { } else { signal.addEventListener("abort", onAbortListener, { once: true }); child.once("exit", () => - signal.removeEventListener("abort", onAbortListener) + signal.removeEventListener("abort", onAbortListener), ); } @@ -178,7 +178,7 @@ export function execFile(file, args, options, callback) { file, args, options, - callback + callback, )); options = { @@ -332,7 +332,7 @@ export function execFile(file, args, options, callback) { const truncatedLen = maxBuffer - (encodedStdoutLen - actualLen); ArrayPrototypePush.call( _stdout, - StringPrototypeSlice.apply(chunk, 0, truncatedLen) + StringPrototypeSlice.apply(chunk, 0, truncatedLen), ); ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER("stdout"); @@ -353,7 +353,7 @@ export function execFile(file, args, options, callback) { } else { ArrayPrototypePush.call(_stdout, chunk); } - } + }, ); } @@ -383,7 +383,7 @@ export function execFile(file, args, options, callback) { const truncatedLen = maxBuffer - (encodedStderrLen - actualLen); ArrayPrototypePush.call( _stderr, - StringPrototypeSlice.call(chunk, 0, truncatedLen) + StringPrototypeSlice.call(chunk, 0, truncatedLen), ); ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER("stderr"); @@ -399,7 +399,7 @@ export function execFile(file, args, options, callback) { const truncatedLen = maxBuffer - (stderrLen - chunk.length); ArrayPrototypePush.call( _stderr, - StringPrototypeSlice.call(chunk, 0, truncatedLen) + StringPrototypeSlice.call(chunk, 0, truncatedLen), ); ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER("stderr"); @@ -407,7 +407,7 @@ export function execFile(file, args, options, callback) { } else { ArrayPrototypePush.call(_stderr, chunk); } - } + }, ); } @@ -651,7 +651,7 @@ function sanitizeKillSignal(killSignal) { throw new ERR_INVALID_ARG_TYPE( "options.killSignal", ["string", "number"], - killSignal + killSignal, ); } } @@ -771,7 +771,7 @@ function normalizeSpawnArguments(file, args, options) { throw new ERR_INVALID_ARG_TYPE( "options.shell", ["boolean", "string"], - options.shell + options.shell, ); } @@ -1257,7 +1257,7 @@ function validateMaxBuffer(maxBuffer) { throw new ERR_OUT_OF_RANGE( "options.maxBuffer", "a positive number", - maxBuffer + maxBuffer, ); } } @@ -1267,7 +1267,7 @@ function validateArgumentNullCheck(arg, propName) { throw new ERR_INVALID_ARG_VALUE( propName, arg, - "must be a string without null bytes" + "must be a string without null bytes", ); } } @@ -1332,9 +1332,9 @@ const validateOneOf = (value, name, oneOf) => { if (!ArrayPrototypeIncludes.call(oneOf, value)) { const allowed = ArrayPrototypeJoin.call( ArrayPrototypeMap.call(oneOf, (v) => - typeof v === "string" ? `'${v}'` : String(v) + typeof v === "string" ? `'${v}'` : String(v), ), - ", " + ", ", ); const reason = "must be one of: " + allowed; throw new ERR_INVALID_ARG_VALUE(name, value, reason); @@ -1417,7 +1417,7 @@ function nullCheck(path, propName, throwError = true) { const err = new ERR_INVALID_ARG_VALUE( propName, path, - "must be a string or Uint8Array without null bytes" + "must be a string or Uint8Array without null bytes", ); if (throwError) { throw err; @@ -1672,7 +1672,7 @@ function ERR_OUT_OF_RANGE(str, range, input, replaceDefaultBoolean = false) { // msg += ` It must be ${range}. Received ${received}`; // return new RangeError(msg); return new RangeError( - `The value of ${str} is out of range. It must be ${range}. Received ${input}` + `The value of ${str} is out of range. It must be ${range}. Received ${input}`, ); } @@ -1688,7 +1688,7 @@ function ERR_UNKNOWN_SIGNAL(name) { function ERR_INVALID_ARG_TYPE(name, type, value) { const err = new TypeError( - `The "${name}" argument must be of type ${type}. Received ${value}` + `The "${name}" argument must be of type ${type}. Received ${value}`, ); err.code = "ERR_INVALID_ARG_TYPE"; return err; @@ -1700,7 +1700,7 @@ function ERR_INVALID_OPT_VALUE(name, value) { function ERR_INVALID_ARG_VALUE(name, value, reason) { return new Error( - `The value "${value}" is invalid for argument '${name}'. Reason: ${reason}` + `The value "${value}" is invalid for argument '${name}'. Reason: ${reason}`, ); } diff --git a/src/bun.js/depd.exports.js b/src/bun.js/depd.exports.js index 04ed01555..b6164bf02 100644 --- a/src/bun.js/depd.exports.js +++ b/src/bun.js/depd.exports.js @@ -38,7 +38,7 @@ var __toESM = (mod, isNodeMode, target) => ( isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod + mod, ) ); diff --git a/src/bun.js/ffi.exports.js b/src/bun.js/ffi.exports.js index 67ad97287..ec553b7d5 100644 --- a/src/bun.js/ffi.exports.js +++ b/src/bun.js/ffi.exports.js @@ -54,7 +54,7 @@ export class CString extends String { ? typeof byteLength === "number" && Number.isSafeInteger(byteLength) ? new BunCString(ptr, byteOffset || 0, byteLength) : new BunCString(ptr) - : "" + : "", ); this.ptr = typeof ptr === "number" ? ptr : 0; if (typeof byteOffset !== "undefined") { @@ -82,7 +82,7 @@ export class CString extends String { return (this.#cachedArrayBuffer = toArrayBuffer( this.ptr, this.byteOffset, - this.byteLength + this.byteLength, )); } } @@ -209,7 +209,7 @@ Object.defineProperty(globalThis, "__GlobalBunFFIPtrFunctionForWrapper", { }); ffiWrappers[FFIType.cstring] = ffiWrappers[FFIType.pointer] = function pointer( - val + val, ) { if (typeof val === "number") return val; if (!val) { @@ -222,7 +222,7 @@ ffiWrappers[FFIType.cstring] = ffiWrappers[FFIType.pointer] = function pointer( if (typeof val === "string") { throw new TypeError( - "To convert a string to a pointer, encode it as a buffer" + "To convert a string to a pointer, encode it as a buffer", ); } @@ -267,7 +267,7 @@ function FFIBuilder(params, returnType, functionToCall, name) { throw new TypeError( `Unsupported type ${params[i]}. Must be one of: ${Object.keys(FFIType) .sort() - .join(", ")}` + .join(", ")}`, ); } } @@ -335,7 +335,7 @@ function FFIBuilder(params, returnType, functionToCall, name) { arg6, arg7, arg8, - arg9 + arg9, ); break; default: { @@ -376,7 +376,7 @@ export function dlopen(path, options) { // "sqlite3_get_version() - sqlit3.so" path.includes("/") ? `${key} (${path.split("/").pop()})` - : `${key} (${path})` + : `${key} (${path})`, ); } else { // consistentcy @@ -400,7 +400,7 @@ export function linkSymbols(options) { options[key].args ?? [], options[key].returns ?? FFIType.void, symbol, - key + key, ); } else { // consistentcy @@ -433,7 +433,7 @@ export function CFunction(options) { cFunctionRegistry ||= new FinalizationRegistry(onCloseCFunction); cFunctionRegistry.register( result.symbols[identifier], - result.symbols[identifier].close + result.symbols[identifier].close, ); return result.symbols[identifier]; diff --git a/src/bun.js/fs.exports.js b/src/bun.js/fs.exports.js index ebf929cb1..583ede0cb 100644 --- a/src/bun.js/fs.exports.js +++ b/src/bun.js/fs.exports.js @@ -199,13 +199,13 @@ export var rmSync = fs.rmSync.bind(fs); // _maxListener var _lazyReadStream; var readStreamPathFastPathSymbol = Symbol.for( - "Bun.Node.readStreamPathFastPath" + "Bun.Node.readStreamPathFastPath", ); const readStreamSymbol = Symbol.for("Bun.NodeReadStream"); const readStreamPathOrFdSymbol = Symbol.for("Bun.NodeReadStreamPathOrFd"); var writeStreamPathFastPathSymbol = Symbol.for("Bun.NodeWriteStreamFastPath"); var writeStreamPathFastPathCallSymbol = Symbol.for( - "Bun.NodeWriteStreamFastPathCall" + "Bun.NodeWriteStreamFastPathCall", ); var kIoDone = Symbol.for("kIoDone"); @@ -653,7 +653,7 @@ function getLazyWriteStream() { readStream[kIoDone] = false; return Bun.write( this[writeStreamPathFastPathSymbol], - readStream[readStreamPathOrFdSymbol] + readStream[readStreamPathOrFdSymbol], ).then( (bytesWritten) => { readStream[kIoDone] = this[kIoDone] = true; @@ -666,7 +666,7 @@ function getLazyWriteStream() { readStream[kIoDone] = this[kIoDone] = true; this.#errorOrDestroy(err); readStream.emit("error", err); - } + }, ); } @@ -769,7 +769,7 @@ function getLazyWriteStream() { this.emit(kIoDone); !err ? cb() : cb(err); - } + }, ); } else { this[kIoDone] = true; @@ -784,7 +784,7 @@ function getLazyWriteStream() { this.#handleWrite(err, bytes); this.emit(kIoDone); !err ? cb() : cb(err); - } + }, ); } } diff --git a/src/bun.js/http.exports.js b/src/bun.js/http.exports.js index 4804b9322..d0a669d7b 100644 --- a/src/bun.js/http.exports.js +++ b/src/bun.js/http.exports.js @@ -85,7 +85,7 @@ export class Server extends EventEmitter { } catch (err) { this.emit( "error", - new Error(`bun-http-polyfill: Bun.serve failed: ${err.message}`) + new Error(`bun-http-polyfill: Bun.serve failed: ${err.message}`), ); } } @@ -170,7 +170,7 @@ export class IncomingMessage extends Readable { this.complete = true; } else { this.push( - this._body.subarray(this._body_offset, (this._body_offset += size)) + this._body.subarray(this._body_offset, (this._body_offset += size)), ); } } @@ -313,8 +313,8 @@ export class ServerResponse extends Writable { headers: this.#headers, status: this.statusCode, statusText: this.statusMessage ?? STATUS_CODES[this.statusCode], - } - ) + }, + ), ); } @@ -327,7 +327,7 @@ export class ServerResponse extends Writable { headers: this.#headers, status: this.statusCode, statusText: this.statusMessage ?? STATUS_CODES[this.statusCode], - }) + }), ); callback && callback(); return; diff --git a/src/bun.js/net.exports.js b/src/bun.js/net.exports.js index ce70c3ee1..fee0c9afa 100644 --- a/src/bun.js/net.exports.js +++ b/src/bun.js/net.exports.js @@ -36,7 +36,7 @@ const IPv6Reg = new RegExp( `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` + `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` + `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + - ")(%[0-9a-zA-Z-.:]{1,})?$" + ")(%[0-9a-zA-Z-.:]{1,})?$", ); export function isIPv4(s) { diff --git a/src/bun.js/perf_hooks.exports.js b/src/bun.js/perf_hooks.exports.js index b49e2fc4a..d25f90ccf 100644 --- a/src/bun.js/perf_hooks.exports.js +++ b/src/bun.js/perf_hooks.exports.js @@ -14,7 +14,7 @@ export class PerformanceEntry { export class PerformanceNodeTiming { constructor() { throw new Error( - "PerformanceNodeTiming is not supported in this environment." + "PerformanceNodeTiming is not supported in this environment.", ); } } diff --git a/src/bun.js/scripts/class-definitions.ts b/src/bun.js/scripts/class-definitions.ts index 95dfd69bf..5dac5db9c 100644 --- a/src/bun.js/scripts/class-definitions.ts +++ b/src/bun.js/scripts/class-definitions.ts @@ -6,7 +6,7 @@ export type Field = fn: string; length?: number; DOMJIT?: { - return: string; + returns: string; args?: [string, string] | [string, string, string] | [string]; }; } @@ -24,6 +24,7 @@ export interface ClassDefinition { noConstructor?: boolean; estimatedSize?: boolean; hasPendingActivity?: boolean; + isEventEmitter?: boolean; } export function define( @@ -35,7 +36,7 @@ export function define( call = false, construct = false, ...rest - } = {} as ClassDefinition + } = {} as ClassDefinition, ): ClassDefinition { return { ...rest, @@ -44,10 +45,10 @@ export function define( estimatedSize, values, klass: Object.fromEntries( - Object.entries(klass).sort(([a], [b]) => a.localeCompare(b)) + Object.entries(klass).sort(([a], [b]) => a.localeCompare(b)), ), proto: Object.fromEntries( - Object.entries(proto).sort(([a], [b]) => a.localeCompare(b)) + Object.entries(proto).sort(([a], [b]) => a.localeCompare(b)), ), }; } diff --git a/src/bun.js/scripts/generate-classes.ts b/src/bun.js/scripts/generate-classes.ts index 2b50246d4..ba6f68e08 100644 --- a/src/bun.js/scripts/generate-classes.ts +++ b/src/bun.js/scripts/generate-classes.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { unlinkSync } from "fs"; import { readdirSync } from "fs"; import { resolve } from "path"; @@ -95,18 +96,18 @@ function DOMJITFunctionDeclaration(jsClassName, fnName, { args, returns }) { const argNames = args.map((arg, i) => `${argTypeName(arg)} arg${i}`); return ` extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(${DOMJITName( - fnName + fnName, )}Wrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, ${argNames.join( - ", " + ", ", )})); extern "C" EncodedJSValue ${DOMJITName( - fnName + fnName, )}(void* ptr, JSC::JSGlobalObject * lexicalGlobalObject, ${argNames.join( - ", " + ", ", )}); static const JSC::DOMJIT::Signature DOMJITSignatureFor${fnName}(${DOMJITName( - fnName + fnName, )}Wrapper, ${jsClassName}::info(), JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), @@ -120,9 +121,9 @@ function DOMJITFunctionDefinition(jsClassName, fnName, { args }) { const argNames = args.map((arg, i) => `${argTypeName(arg)} arg${i}`); return ` JSC_DEFINE_JIT_OPERATION(${DOMJITName( - fnName + fnName, )}Wrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, ${argNames.join( - ", " + ", ", )})) { VM& vm = JSC::getVM(lexicalGlobalObject); @@ -131,7 +132,7 @@ JSC_DEFINE_JIT_OPERATION(${DOMJITName( IGNORE_WARNINGS_END JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); return ${DOMJITName( - fnName + fnName, )}(reinterpret_cast<${jsClassName}*>(thisValue)->wrapped(), lexicalGlobalObject, ${args .map((b, i) => "arg" + i) .join(", ")}); @@ -142,7 +143,7 @@ JSC_DEFINE_JIT_OPERATION(${DOMJITName( function appendSymbols( to: Map<string, string>, symbolName: (name: string) => string, - prop + prop, ) { var { defaultValue, getter, setter, accesosr, fn, DOMJIT, cache } = prop; @@ -171,7 +172,7 @@ function propRow( typeName: string, name: string, prop: Field, - isWrapped = true + isWrapped = true, ) { var { defaultValue, @@ -183,7 +184,7 @@ function propRow( length = 0, cache, DOMJIT, - } = prop; + } = prop as any; if (accesosr) { getter = accesosr.getter; @@ -249,7 +250,7 @@ export function generateHashTable( typeName, obj, props = {}, - wrapped + wrapped, ) { const rows = []; @@ -294,7 +295,7 @@ ${ obj.construct ? `extern "C" void* ${classSymbolName( typeName, - "construct" + "construct", )}(JSC::JSGlobalObject*, JSC::CallFrame*); JSC_DECLARE_CUSTOM_GETTER(js${typeName}Constructor);` : "" @@ -308,7 +309,7 @@ ${ obj.call ? `extern "C" JSC_DECLARE_HOST_FUNCTION(${classSymbolName( typeName, - "call" + "call", )});` : "" } @@ -323,7 +324,7 @@ ${generateHashTable( obj, protoFields, - true + true, )} @@ -334,14 +335,14 @@ ${renderFieldsImpl( typeName, obj, protoFields, - obj.values || [] + obj.values || [], )} void ${proto}::finishCreation(JSC::VM& vm, JSC::JSGlobalObject* globalObject) { Base::finishCreation(vm); reifyStaticProperties(vm, ${className( - typeName + typeName, )}::info(), ${proto}TableValues, *this); JSC_TO_STRING_TAG_WITHOUT_TRANSITION(); } @@ -391,7 +392,7 @@ function generateConstructorHeader(typeName) { public: using Base = JSC::InternalFunction; static ${name}* create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::Structure* structure, ${prototypeName( - typeName + typeName, )}* prototype); static constexpr unsigned StructureFlags = Base::StructureFlags; @@ -409,22 +410,22 @@ function generateConstructorHeader(typeName) { return WebCore::subspaceForImpl<${name}, WebCore::UseCustomHeapCellType::No>( vm, [](auto& spaces) { return spaces.${clientSubspaceFor( - typeName + typeName, )}Constructor.get(); }, [](auto& spaces, auto&& space) { spaces.${clientSubspaceFor( - typeName + typeName, )}Constructor = WTFMove(space); }, [](auto& spaces) { return spaces.${subspaceFor( - typeName + typeName, )}Constructor.get(); }, [](auto& spaces, auto&& space) { spaces.${subspaceFor( - typeName + typeName, )}Constructor = WTFMove(space); }); } void initializeProperties(JSC::VM& vm, JSC::JSGlobalObject* globalObject, ${prototypeName( - typeName + typeName, )}* prototype); // Must be defined for each specialization class. @@ -434,7 +435,7 @@ function generateConstructorHeader(typeName) { private: ${name}(JSC::VM& vm, JSC::Structure* structure); void finishCreation(JSC::VM&, JSC::JSGlobalObject* globalObject, ${prototypeName( - typeName + typeName, )}* prototype); }; @@ -460,7 +461,7 @@ ${renderStaticDecls(classSymbolName, typeName, fields)} ${hashTable} void ${name}::finishCreation(VM& vm, JSC::JSGlobalObject* globalObject, ${prototypeName( - typeName + typeName, )}* prototype) { Base::finishCreation(vm, 0, "${typeName}"_s, PropertyAdditionMode::WithoutStructureTransition); @@ -480,7 +481,7 @@ ${name}::${name}(JSC::VM& vm, JSC::Structure* structure) : Base(vm, structure, $ } ${name}* ${name}::create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::Structure* structure, ${prototypeName( - typeName + typeName, )}* prototype) { ${name}* ptr = new (NotNull, JSC::allocateCell<${name}>(vm)) ${name}(vm, structure); ptr->finishCreation(vm, globalObject, prototype); @@ -511,7 +512,7 @@ JSC::EncodedJSValue JSC_HOST_CALL_ATTRIBUTES ${name}::construct(JSC::JSGlobalObj void* ptr = ${classSymbolName( typeName, - "construct" + "construct", )}(globalObject, callFrame); if (UNLIKELY(!ptr)) { @@ -519,13 +520,13 @@ JSC::EncodedJSValue JSC_HOST_CALL_ATTRIBUTES ${name}::construct(JSC::JSGlobalObj } ${className(typeName)}* instance = ${className( - typeName + typeName, )}::create(vm, globalObject, structure, ptr); ${ obj.estimatedSize ? `vm.heap.reportExtraMemoryAllocated(${symbolName( obj.name, - "estimatedSize" + "estimatedSize", )}(instance->wrapped()));` : "" } @@ -537,13 +538,13 @@ extern "C" EncodedJSValue ${typeName}__create(Zig::GlobalObject* globalObject, v auto &vm = globalObject->vm(); JSC::Structure* structure = globalObject->${className(typeName)}Structure(); ${className(typeName)}* instance = ${className( - typeName + typeName, )}::create(vm, globalObject, structure, ptr); ${ obj.estimatedSize ? `vm.heap.reportExtraMemoryAllocated(${symbolName( obj.name, - "estimatedSize" + "estimatedSize", )}(ptr));` : "" } @@ -551,7 +552,7 @@ extern "C" EncodedJSValue ${typeName}__create(Zig::GlobalObject* globalObject, v } void ${name}::initializeProperties(VM& vm, JSC::JSGlobalObject* globalObject, ${prototypeName( - typeName + typeName, )}* prototype) { @@ -607,12 +608,12 @@ function renderDecls(symbolName, typeName, proto) { rows.push( `extern "C" JSC::EncodedJSValue ${symbolName( typeName, - proto[name].getter || proto[name].accessor.getter + proto[name].getter || proto[name].accessor.getter, )}(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject);`, ` JSC_DECLARE_CUSTOM_GETTER(${symbolName(typeName, name)}GetterWrap); `.trim(), - "\n" + "\n", ); } @@ -623,12 +624,12 @@ function renderDecls(symbolName, typeName, proto) { rows.push( `extern "C" bool ${symbolName( typeName, - proto[name].setter || proto[name].accessor.setter + proto[name].setter || proto[name].accessor.setter, )}(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::EncodedJSValue value);`, ` JSC_DECLARE_CUSTOM_SETTER(${symbolName(typeName, name)}SetterWrap); `.trim(), - "\n" + "\n", ); } @@ -636,13 +637,13 @@ function renderDecls(symbolName, typeName, proto) { rows.push( `extern "C" EncodedJSValue ${symbolName( typeName, - proto[name].fn + proto[name].fn, )}(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);`, ` JSC_DECLARE_HOST_FUNCTION(${symbolName(typeName, name)}Callback); `.trim(), - "\n" + "\n", ); if (proto[name].DOMJIT) { @@ -650,13 +651,13 @@ function renderDecls(symbolName, typeName, proto) { DOMJITFunctionDeclaration( className(typeName), symbolName(typeName, name), - proto[name].DOMJIT + proto[name].DOMJIT, ), DOMJITFunctionDefinition( className(typeName), symbolName(typeName, name), - proto[name].DOMJIT - ) + proto[name].DOMJIT, + ), ); } } @@ -676,8 +677,8 @@ function renderStaticDecls(symbolName, typeName, fields) { rows.push( `extern "C" JSC_DECLARE_CUSTOM_GETTER(${symbolName( typeName, - fields[name].getter || fields[name].accessor.getter - )});` + fields[name].getter || fields[name].accessor.getter, + )});`, ); } @@ -688,8 +689,8 @@ function renderStaticDecls(symbolName, typeName, fields) { rows.push( `extern "C" JSC_DECLARE_CUSTOM_SETTER(${symbolName( typeName, - fields[name].setter || fields[name].accessor.setter - )});` + fields[name].setter || fields[name].accessor.setter, + )});`, ); } @@ -697,8 +698,8 @@ function renderStaticDecls(symbolName, typeName, fields) { rows.push( `extern "C" JSC_DECLARE_HOST_FUNCTION(${symbolName( typeName, - fields[name].fn - )});` + fields[name].fn, + )});`, ); } } @@ -710,23 +711,23 @@ function writeBarrier(symbolName, typeName, name, cacheName) { extern "C" void ${symbolName( typeName, - name + name, )}SetCachedValue(JSC::EncodedJSValue thisValue, JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { auto& vm = globalObject->vm(); auto* thisObject = jsCast<${className( - typeName + typeName, )}*>(JSValue::decode(thisValue)); thisObject->${cacheName}.set(vm, thisObject, JSValue::decode(value)); } extern "C" EncodedJSValue ${symbolName( typeName, - name + name, )}GetCachedValue(JSC::EncodedJSValue thisValue) { auto* thisObject = jsCast<${className( - typeName + typeName, )}*>(JSValue::decode(thisValue)); return JSValue::encode(thisObject->${cacheName}.get()); } @@ -738,7 +739,7 @@ function renderFieldsImpl( typeName: string, obj: ClassDefinition, proto: ClassDefinition["proto"], - cachedValues: string[] + cachedValues: string[], ) { const rows: string[] = []; @@ -751,7 +752,7 @@ JSC_DEFINE_CUSTOM_GETTER(js${typeName}Constructor, (JSGlobalObject * lexicalGlob auto throwScope = DECLARE_THROW_SCOPE(vm); auto* globalObject = reinterpret_cast<Zig::GlobalObject*>(lexicalGlobalObject); auto* prototype = jsDynamicCast<${prototypeName( - typeName + typeName, )}*>(JSValue::decode(thisValue)); if (UNLIKELY(!prototype)) @@ -772,14 +773,14 @@ JSC_DEFINE_CUSTOM_GETTER(js${typeName}Constructor, (JSGlobalObject * lexicalGlob rows.push(` JSC_DEFINE_CUSTOM_GETTER(${symbolName( typeName, - name + name, )}GetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) { auto& vm = lexicalGlobalObject->vm(); Zig::GlobalObject *globalObject = reinterpret_cast<Zig::GlobalObject*>(lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); ${className(typeName)}* thisObject = jsCast<${className( - typeName + typeName, )}*>(JSValue::decode(thisValue)); JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); @@ -789,7 +790,7 @@ JSC_DEFINE_CUSTOM_GETTER(${symbolName( JSC::JSValue result = JSC::JSValue::decode( ${symbolName( typeName, - proto[name].getter + proto[name].getter, )}(thisObject->wrapped(), globalObject) ); RETURN_IF_EXCEPTION(throwScope, {}); @@ -805,19 +806,19 @@ JSC_DEFINE_CUSTOM_GETTER(${symbolName( rows.push(` JSC_DEFINE_CUSTOM_GETTER(${symbolName( typeName, - name + name, )}GetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) { auto& vm = lexicalGlobalObject->vm(); Zig::GlobalObject *globalObject = reinterpret_cast<Zig::GlobalObject*>(lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); ${className(typeName)}* thisObject = jsCast<${className( - typeName + typeName, )}*>(JSValue::decode(thisValue)); JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); JSC::EncodedJSValue result = ${symbolName( typeName, - proto[name].getter + proto[name].getter, )}(thisObject->wrapped(), globalObject); RETURN_IF_EXCEPTION(throwScope, {}); RELEASE_AND_RETURN(throwScope, result); @@ -833,23 +834,23 @@ JSC_DEFINE_CUSTOM_GETTER(${symbolName( ` JSC_DEFINE_CUSTOM_SETTER(${symbolName( typeName, - name + name, )}SetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, EncodedJSValue encodedValue, PropertyName attributeName)) { auto& vm = lexicalGlobalObject->vm(); auto throwScope = DECLARE_THROW_SCOPE(vm); ${className(typeName)}* thisObject = jsCast<${className( - typeName + typeName, )}*>(JSValue::decode(thisValue)); JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); auto result = ${symbolName( typeName, - proto[name].setter || proto[name].accessor.setter + proto[name].setter || proto[name].accessor.setter, )}(thisObject->wrapped(), lexicalGlobalObject, encodedValue); RELEASE_AND_RETURN(throwScope, result); } -` +`, ); } @@ -857,13 +858,13 @@ JSC_DEFINE_CUSTOM_SETTER(${symbolName( rows.push(` JSC_DEFINE_HOST_FUNCTION(${symbolName( typeName, - name + name, )}Callback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) { auto& vm = lexicalGlobalObject->vm(); ${className(typeName)}* thisObject = jsDynamicCast<${className( - typeName + typeName, )}*>(callFrame->thisValue()); if (UNLIKELY(!thisObject)) { @@ -875,7 +876,7 @@ JSC_DEFINE_CUSTOM_SETTER(${symbolName( return ${symbolName( typeName, - proto[name].fn + proto[name].fn, )}(thisObject->wrapped(), lexicalGlobalObject, callFrame); } `); @@ -885,7 +886,7 @@ JSC_DEFINE_CUSTOM_SETTER(${symbolName( if (cachedValues?.length) { for (const cacheName of cachedValues) { rows.push( - writeBarrier(symbolName, typeName, cacheName, "m_" + cacheName) + writeBarrier(symbolName, typeName, cacheName, "m_" + cacheName), ); } } @@ -955,16 +956,16 @@ function generateClassHeader(typeName, obj: ClassDefinition) { return WebCore::subspaceForImpl<${name}, WebCore::UseCustomHeapCellType::No>( vm, [](auto& spaces) { return spaces.${clientSubspaceFor( - typeName + typeName, )}.get(); }, [](auto& spaces, auto&& space) { spaces.${clientSubspaceFor( - typeName + typeName, )} = WTFMove(space); }, [](auto& spaces) { return spaces.${subspaceFor( - typeName + typeName, )}.get(); }, [](auto& spaces, auto&& space) { spaces.${subspaceFor( - typeName + typeName, )} = WTFMove(space); }); } @@ -1027,7 +1028,7 @@ function generateClassImpl(typeName, obj: ClassDefinition) { ] .filter( ([name, { cache = false, internal = false }]) => - (cache || internal) === true + (cache || internal) === true, ) .map(([name]) => ` visitor.append(thisObject->m_${name});`) .join("\n"); @@ -1119,7 +1120,7 @@ extern "C" void* ${typeName}__fromJS(JSC::EncodedJSValue value) { return nullptr; ${className(typeName)}* object = JSC::jsDynamicCast<${className( - typeName + typeName, )}*>(decodedValue); if (!object) @@ -1130,7 +1131,7 @@ extern "C" void* ${typeName}__fromJS(JSC::EncodedJSValue value) { extern "C" bool ${typeName}__dangerouslySetPtr(JSC::EncodedJSValue value, void* ptr) { ${className(typeName)}* object = JSC::jsDynamicCast<${className( - typeName + typeName, )}*>(JSValue::decode(value)); if (!object) return false; @@ -1141,7 +1142,7 @@ extern "C" bool ${typeName}__dangerouslySetPtr(JSC::EncodedJSValue value, void* extern "C" const size_t ${typeName}__ptrOffset = ${className( - typeName + typeName, )}::offsetOfWrapped(); void ${name}::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) @@ -1157,18 +1158,18 @@ void ${name}::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) JSObject* ${name}::createConstructor(VM& vm, JSGlobalObject* globalObject, JSValue prototype) { return WebCore::${constructorName( - typeName + typeName, )}::create(vm, globalObject, WebCore::${constructorName( - typeName + typeName, )}::createStructure(vm, globalObject, globalObject->functionPrototype()), jsCast<WebCore::${prototypeName( - typeName + typeName, )}*>(prototype)); } JSObject* ${name}::createPrototype(VM& vm, JSDOMGlobalObject* globalObject) { return ${prototypeName(typeName)}::create(vm, globalObject, ${prototypeName( - typeName + typeName, )}::createStructure(vm, globalObject, globalObject->objectPrototype())); } @@ -1207,7 +1208,7 @@ function generateZig( call = false, values = [], hasPendingActivity = false, - } = {} as ClassDefinition + } = {} as ClassDefinition, ) { const exports = new Map<string, string>(); @@ -1230,15 +1231,15 @@ function generateZig( if (hasPendingActivity) { exports.set( "hasPendingActivity", - symbolName(typeName, "hasPendingActivity") + symbolName(typeName, "hasPendingActivity"), ); } Object.values(klass).map((a) => - appendSymbols(exports, (name) => classSymbolName(typeName, name), a) + appendSymbols(exports, (name) => classSymbolName(typeName, name), a), ); Object.values(proto).map((a) => - appendSymbols(exports, (name) => protoSymbolName(typeName, name), a) + appendSymbols(exports, (name) => protoSymbolName(typeName, name), a), ); const externs = Object.entries({ @@ -1247,18 +1248,18 @@ function generateZig( }) .filter( ([name, { cache, internal }]) => - (cache && typeof cache !== "string") || internal + (cache && typeof cache !== "string") || internal, ) .map( ([name]) => `extern fn ${protoSymbolName( typeName, - name + name, )}SetCachedValue(JSC.JSValue, *JSC.JSGlobalObject, JSC.JSValue) void; extern fn ${protoSymbolName( typeName, - name + name, )}GetCachedValue(JSC.JSValue) JSC.JSValue; /// \`${typeName}.${name}\` setter @@ -1267,7 +1268,7 @@ function generateZig( JSC.markBinding(@src()); ${protoSymbolName( typeName, - name + name, )}SetCachedValue(thisValue, globalObject, value); } @@ -1277,14 +1278,14 @@ function generateZig( JSC.markBinding(@src()); const result = ${protoSymbolName( typeName, - name + name, )}GetCachedValue(thisValue); if (result == .zero) return null; return result; } -`.trim() + "\n" +`.trim() + "\n", ) .join("\n"); @@ -1344,7 +1345,7 @@ function generateZig( output += ` if (@TypeOf(${typeName}.${DOMJITName(fn)}) != ${ZigDOMJITFunctionType( typeName, - DOMJIT + DOMJIT, )}) @compileLog( "Expected ${typeName}.${DOMJITName(fn)} to be a DOMJIT function" @@ -1357,7 +1358,7 @@ function generateZig( "Expected ${typeName}.${fn} to be a callback" );`; } - } + }, ); [...Object.values(klass)].forEach(({ getter, setter, accessor, fn }) => { @@ -1438,7 +1439,7 @@ pub const ${className(typeName)} = struct { if (comptime Environment.allow_assert) { const value__ = ${symbolName( typeName, - "create" + "create", )}(globalObject, this); std.debug.assert(value__.as(${typeName}).? == this); // If this fails, likely a C ABI issue. return value__; @@ -1458,19 +1459,19 @@ pub const ${className(typeName)} = struct { JSC.markBinding(@src()); std.debug.assert(${symbolName( typeName, - "dangerouslySetPtr" + "dangerouslySetPtr", )}(value, null)); } extern fn ${symbolName(typeName, "fromJS")}(JSC.JSValue) ?*${typeName}; extern fn ${symbolName( typeName, - "getConstructor" + "getConstructor", )}(*JSC.JSGlobalObject) JSC.JSValue; extern fn ${symbolName( typeName, - "create" + "create", )}(globalObject: *JSC.JSGlobalObject, ptr: ?*${typeName}) JSC.JSValue; extern fn ${typeName}__dangerouslySetPtr(JSC.JSValue, ?*${typeName}) bool; @@ -1482,7 +1483,7 @@ ${[...exports] .sort(([a], [b]) => a.localeCompare(b)) .map( ([internalName, externalName]) => - `@export(${typeName}.${internalName}, .{.name = "${externalName}"});` + `@export(${typeName}.${internalName}, .{.name = "${externalName}"});`, ) .join("\n ")} } @@ -1495,21 +1496,21 @@ ${[...exports] function generateLazyClassStructureHeader( typeName, - { klass = {}, proto = {} } + { klass = {}, proto = {} }, ) { return ` JSC::Structure* ${className( - typeName + typeName, )}Structure() { return m_${className( - typeName + typeName, )}.getInitializedOnMainThread(this); } JSC::JSObject* ${className( - typeName + typeName, )}Constructor() { return m_${className( - typeName + typeName, )}.constructorInitializedOnMainThread(this); } JSC::JSValue ${className(typeName)}Prototype() { return m_${className( - typeName + typeName, )}.prototypeInitializedOnMainThread(this); } JSC::LazyClassStructure m_${className(typeName)}; bool has${className(typeName)}SetterValue { false }; @@ -1520,7 +1521,7 @@ function generateLazyClassStructureHeader( function generateLazyStructureHeader(typeName, { klass = {}, proto = {} }) { return ` JSC::Structure* ${className( - typeName + typeName, )}Structure() { return m_${className(typeName)}.get(this); } JSC::LazyProperty<Zig::GlobalObject, Structure> m_${className(typeName)}; bool has${className(typeName)}SetterValue { false }; @@ -1533,10 +1534,10 @@ function generateLazyStructureImpl(typeName, { klass = {}, proto = {} }) { m_${className(typeName)}.initLater( [](const JSC::LazyProperty<JSC::JSGlobalObject, JSC::JSObject>::Initializer& init) { auto *prototype = WebCore::${className( - typeName + typeName, )}::createPrototype(init.vm, reinterpret_cast<Zig::GlobalObject*>(init.owner)); init.set(WebCore::${className( - typeName + typeName, )}::createStructure(init.vm, init.owner, prototype)); }); @@ -1548,13 +1549,13 @@ function generateLazyClassStructureImpl(typeName, { klass = {}, proto = {} }) { m_${className(typeName)}.initLater( [](LazyClassStructure::Initializer& init) { init.setPrototype(WebCore::${className( - typeName + typeName, )}::createPrototype(init.vm, reinterpret_cast<Zig::GlobalObject*>(init.global))); init.setStructure(WebCore::${className( - typeName + typeName, )}::createStructure(init.vm, init.global, init.prototype)); init.setConstructor(WebCore::${className( - typeName + typeName, )}::createConstructor(init.vm, init.global, init.prototype)); }); @@ -1645,10 +1646,10 @@ void GlobalObject::visitGeneratedLazyClasses(GlobalObject *thisObject, Visitor& .map( (a) => `thisObject->m_${className( - a.name + a.name, )}.visit(visitor); visitor.append(thisObject->m_${className( - a.name - )}SetterValue);` + a.name, + )}SetterValue);`, ) .join("\n ")} } @@ -1725,9 +1726,9 @@ await writeAndUnlink( .map((a) => !a.noConstructor ? generateLazyClassStructureHeader(a.name, a) - : generateLazyStructureHeader(a.name, a) + : generateLazyStructureHeader(a.name, a), ) - .join("\n") + .join("\n"), ); await writeAndUnlink( @@ -1737,11 +1738,11 @@ await writeAndUnlink( `std::unique_ptr<GCClient::IsoSubspace> ${clientSubspaceFor(a.name)};`, !a.noConstructor ? `std::unique_ptr<GCClient::IsoSubspace> ${clientSubspaceFor( - a.name + a.name, )}Constructor;` : "", - ].join("\n") - ) + ].join("\n"), + ), ); await writeAndUnlink( @@ -1752,8 +1753,8 @@ await writeAndUnlink( !a.noConstructor ? `std::unique_ptr<IsoSubspace> ${subspaceFor(a.name)}Constructor;` : ``, - ].join("\n") - ) + ].join("\n"), + ), ); await writeAndUnlink( @@ -1762,11 +1763,11 @@ await writeAndUnlink( classes.map((a) => !a.noConstructor ? generateLazyClassStructureImpl(a.name, a) - : generateLazyStructureImpl(a.name, a) - ) + : generateLazyStructureImpl(a.name, a), + ), ) + "\n" + - visitLazyClasses(classes) + visitLazyClasses(classes), ); export {}; diff --git a/src/bun.js/scripts/generate-jssink.js b/src/bun.js/scripts/generate-jssink.js index 65fc864fb..0e9d3bb50 100644 --- a/src/bun.js/scripts/generate-jssink.js +++ b/src/bun.js/scripts/generate-jssink.js @@ -481,19 +481,19 @@ JSC_DEFINE_HOST_FUNCTION(${name}__doClose, (JSC::JSGlobalObject * lexicalGlobalO /* Source for JS${name}PrototypeTableValues.lut.h @begin JS${name}PrototypeTable close ${`${name}__doClose`.padEnd( - padding + 8 + padding + 8, )} ReadOnly|DontDelete|Function 0 flush ${`${name}__flush`.padEnd( - padding + 8 + padding + 8, )} ReadOnly|DontDelete|Function 1 end ${`${name}__end`.padEnd( - padding + 8 + padding + 8, )} ReadOnly|DontDelete|Function 0 start ${`${name}__start`.padEnd( - padding + 8 + padding + 8, )} ReadOnly|DontDelete|Function 1 write ${`${name}__write`.padEnd( - padding + 8 + padding + 8, )} ReadOnly|DontDelete|Function 1 @end */ @@ -502,19 +502,19 @@ JSC_DEFINE_HOST_FUNCTION(${name}__doClose, (JSC::JSGlobalObject * lexicalGlobalO /* Source for ${controllerPrototypeName}TableValues.lut.h @begin ${controllerPrototypeName}Table close ${`${controller}__close`.padEnd( - protopad + 4 + protopad + 4, )} ReadOnly|DontDelete|Function 0 flush ${`${name}__flush`.padEnd( - protopad + 4 + protopad + 4, )} ReadOnly|DontDelete|Function 1 end ${`${controller}__end`.padEnd( - protopad + 4 + protopad + 4, )} ReadOnly|DontDelete|Function 0 start ${`${name}__start`.padEnd( - protopad + 4 + protopad + 4, )} ReadOnly|DontDelete|Function 1 write ${`${name}__write`.padEnd( - protopad + 4 + protopad + 4, )} ReadOnly|DontDelete|Function 1 @end */ @@ -950,5 +950,5 @@ extern "C" void ${name}__onClose(JSC__JSValue controllerValue, JSC__JSValue reas await Bun.write(resolve(import.meta.dir + "/../bindings/JSSink.h"), header()); await Bun.write( resolve(import.meta.dir + "/../bindings/JSSink.cpp"), - await implementation() + await implementation(), ); diff --git a/src/bun.js/streams.exports.js b/src/bun.js/streams.exports.js index a7a37b107..24e34447d 100644 --- a/src/bun.js/streams.exports.js +++ b/src/bun.js/streams.exports.js @@ -94,13 +94,13 @@ var ArrayIsArray = Array.isArray; function ERR_INVALID_ARG_TYPE(name, type, value) { return new Error( - `The argument '${name}' is invalid. Received '${value}' for type '${type}'` + `The argument '${name}' is invalid. Received '${value}' for type '${type}'`, ); } function ERR_INVALID_ARG_VALUE(name, value, reason) { return new Error( - `The value '${value}' is invalid for argument '${name}'. Reason: ${reason}` + `The value '${value}' is invalid for argument '${name}'. Reason: ${reason}`, ); } @@ -220,7 +220,7 @@ var require_util = __commonJS({ constructor(errors) { if (!Array.isArray(errors)) { throw new TypeError( - `Expected input to be an Array, got ${typeof errors}` + `Expected input to be an Array, got ${typeof errors}`, ); } let message = ""; @@ -327,7 +327,7 @@ var require_util = __commonJS({ isBlob, }; module.exports.promisify.custom = Symbol.for( - "nodejs.util.promisify.custom" + "nodejs.util.promisify.custom", ); }, }); @@ -375,14 +375,14 @@ var require_errors = __commonJS({ if (typeof msg === "function") { assert( msg.length <= args.length, - `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).` + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`, ); return msg(...args); } const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length; assert( expectedLength === args.length, - `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`, ); if (args.length === 0) { return msg; @@ -436,7 +436,7 @@ var require_errors = __commonJS({ } const err = new AggregateError( [outerError, innerError], - outerError.message + outerError.message, ); err.code = outerError.code; return err; @@ -474,7 +474,7 @@ var require_errors = __commonJS({ for (const value of expected) { assert( typeof value === "string", - "All expected entries have to be of type string" + "All expected entries have to be of type string", ); if (kTypes.includes(value)) { types.push(value.toLowerCase()); @@ -483,7 +483,7 @@ var require_errors = __commonJS({ } else { assert( value !== "object", - 'The value "object" should be written as "Object"' + 'The value "object" should be written as "Object"', ); other.push(value); } @@ -575,7 +575,7 @@ var require_errors = __commonJS({ } return msg; }, - TypeError + TypeError, ); E( "ERR_INVALID_ARG_VALUE", @@ -587,7 +587,7 @@ var require_errors = __commonJS({ const type = name.includes(".") ? "property" : "argument"; return `The ${type} '${name}' ${reason}. Received ${inspected}`; }, - TypeError + TypeError, ); E( "ERR_INVALID_RETURN_VALUE", @@ -603,7 +603,7 @@ var require_errors = __commonJS({ : `type ${typeof value}`; return `Expected ${input} to be returned from the "${name}" function but got ${type}.`; }, - TypeError + TypeError, ); E( "ERR_MISSING_ARGS", @@ -630,7 +630,7 @@ var require_errors = __commonJS({ } return `${msg} must be specified`; }, - TypeError + TypeError, ); E( "ERR_OUT_OF_RANGE", @@ -650,32 +650,32 @@ var require_errors = __commonJS({ } return `The value of "${str}" is out of range. It must be ${range}. Received ${received}`; }, - RangeError + RangeError, ); E("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error); E("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error); E( "ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", - Error + Error, ); E("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error); E( "ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", - Error + Error, ); E( "ERR_STREAM_NULL_VALUES", "May not write null values to stream", - TypeError + TypeError, ); E("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error); E("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error); E( "ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", - Error + Error, ); E("ERR_STREAM_WRITE_AFTER_END", "write after end", Error); E("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError); @@ -745,7 +745,7 @@ var require_validators = __commonJS({ value, name, min = NumberMIN_SAFE_INTEGER, - max = NumberMAX_SAFE_INTEGER + max = NumberMAX_SAFE_INTEGER, ) => { if (typeof value !== "number") throw new ERR_INVALID_ARG_TYPE(name, "number", value); @@ -753,7 +753,7 @@ var require_validators = __commonJS({ throw new ERR_OUT_OF_RANGE(name, "an integer", value); if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); - } + }, ); var validateInt32 = hideStackFrames( (value, name, min = -2147483648, max = 2147483647) => { @@ -769,7 +769,7 @@ var require_validators = __commonJS({ if (value < min || value > max) { throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); } - } + }, ); var validateUint32 = hideStackFrames((value, name, positive) => { if (typeof value !== "number") { @@ -798,9 +798,9 @@ var require_validators = __commonJS({ if (!ArrayPrototypeIncludes(oneOf, value)) { const allowed = ArrayPrototypeJoin( ArrayPrototypeMap(oneOf, (v) => - typeof v === "string" ? `'${v}'` : String2(v) + typeof v === "string" ? `'${v}'` : String2(v), ), - ", " + ", ", ); const reason = "must be one of: " + allowed; throw new ERR_INVALID_ARG_VALUE(name, value, reason); @@ -838,7 +838,7 @@ var require_validators = __commonJS({ if (signals[signal] === void 0) { if (signals[StringPrototypeToUpperCase(signal)] !== void 0) { throw new ERR_UNKNOWN_SIGNAL( - signal + " (signals must use all capital letters)" + signal + " (signals must use all capital letters)", ); } throw new ERR_UNKNOWN_SIGNAL(signal); @@ -849,7 +849,7 @@ var require_validators = __commonJS({ throw new ERR_INVALID_ARG_TYPE( name, ["Buffer", "TypedArray", "DataView"], - buffer + buffer, ); } }); @@ -860,7 +860,7 @@ var require_validators = __commonJS({ throw new ERR_INVALID_ARG_VALUE( "encoding", encoding, - `is invalid for data of length ${length}` + `is invalid for data of length ${length}`, ); } } @@ -927,7 +927,7 @@ var require_validators = __commonJS({ var require_utils = __commonJS({ "node_modules/readable-stream/lib/internal/streams/utils.js"( exports, - module + module, ) { "use strict"; var { @@ -1304,7 +1304,7 @@ var require_utils = __commonJS({ var require_end_of_stream = __commonJS({ "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"( exports, - module + module, ) { "use strict"; var { AbortError, codes } = require_errors(); @@ -1489,7 +1489,7 @@ var require_end_of_stream = __commonJS({ stream, new AbortError(void 0, { cause: options.signal.reason, - }) + }), ); }; if (options.signal.aborted) { @@ -1525,7 +1525,7 @@ var require_end_of_stream = __commonJS({ var require_operators = __commonJS({ "node_modules/readable-stream/lib/internal/streams/operators.js"( exports, - module + module, ) { "use strict"; var AbortController = @@ -1738,7 +1738,7 @@ var require_operators = __commonJS({ async (...args) => { return !(await fn(...args)); }, - options + options, )); } async function find(fn, options) { @@ -1781,7 +1781,7 @@ var require_operators = __commonJS({ throw new ERR_INVALID_ARG_TYPE( "reducer", ["Function", "AsyncFunction"], - reducer + reducer, ); } if (options != null) { @@ -1997,7 +1997,7 @@ var require_operators = __commonJS({ var require_destroy = __commonJS({ "node_modules/readable-stream/lib/internal/streams/destroy.js"( exports, - module + module, ) { "use strict"; var { @@ -2183,7 +2183,7 @@ var require_destroy = __commonJS({ if (called) { errorOrDestroy( stream, - err !== null && err !== void 0 ? err : new ERR_MULTIPLE_CALLBACK() + err !== null && err !== void 0 ? err : new ERR_MULTIPLE_CALLBACK(), ); return; } @@ -2265,7 +2265,7 @@ var require_destroy = __commonJS({ var require_legacy = __commonJS({ "node_modules/readable-stream/lib/internal/streams/legacy.js"( exports, - module + module, ) { "use strict"; var { ArrayIsArray, ObjectSetPrototypeOf } = require_primordials(); @@ -2349,7 +2349,7 @@ var require_legacy = __commonJS({ var require_add_abort_signal = __commonJS({ "node_modules/readable-stream/lib/internal/streams/add-abort-signal.js"( exports, - module + module, ) { "use strict"; var { AbortError, codes } = require_errors(); @@ -2378,7 +2378,7 @@ var require_add_abort_signal = __commonJS({ stream.destroy( new AbortError(void 0, { cause: signal.reason, - }) + }), ); }; if (signal.aborted) { @@ -2396,7 +2396,7 @@ var require_add_abort_signal = __commonJS({ var require_state = __commonJS({ "node_modules/readable-stream/lib/internal/streams/state.js"( exports, - module + module, ) { "use strict"; var { MathFloor, NumberIsInteger } = require_primordials(); @@ -2477,7 +2477,7 @@ var require_from = __commonJS({ PromisePrototypeThen( close(error), () => runOnNextTick(cb, error), - (e) => runOnNextTick(cb, e || error) + (e) => runOnNextTick(cb, e || error), ); }; async function close(error) { @@ -2531,7 +2531,7 @@ var require_from = __commonJS({ var require_readable = __commonJS({ "node_modules/readable-stream/lib/internal/streams/readable.js"( exports, - module + module, ) { "use strict"; var { @@ -2648,7 +2648,7 @@ var require_readable = __commonJS({ if (!value) throw new Error( - `Invalid value from ReadableStream reader: ${value}` + `Invalid value from ReadableStream reader: ${value}`, ); if (ArrayIsArray(value)) { this.push(...value); @@ -2698,7 +2698,7 @@ var require_readable = __commonJS({ throw new ERR_INVALID_ARG_TYPE( "readableStream", "ReadableStream", - readableStream + readableStream, ); } @@ -2783,7 +2783,7 @@ var require_readable = __commonJS({ err = new ERR_INVALID_ARG_TYPE( "chunk", ["string", "Buffer", "Uint8Array"], - chunk + chunk, ); } } @@ -3043,7 +3043,7 @@ var require_readable = __commonJS({ if (!state.multiAwaitDrain) { state.multiAwaitDrain = true; state.awaitDrainWriters = new SafeSet( - state.awaitDrainWriters ? [state.awaitDrainWriters] : [] + state.awaitDrainWriters ? [state.awaitDrainWriters] : [], ); } } @@ -3325,7 +3325,7 @@ var require_readable = __commonJS({ error = err ? aggregateTwoErrors(error, err) : null; callback(); callback = nop; - } + }, ); try { while (true) { @@ -3530,12 +3530,12 @@ var require_readable = __commonJS({ Readable.fromWeb = function (readableStream, options) { return lazyWebStreams().newStreamReadableFromReadableStream( readableStream, - options + options, ); }; Readable.toWeb = function (streamReadable) { return lazyWebStreams().newReadableStreamFromStreamReadable( - streamReadable + streamReadable, ); }; Readable.wrap = function (src, options) { @@ -3563,7 +3563,7 @@ var require_readable = __commonJS({ var require_writable = __commonJS({ "node_modules/readable-stream/lib/internal/streams/writable.js"( exports, - module + module, ) { "use strict"; var { @@ -3721,7 +3721,7 @@ var require_writable = __commonJS({ throw new ERR_INVALID_ARG_TYPE( "chunk", ["string", "Buffer", "Uint8Array"], - chunk + chunk, ); } } @@ -3753,7 +3753,7 @@ var require_writable = __commonJS({ } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding( - encoding + encoding, ) { if (typeof encoding === "string") encoding = StringPrototypeToLowerCase(encoding); @@ -3894,7 +3894,7 @@ var require_writable = __commonJS({ callback( (_state$errored = state.errored) !== null && _state$errored !== void 0 ? _state$errored - : new ERR_STREAM_DESTROYED("write") + : new ERR_STREAM_DESTROYED("write"), ); } const onfinishCallbacks = state[kOnFinished].splice(0); @@ -3904,7 +3904,7 @@ var require_writable = __commonJS({ (_state$errored2 = state.errored) !== null && _state$errored2 !== void 0 ? _state$errored2 - : new ERR_STREAM_DESTROYED("end") + : new ERR_STREAM_DESTROYED("end"), ); } resetBuffer(state); @@ -3968,7 +3968,7 @@ var require_writable = __commonJS({ encoding, }, ], - cb + cb, ); } else { throw new ERR_METHOD_NOT_IMPLEMENTED("_write()"); @@ -4035,7 +4035,7 @@ var require_writable = __commonJS({ if (called) { errorOrDestroy( stream, - err !== null && err !== void 0 ? err : ERR_MULTIPLE_CALLBACK() + err !== null && err !== void 0 ? err : ERR_MULTIPLE_CALLBACK(), ); return; } @@ -4089,7 +4089,7 @@ var require_writable = __commonJS({ } }, stream, - state + state, ); } else if (needFinish(state)) { state.pendingcb++; @@ -4238,12 +4238,12 @@ var require_writable = __commonJS({ Writable.fromWeb = function (writableStream, options) { return lazyWebStreams().newStreamWritableFromWritableStream( writableStream, - options + options, ); }; Writable.toWeb = function (streamWritable) { return lazyWebStreams().newWritableStreamFromStreamWritable( - streamWritable + streamWritable, ); }; }, @@ -4253,7 +4253,7 @@ var require_writable = __commonJS({ var require_duplexify = __commonJS({ "node_modules/readable-stream/lib/internal/streams/duplexify.js"( exports, - module + module, ) { "use strict"; var bufferModule = __require("buffer"); @@ -4356,7 +4356,7 @@ var require_duplexify = __commonJS({ }, (err) => { destroyer(d, err); - } + }, ); return (d = new Duplexify({ objectMode: true, @@ -4378,7 +4378,7 @@ var require_duplexify = __commonJS({ throw new ERR_INVALID_RETURN_VALUE( "Iterable, AsyncIterable or AsyncFunction", name, - value + value, ); } if (isBlob(body)) { @@ -4399,7 +4399,7 @@ var require_duplexify = __commonJS({ const readable = body !== null && body !== void 0 && body.readable ? isReadableNodeStream( - body === null || body === void 0 ? void 0 : body.readable + body === null || body === void 0 ? void 0 : body.readable, ) ? body === null || body === void 0 ? void 0 @@ -4409,7 +4409,7 @@ var require_duplexify = __commonJS({ const writable = body !== null && body !== void 0 && body.writable ? isWritableNodeStream( - body === null || body === void 0 ? void 0 : body.writable + body === null || body === void 0 ? void 0 : body.writable, ) ? body === null || body === void 0 ? void 0 @@ -4435,7 +4435,7 @@ var require_duplexify = __commonJS({ }, (err) => { destroyer(d, err); - } + }, ); return (d = new Duplexify({ objectMode: true, @@ -4456,7 +4456,7 @@ var require_duplexify = __commonJS({ "{ readable, writable } pair", "Promise", ], - body + body, ); }; function fromAsyncGen(fn) { @@ -4481,7 +4481,7 @@ var require_duplexify = __commonJS({ })(), { signal, - } + }, ); return { value, @@ -4635,7 +4635,7 @@ var require_duplexify = __commonJS({ var require_duplex = __commonJS({ "node_modules/readable-stream/lib/internal/streams/duplex.js"( exports, - module + module, ) { "use strict"; var { @@ -4686,35 +4686,35 @@ var require_duplex = __commonJS({ writable: ObjectGetOwnPropertyDescriptor(Writable.prototype, "writable"), writableHighWaterMark: ObjectGetOwnPropertyDescriptor( Writable.prototype, - "writableHighWaterMark" + "writableHighWaterMark", ), writableObjectMode: ObjectGetOwnPropertyDescriptor( Writable.prototype, - "writableObjectMode" + "writableObjectMode", ), writableBuffer: ObjectGetOwnPropertyDescriptor( Writable.prototype, - "writableBuffer" + "writableBuffer", ), writableLength: ObjectGetOwnPropertyDescriptor( Writable.prototype, - "writableLength" + "writableLength", ), writableFinished: ObjectGetOwnPropertyDescriptor( Writable.prototype, - "writableFinished" + "writableFinished", ), writableCorked: ObjectGetOwnPropertyDescriptor( Writable.prototype, - "writableCorked" + "writableCorked", ), writableEnded: ObjectGetOwnPropertyDescriptor( Writable.prototype, - "writableEnded" + "writableEnded", ), writableNeedDrain: ObjectGetOwnPropertyDescriptor( Writable.prototype, - "writableNeedDrain" + "writableNeedDrain", ), destroyed: { get() { @@ -4742,7 +4742,7 @@ var require_duplex = __commonJS({ Duplex.fromWeb = function (pair, options) { return lazyWebStreams().newStreamDuplexFromReadableWritablePair( pair, - options + options, ); }; Duplex.toWeb = function (duplex) { @@ -4762,7 +4762,7 @@ var require_duplex = __commonJS({ var require_transform = __commonJS({ "node_modules/readable-stream/lib/internal/streams/transform.js"( exports, - module + module, ) { "use strict"; var { ObjectSetPrototypeOf, Symbol: Symbol2 } = require_primordials(); @@ -4857,7 +4857,7 @@ var require_transform = __commonJS({ var require_passthrough = __commonJS({ "node_modules/readable-stream/lib/internal/streams/passthrough.js"( exports, - module + module, ) { "use strict"; var Transform = require_transform(); @@ -4881,7 +4881,7 @@ var require_passthrough = __commonJS({ var require_pipeline = __commonJS({ "node_modules/readable-stream/lib/internal/streams/pipeline.js"( exports, - module + module, ) { "use strict"; var { @@ -4924,7 +4924,7 @@ var require_pipeline = __commonJS({ }, (err) => { finished = !err; - } + }, ); return { destroy: (err) => { @@ -4932,7 +4932,7 @@ var require_pipeline = __commonJS({ finished = true; destroyImpl.destroyer( stream, - err || new ERR_STREAM_DESTROYED("pipe") + err || new ERR_STREAM_DESTROYED("pipe"), ); }, cleanup, @@ -4941,7 +4941,7 @@ var require_pipeline = __commonJS({ function popCallback(streams) { validateFunction( streams[streams.length - 1], - "streams[stream.length - 1]" + "streams[stream.length - 1]", ); return streams.pop(); } @@ -4954,7 +4954,7 @@ var require_pipeline = __commonJS({ throw new ERR_INVALID_ARG_TYPE( "val", ["Readable", "Iterable", "AsyncIterable"], - val + val, ); } async function* fromReadable(val) { @@ -4996,7 +4996,7 @@ var require_pipeline = __commonJS({ { readable: false, }, - resume + resume, ); try { if (writable.writableNeedDrain) { @@ -5111,7 +5111,7 @@ var require_pipeline = __commonJS({ throw new ERR_INVALID_RETURN_VALUE( "Iterable, AsyncIterable or Stream", "source", - ret + ret, ); } } else if (isIterable(stream) || isReadableNodeStream(stream)) { @@ -5129,7 +5129,7 @@ var require_pipeline = __commonJS({ throw new ERR_INVALID_RETURN_VALUE( "AsyncIterable", `transform[${i - 1}]`, - ret + ret, ); } } else { @@ -5159,7 +5159,7 @@ var require_pipeline = __commonJS({ (err) => { pt.destroy(err); runOnNextTick(finish, err); - } + }, ); } else if (isIterable(ret, true)) { finishCount++; @@ -5170,7 +5170,7 @@ var require_pipeline = __commonJS({ throw new ERR_INVALID_RETURN_VALUE( "AsyncIterable or Promise", "destination", - ret + ret, ); } ret = pt; @@ -5198,7 +5198,7 @@ var require_pipeline = __commonJS({ throw new ERR_INVALID_ARG_TYPE( "val", ["Readable", "Iterable", "AsyncIterable"], - ret + ret, ); } ret = stream; @@ -5243,7 +5243,7 @@ var require_pipeline = __commonJS({ } else { finish(err); } - } + }, ); return eos( dst, @@ -5251,7 +5251,7 @@ var require_pipeline = __commonJS({ readable: false, writable: true, }, - finish + finish, ); } module.exports = { @@ -5265,7 +5265,7 @@ var require_pipeline = __commonJS({ var require_compose = __commonJS({ "node_modules/readable-stream/lib/internal/streams/compose.js"( exports, - module + module, ) { "use strict"; var { pipeline } = require_pipeline(); @@ -5299,14 +5299,14 @@ var require_compose = __commonJS({ throw new ERR_INVALID_ARG_VALUE( `streams[${n}]`, orgStreams[n], - "must be readable" + "must be readable", ); } if (n > 0 && !isWritable(streams[n])) { throw new ERR_INVALID_ARG_VALUE( `streams[${n}]`, orgStreams[n], - "must be writable" + "must be writable", ); } } @@ -5449,7 +5449,7 @@ var require_promises = __commonJS({ { signal, end, - } + }, ); }); } diff --git a/src/bun.js/url.exports.js b/src/bun.js/url.exports.js index a59b6de08..f1478e212 100644 --- a/src/bun.js/url.exports.js +++ b/src/bun.js/url.exports.js @@ -1,2 +1,452 @@ -"use strict";const{URL:F,URLSearchParams:M,[Symbol.for("Bun.lazy")]:S}=globalThis;function it(s){return typeof s=="string"}function D(s){return typeof s=="object"&&s!==null}function I(s){return s===null}function E(s){return s==null}function ft(s){return s===void 0}function m(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var tt=/^([a-z0-9.+-]+:)/i,st=/:[0-9]*$/,ht=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,et=["<",">",'"',"`"," ","\r",` -`," "],rt=["{","}","|","\\","^","`"].concat(et),B=["'"].concat(rt),G=["%","/","?",";","#"].concat(B),J=["/","?","#"],ot=255,K=/^[+a-z0-9A-Z_-]{0,63}$/,at=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,nt={javascript:!0,"javascript:":!0},N={javascript:!0,"javascript:":!0},R={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},Z={parse(s){var r=decodeURIComponent;return(s+"").replace(/\+/g," ").split("&").filter(Boolean).reduce(function(t,o,a){var l=o.split("="),f=r(l[0]||""),h=r(l[1]||""),g=t[f];return t[f]=g===void 0?h:[].concat(g,h),t},{})},stringify(s){var r=encodeURIComponent;return Object.keys(s||{}).reduce(function(t,o){return[].concat(s[o]).forEach(function(a){t.push(r(o)+"="+r(a))}),t},[]).join("&").replace(/\s/g,"+")}};function A(s,r,t){if(s&&D(s)&&s instanceof m)return s;var o=new m;return o.parse(s,r,t),o}m.prototype.parse=function(s,r,t){if(!it(s))throw new TypeError("Parameter 'url' must be a string, not "+typeof s);var o=s.indexOf("?"),a=o!==-1&&o<s.indexOf("#")?"?":"#",l=s.split(a),f=/\\/g;l[0]=l[0].replace(f,"/"),s=l.join(a);var h=s;if(h=h.trim(),!t&&s.split("#").length===1){var g=ht.exec(h);if(g)return this.path=h,this.href=h,this.pathname=g[1],g[2]?(this.search=g[2],r?this.query=Z.parse(this.search.substr(1)):this.query=this.search.substr(1)):r&&(this.search="",this.query={}),this}var c=tt.exec(h);if(c){c=c[0];var v=c.toLowerCase();this.protocol=v,h=h.substr(c.length)}if(t||c||h.match(/^\/\/[^@\/]+@[^@\/]+/)){var j=h.substr(0,2)==="//";j&&!(c&&N[c])&&(h=h.substr(2),this.slashes=!0)}if(!N[c]&&(j||c&&!R[c])){for(var u=-1,n=0;n<J.length;n++){var b=h.indexOf(J[n]);b!==-1&&(u===-1||b<u)&&(u=b)}var P,p;u===-1?p=h.lastIndexOf("@"):p=h.lastIndexOf("@",u),p!==-1&&(P=h.slice(0,p),h=h.slice(p+1),this.auth=decodeURIComponent(P)),u=-1;for(var n=0;n<G.length;n++){var b=h.indexOf(G[n]);b!==-1&&(u===-1||b<u)&&(u=b)}u===-1&&(u=h.length),this.host=h.slice(0,u),h=h.slice(u),this.parseHost(),this.hostname=this.hostname||"";var C=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!C)for(var e=this.hostname.split(/\./),n=0,i=e.length;n<i;n++){var d=e[n];if(!!d&&!d.match(K)){for(var y="",x=0,_=d.length;x<_;x++)d.charCodeAt(x)>127?y+="x":y+=d[x];if(!y.match(K)){var q=e.slice(0,n),O=e.slice(n+1),U=d.match(at);U&&(q.push(U[1]),O.unshift(U[2])),O.length&&(h="/"+O.join(".")+h),this.hostname=q.join(".");break}}}this.hostname.length>ot?this.hostname="":this.hostname=this.hostname.toLowerCase(),C||(this.hostname=new F(`https://${this.hostname}`).hostname);var w=this.port?":"+this.port:"",H=this.hostname||"";this.host=H+w,this.href+=this.host,C&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),h[0]!=="/"&&(h="/"+h))}if(!nt[v])for(var n=0,i=B.length;n<i;n++){var L=B[n];if(h.indexOf(L)!==-1){var z=encodeURIComponent(L);z===L&&(z=escape(L)),h=h.split(L).join(z)}}var $=h.indexOf("#");$!==-1&&(this.hash=h.substr($),h=h.slice(0,$));var T=h.indexOf("?");if(T!==-1?(this.search=h.substr(T),this.query=h.substr(T+1),r&&(this.query=Z.parse(this.query)),h=h.slice(0,T)):r&&(this.search="",this.query={}),h&&(this.pathname=h),R[v]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var w=this.pathname||"",Q=this.search||"";this.path=w+Q}return this.href=this.format(),this};function V(s){return it(s)&&(s=A(s)),s instanceof m?s.format():m.prototype.format.call(s)}m.prototype.format=function(){var s=this.auth||"";s&&(s=encodeURIComponent(s),s=s.replace(/%3A/i,":"),s+="@");var r=this.protocol||"",t=this.pathname||"",o=this.hash||"",a=!1,l="";this.host?a=s+this.host:this.hostname&&(a=s+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(a+=":"+this.port)),this.query&&D(this.query)&&Object.keys(this.query).length&&(l=Z.stringify(this.query));var f=this.search||l&&"?"+l||"";return r&&r.substr(-1)!==":"&&(r+=":"),this.slashes||(!r||R[r])&&a!==!1?(a="//"+(a||""),t&&t.charAt(0)!=="/"&&(t="/"+t)):a||(a=""),o&&o.charAt(0)!=="#"&&(o="#"+o),f&&f.charAt(0)!=="?"&&(f="?"+f),t=t.replace(/[?#]/g,function(h){return encodeURIComponent(h)}),f=f.replace("#","%23"),r+a+t+f+o};function W(s,r){return A(s,!1,!0).resolve(r)}m.prototype.resolve=function(s){return this.resolveObject(A(s,!1,!0)).format()};function X(s,r){return s?A(s,!1,!0).resolveObject(r):r}m.prototype.resolveObject=function(s){if(it(s)){var r=new m;r.parse(s,!1,!0),s=r}for(var t=new m,o=Object.keys(this),a=0;a<o.length;a++){var l=o[a];t[l]=this[l]}if(t.hash=s.hash,s.href==="")return t.href=t.format(),t;if(s.slashes&&!s.protocol){for(var f=Object.keys(s),h=0;h<f.length;h++){var g=f[h];g!=="protocol"&&(t[g]=s[g])}return R[t.protocol]&&t.hostname&&!t.pathname&&(t.path=t.pathname="/"),t.href=t.format(),t}if(s.protocol&&s.protocol!==t.protocol){if(!R[s.protocol]){for(var c=Object.keys(s),v=0;v<c.length;v++){var j=c[v];t[j]=s[j]}return t.href=t.format(),t}if(t.protocol=s.protocol,!s.host&&!N[s.protocol]){for(var i=(s.pathname||"").split("/");i.length&&!(s.host=i.shift()););s.host||(s.host=""),s.hostname||(s.hostname=""),i[0]!==""&&i.unshift(""),i.length<2&&i.unshift(""),t.pathname=i.join("/")}else t.pathname=s.pathname;if(t.search=s.search,t.query=s.query,t.host=s.host||"",t.auth=s.auth,t.hostname=s.hostname||s.host,t.port=s.port,t.pathname||t.search){var u=t.pathname||"",n=t.search||"";t.path=u+n}return t.slashes=t.slashes||s.slashes,t.href=t.format(),t}var b=t.pathname&&t.pathname.charAt(0)==="/",P=s.host||s.pathname&&s.pathname.charAt(0)==="/",p=P||b||t.host&&s.pathname,C=p,e=t.pathname&&t.pathname.split("/")||[],i=s.pathname&&s.pathname.split("/")||[],d=t.protocol&&!R[t.protocol];if(d&&(t.hostname="",t.port=null,t.host&&(e[0]===""?e[0]=t.host:e.unshift(t.host)),t.host="",s.protocol&&(s.hostname=null,s.port=null,s.host&&(i[0]===""?i[0]=s.host:i.unshift(s.host)),s.host=null),p=p&&(i[0]===""||e[0]==="")),P)t.host=s.host||s.host===""?s.host:t.host,t.hostname=s.hostname||s.hostname===""?s.hostname:t.hostname,t.search=s.search,t.query=s.query,e=i;else if(i.length)e||(e=[]),e.pop(),e=e.concat(i),t.search=s.search,t.query=s.query;else if(!E(s.search)){if(d){t.hostname=t.host=e.shift();var y=t.host&&t.host.indexOf("@")>0?t.host.split("@"):!1;y&&(t.auth=y.shift(),t.host=t.hostname=y.shift())}return t.search=s.search,t.query=s.query,(!I(t.pathname)||!I(t.search))&&(t.path=(t.pathname?t.pathname:"")+(t.search?t.search:"")),t.href=t.format(),t}if(!e.length)return t.pathname=null,t.search?t.path="/"+t.search:t.path=null,t.href=t.format(),t;for(var x=e.slice(-1)[0],_=(t.host||s.host||e.length>1)&&(x==="."||x==="..")||x==="",q=0,O=e.length;O>=0;O--)x=e[O],x==="."?e.splice(O,1):x===".."?(e.splice(O,1),q++):q&&(e.splice(O,1),q--);if(!p&&!C)for(;q--;q)e.unshift("..");p&&e[0]!==""&&(!e[0]||e[0].charAt(0)!=="/")&&e.unshift(""),_&&e.join("/").substr(-1)!=="/"&&e.push("");var U=e[0]===""||e[0]&&e[0].charAt(0)==="/";if(d){t.hostname=t.host=U?"":e.length?e.shift():"";var y=t.host&&t.host.indexOf("@")>0?t.host.split("@"):!1;y&&(t.auth=y.shift(),t.host=t.hostname=y.shift())}return p=p||t.host&&e.length,p&&!U&&e.unshift(""),e.length?t.pathname=e.join("/"):(t.pathname=null,t.path=null),(!I(t.pathname)||!I(t.search))&&(t.path=(t.pathname?t.pathname:"")+(t.search?t.search:"")),t.auth=s.auth||t.auth,t.slashes=t.slashes||s.slashes,t.href=t.format(),t},m.prototype.parseHost=function(){var s=this.host,r=st.exec(s);r&&(r=r[0],r!==":"&&(this.port=r.substr(1)),s=s.substr(0,s.length-r.length)),s&&(this.hostname=s)};var Y,k;S&&(Y=S("pathToFileURL"),k=S("fileURLToPath"));var ut={parse:A,resolve:W,resolveObject:X,format:V,Url:m,pathToFileURL:Y,fileURLToPath:k,URL:F,URLSearchParams:M};"use strict";export{F as URL,M as URLSearchParams,m as Url,ut as default,k as fileURLToPath,V as format,A as parse,Y as pathToFileURL,W as resolve,X as resolveObject}; +"use strict"; +const { URL: F, URLSearchParams: M, [Symbol.for("Bun.lazy")]: S } = globalThis; +function it(s) { + return typeof s == "string"; +} +function D(s) { + return typeof s == "object" && s !== null; +} +function I(s) { + return s === null; +} +function E(s) { + return s == null; +} +function ft(s) { + return s === void 0; +} +function m() { + (this.protocol = null), + (this.slashes = null), + (this.auth = null), + (this.host = null), + (this.port = null), + (this.hostname = null), + (this.hash = null), + (this.search = null), + (this.query = null), + (this.pathname = null), + (this.path = null), + (this.href = null); +} +var tt = /^([a-z0-9.+-]+:)/i, + st = /:[0-9]*$/, + ht = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + et = [ + "<", + ">", + '"', + "`", + " ", + "\r", + ` +`, + " ", + ], + rt = ["{", "}", "|", "\\", "^", "`"].concat(et), + B = ["'"].concat(rt), + G = ["%", "/", "?", ";", "#"].concat(B), + J = ["/", "?", "#"], + ot = 255, + K = /^[+a-z0-9A-Z_-]{0,63}$/, + at = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + nt = { javascript: !0, "javascript:": !0 }, + N = { javascript: !0, "javascript:": !0 }, + R = { + http: !0, + https: !0, + ftp: !0, + gopher: !0, + file: !0, + "http:": !0, + "https:": !0, + "ftp:": !0, + "gopher:": !0, + "file:": !0, + }, + Z = { + parse(s) { + var r = decodeURIComponent; + return (s + "") + .replace(/\+/g, " ") + .split("&") + .filter(Boolean) + .reduce(function (t, o, a) { + var l = o.split("="), + f = r(l[0] || ""), + h = r(l[1] || ""), + g = t[f]; + return (t[f] = g === void 0 ? h : [].concat(g, h)), t; + }, {}); + }, + stringify(s) { + var r = encodeURIComponent; + return Object.keys(s || {}) + .reduce(function (t, o) { + return ( + [].concat(s[o]).forEach(function (a) { + t.push(r(o) + "=" + r(a)); + }), + t + ); + }, []) + .join("&") + .replace(/\s/g, "+"); + }, + }; +function A(s, r, t) { + if (s && D(s) && s instanceof m) return s; + var o = new m(); + return o.parse(s, r, t), o; +} +m.prototype.parse = function (s, r, t) { + if (!it(s)) + throw new TypeError("Parameter 'url' must be a string, not " + typeof s); + var o = s.indexOf("?"), + a = o !== -1 && o < s.indexOf("#") ? "?" : "#", + l = s.split(a), + f = /\\/g; + (l[0] = l[0].replace(f, "/")), (s = l.join(a)); + var h = s; + if (((h = h.trim()), !t && s.split("#").length === 1)) { + var g = ht.exec(h); + if (g) + return ( + (this.path = h), + (this.href = h), + (this.pathname = g[1]), + g[2] + ? ((this.search = g[2]), + r + ? (this.query = Z.parse(this.search.substr(1))) + : (this.query = this.search.substr(1))) + : r && ((this.search = ""), (this.query = {})), + this + ); + } + var c = tt.exec(h); + if (c) { + c = c[0]; + var v = c.toLowerCase(); + (this.protocol = v), (h = h.substr(c.length)); + } + if (t || c || h.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var j = h.substr(0, 2) === "//"; + j && !(c && N[c]) && ((h = h.substr(2)), (this.slashes = !0)); + } + if (!N[c] && (j || (c && !R[c]))) { + for (var u = -1, n = 0; n < J.length; n++) { + var b = h.indexOf(J[n]); + b !== -1 && (u === -1 || b < u) && (u = b); + } + var P, p; + u === -1 ? (p = h.lastIndexOf("@")) : (p = h.lastIndexOf("@", u)), + p !== -1 && + ((P = h.slice(0, p)), + (h = h.slice(p + 1)), + (this.auth = decodeURIComponent(P))), + (u = -1); + for (var n = 0; n < G.length; n++) { + var b = h.indexOf(G[n]); + b !== -1 && (u === -1 || b < u) && (u = b); + } + u === -1 && (u = h.length), + (this.host = h.slice(0, u)), + (h = h.slice(u)), + this.parseHost(), + (this.hostname = this.hostname || ""); + var C = + this.hostname[0] === "[" && + this.hostname[this.hostname.length - 1] === "]"; + if (!C) + for (var e = this.hostname.split(/\./), n = 0, i = e.length; n < i; n++) { + var d = e[n]; + if (!!d && !d.match(K)) { + for (var y = "", x = 0, _ = d.length; x < _; x++) + d.charCodeAt(x) > 127 ? (y += "x") : (y += d[x]); + if (!y.match(K)) { + var q = e.slice(0, n), + O = e.slice(n + 1), + U = d.match(at); + U && (q.push(U[1]), O.unshift(U[2])), + O.length && (h = "/" + O.join(".") + h), + (this.hostname = q.join(".")); + break; + } + } + } + this.hostname.length > ot + ? (this.hostname = "") + : (this.hostname = this.hostname.toLowerCase()), + C || (this.hostname = new F(`https://${this.hostname}`).hostname); + var w = this.port ? ":" + this.port : "", + H = this.hostname || ""; + (this.host = H + w), + (this.href += this.host), + C && + ((this.hostname = this.hostname.substr(1, this.hostname.length - 2)), + h[0] !== "/" && (h = "/" + h)); + } + if (!nt[v]) + for (var n = 0, i = B.length; n < i; n++) { + var L = B[n]; + if (h.indexOf(L) !== -1) { + var z = encodeURIComponent(L); + z === L && (z = escape(L)), (h = h.split(L).join(z)); + } + } + var $ = h.indexOf("#"); + $ !== -1 && ((this.hash = h.substr($)), (h = h.slice(0, $))); + var T = h.indexOf("?"); + if ( + (T !== -1 + ? ((this.search = h.substr(T)), + (this.query = h.substr(T + 1)), + r && (this.query = Z.parse(this.query)), + (h = h.slice(0, T))) + : r && ((this.search = ""), (this.query = {})), + h && (this.pathname = h), + R[v] && this.hostname && !this.pathname && (this.pathname = "/"), + this.pathname || this.search) + ) { + var w = this.pathname || "", + Q = this.search || ""; + this.path = w + Q; + } + return (this.href = this.format()), this; +}; +function V(s) { + return ( + it(s) && (s = A(s)), + s instanceof m ? s.format() : m.prototype.format.call(s) + ); +} +m.prototype.format = function () { + var s = this.auth || ""; + s && ((s = encodeURIComponent(s)), (s = s.replace(/%3A/i, ":")), (s += "@")); + var r = this.protocol || "", + t = this.pathname || "", + o = this.hash || "", + a = !1, + l = ""; + this.host + ? (a = s + this.host) + : this.hostname && + ((a = + s + + (this.hostname.indexOf(":") === -1 + ? this.hostname + : "[" + this.hostname + "]")), + this.port && (a += ":" + this.port)), + this.query && + D(this.query) && + Object.keys(this.query).length && + (l = Z.stringify(this.query)); + var f = this.search || (l && "?" + l) || ""; + return ( + r && r.substr(-1) !== ":" && (r += ":"), + this.slashes || ((!r || R[r]) && a !== !1) + ? ((a = "//" + (a || "")), t && t.charAt(0) !== "/" && (t = "/" + t)) + : a || (a = ""), + o && o.charAt(0) !== "#" && (o = "#" + o), + f && f.charAt(0) !== "?" && (f = "?" + f), + (t = t.replace(/[?#]/g, function (h) { + return encodeURIComponent(h); + })), + (f = f.replace("#", "%23")), + r + a + t + f + o + ); +}; +function W(s, r) { + return A(s, !1, !0).resolve(r); +} +m.prototype.resolve = function (s) { + return this.resolveObject(A(s, !1, !0)).format(); +}; +function X(s, r) { + return s ? A(s, !1, !0).resolveObject(r) : r; +} +(m.prototype.resolveObject = function (s) { + if (it(s)) { + var r = new m(); + r.parse(s, !1, !0), (s = r); + } + for (var t = new m(), o = Object.keys(this), a = 0; a < o.length; a++) { + var l = o[a]; + t[l] = this[l]; + } + if (((t.hash = s.hash), s.href === "")) return (t.href = t.format()), t; + if (s.slashes && !s.protocol) { + for (var f = Object.keys(s), h = 0; h < f.length; h++) { + var g = f[h]; + g !== "protocol" && (t[g] = s[g]); + } + return ( + R[t.protocol] && t.hostname && !t.pathname && (t.path = t.pathname = "/"), + (t.href = t.format()), + t + ); + } + if (s.protocol && s.protocol !== t.protocol) { + if (!R[s.protocol]) { + for (var c = Object.keys(s), v = 0; v < c.length; v++) { + var j = c[v]; + t[j] = s[j]; + } + return (t.href = t.format()), t; + } + if (((t.protocol = s.protocol), !s.host && !N[s.protocol])) { + for ( + var i = (s.pathname || "").split("/"); + i.length && !(s.host = i.shift()); + + ); + s.host || (s.host = ""), + s.hostname || (s.hostname = ""), + i[0] !== "" && i.unshift(""), + i.length < 2 && i.unshift(""), + (t.pathname = i.join("/")); + } else t.pathname = s.pathname; + if ( + ((t.search = s.search), + (t.query = s.query), + (t.host = s.host || ""), + (t.auth = s.auth), + (t.hostname = s.hostname || s.host), + (t.port = s.port), + t.pathname || t.search) + ) { + var u = t.pathname || "", + n = t.search || ""; + t.path = u + n; + } + return (t.slashes = t.slashes || s.slashes), (t.href = t.format()), t; + } + var b = t.pathname && t.pathname.charAt(0) === "/", + P = s.host || (s.pathname && s.pathname.charAt(0) === "/"), + p = P || b || (t.host && s.pathname), + C = p, + e = (t.pathname && t.pathname.split("/")) || [], + i = (s.pathname && s.pathname.split("/")) || [], + d = t.protocol && !R[t.protocol]; + if ( + (d && + ((t.hostname = ""), + (t.port = null), + t.host && (e[0] === "" ? (e[0] = t.host) : e.unshift(t.host)), + (t.host = ""), + s.protocol && + ((s.hostname = null), + (s.port = null), + s.host && (i[0] === "" ? (i[0] = s.host) : i.unshift(s.host)), + (s.host = null)), + (p = p && (i[0] === "" || e[0] === ""))), + P) + ) + (t.host = s.host || s.host === "" ? s.host : t.host), + (t.hostname = s.hostname || s.hostname === "" ? s.hostname : t.hostname), + (t.search = s.search), + (t.query = s.query), + (e = i); + else if (i.length) + e || (e = []), + e.pop(), + (e = e.concat(i)), + (t.search = s.search), + (t.query = s.query); + else if (!E(s.search)) { + if (d) { + t.hostname = t.host = e.shift(); + var y = t.host && t.host.indexOf("@") > 0 ? t.host.split("@") : !1; + y && ((t.auth = y.shift()), (t.host = t.hostname = y.shift())); + } + return ( + (t.search = s.search), + (t.query = s.query), + (!I(t.pathname) || !I(t.search)) && + (t.path = (t.pathname ? t.pathname : "") + (t.search ? t.search : "")), + (t.href = t.format()), + t + ); + } + if (!e.length) + return ( + (t.pathname = null), + t.search ? (t.path = "/" + t.search) : (t.path = null), + (t.href = t.format()), + t + ); + for ( + var x = e.slice(-1)[0], + _ = + ((t.host || s.host || e.length > 1) && (x === "." || x === "..")) || + x === "", + q = 0, + O = e.length; + O >= 0; + O-- + ) + (x = e[O]), + x === "." + ? e.splice(O, 1) + : x === ".." + ? (e.splice(O, 1), q++) + : q && (e.splice(O, 1), q--); + if (!p && !C) for (; q--; q) e.unshift(".."); + p && e[0] !== "" && (!e[0] || e[0].charAt(0) !== "/") && e.unshift(""), + _ && e.join("/").substr(-1) !== "/" && e.push(""); + var U = e[0] === "" || (e[0] && e[0].charAt(0) === "/"); + if (d) { + t.hostname = t.host = U ? "" : e.length ? e.shift() : ""; + var y = t.host && t.host.indexOf("@") > 0 ? t.host.split("@") : !1; + y && ((t.auth = y.shift()), (t.host = t.hostname = y.shift())); + } + return ( + (p = p || (t.host && e.length)), + p && !U && e.unshift(""), + e.length + ? (t.pathname = e.join("/")) + : ((t.pathname = null), (t.path = null)), + (!I(t.pathname) || !I(t.search)) && + (t.path = (t.pathname ? t.pathname : "") + (t.search ? t.search : "")), + (t.auth = s.auth || t.auth), + (t.slashes = t.slashes || s.slashes), + (t.href = t.format()), + t + ); +}), + (m.prototype.parseHost = function () { + var s = this.host, + r = st.exec(s); + r && + ((r = r[0]), + r !== ":" && (this.port = r.substr(1)), + (s = s.substr(0, s.length - r.length))), + s && (this.hostname = s); + }); +var Y, k; +S && ((Y = S("pathToFileURL")), (k = S("fileURLToPath"))); +var ut = { + parse: A, + resolve: W, + resolveObject: X, + format: V, + Url: m, + pathToFileURL: Y, + fileURLToPath: k, + URL: F, + URLSearchParams: M, +}; +("use strict"); +export { + F as URL, + M as URLSearchParams, + m as Url, + ut as default, + k as fileURLToPath, + V as format, + A as parse, + Y as pathToFileURL, + W as resolve, + X as resolveObject, +}; diff --git a/src/bun.js/ws.exports.js b/src/bun.js/ws.exports.js index 90d3f8911..d7a79b0b7 100644 --- a/src/bun.js/ws.exports.js +++ b/src/bun.js/ws.exports.js @@ -81,7 +81,7 @@ var Receiver = (BunWebSocket.Receiver = class Receiver { }); var createWebSocketStream = (BunWebSocket.createWebSocketStream = function ( - ws + ws, ) { throw new Error("Not supported in Bun"); }); diff --git a/src/cli/tsconfig-for-init.json b/src/cli/tsconfig-for-init.json index a659f9e5b..30522c12f 100644 --- a/src/cli/tsconfig-for-init.json +++ b/src/cli/tsconfig-for-init.json @@ -5,15 +5,16 @@ ], "module": "esnext", "target": "esnext", - "moduleResolution": "node", + "moduleResolution": "nodenext", "strict": true, + "downlevelIteration": true, "skipLibCheck": true, + "jsx": "preserve", + "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, - // so that if your project isn't using TypeScript, it still has autocomplete "allowJs": true, - // "bun-types" is the important part "types": [ - "bun-types" + "bun-types" // add Bun global ] } }
\ No newline at end of file diff --git a/src/fallback.ts b/src/fallback.ts index 103c9db1d..964ed4e92 100644 --- a/src/fallback.ts +++ b/src/fallback.ts @@ -1,3 +1,4 @@ +declare var document: any; import { ByteBuffer } from "peechy"; import { FallbackStep } from "./api/schema"; import { @@ -7,7 +8,7 @@ import { function getFallbackInfo(): FallbackMessageContainer { const binary_string = globalThis.atob( - document.getElementById("__bunfallback").textContent.trim() + document.getElementById("__bunfallback").textContent.trim(), ); var len = binary_string.length; diff --git a/src/node-fallbacks/@vercel_fetch.js b/src/node-fallbacks/@vercel_fetch.js index 95314ba9e..f75604b2b 100644 --- a/src/node-fallbacks/@vercel_fetch.js +++ b/src/node-fallbacks/@vercel_fetch.js @@ -1,6 +1,6 @@ // This is just a no-op. Intent is to prevent importing a bunch of stuff that isn't relevant. module.exports = ( - wrapper = "Bun" in globalThis ? Bun.fetch : globalThis.fetch + wrapper = "Bun" in globalThis ? Bun.fetch : globalThis.fetch, ) => { async function vercelFetch(url, opts = {}) { // Convert Object bodies to JSON if they are JS objects diff --git a/src/node-fallbacks/assert.js b/src/node-fallbacks/assert.js index a62319d0a..3636f90e3 100644 --- a/src/node-fallbacks/assert.js +++ b/src/node-fallbacks/assert.js @@ -1 +1 @@ -export * from 'assert';
\ No newline at end of file +export * from "assert"; diff --git a/src/node-fallbacks/events.js b/src/node-fallbacks/events.js index e5b3d28df..738bf1f15 100644 --- a/src/node-fallbacks/events.js +++ b/src/node-fallbacks/events.js @@ -35,7 +35,7 @@ if (R && typeof R.ownKeys === "function") { } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target).concat( - Object.getOwnPropertySymbols(target) + Object.getOwnPropertySymbols(target), ); }; } else { @@ -73,7 +73,7 @@ function checkListener(listener) { if (typeof listener !== "function") { throw new TypeError( 'The "listener" argument must be of type Function. Received type ' + - typeof listener + typeof listener, ); } } @@ -88,7 +88,7 @@ Object.defineProperty(EventEmitter, "defaultMaxListeners", { throw new RangeError( 'The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + - "." + ".", ); } defaultMaxListeners = arg; @@ -114,7 +114,7 @@ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { throw new RangeError( 'The value of "n" is out of range. It must be a non-negative number. Received ' + n + - "." + ".", ); } this._maxListeners = n; @@ -150,7 +150,7 @@ EventEmitter.prototype.emit = function emit(type) { } // At least give some kind of context to the user var err = new Error( - "Unhandled error." + (er ? " (" + er.message + ")" : "") + "Unhandled error." + (er ? " (" + er.message + ")" : ""), ); err.context = er; throw err; // Unhandled 'error' event @@ -189,7 +189,7 @@ function _addListener(target, type, listener, prepend) { target.emit( "newListener", type, - listener.listener ? listener.listener : listener + listener.listener ? listener.listener : listener, ); // Re-assign `events` because a newListener handler could have caused the @@ -229,7 +229,7 @@ function _addListener(target, type, listener, prepend) { String(type) + " listeners " + "added. Use emitter.setMaxListeners() to " + - "increase limit" + "increase limit", ); w.name = "MaxListenersExceededWarning"; w.emitter = target; @@ -250,7 +250,7 @@ EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener( type, - listener + listener, ) { return _addListener(this, type, listener, true); }; @@ -286,7 +286,7 @@ EventEmitter.prototype.once = function once(type, listener) { EventEmitter.prototype.prependOnceListener = function prependOnceListener( type, - listener + listener, ) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); @@ -296,7 +296,7 @@ EventEmitter.prototype.prependOnceListener = function prependOnceListener( // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener( type, - listener + listener, ) { var list, events, position, i, originalListener; @@ -511,7 +511,7 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) { } else { throw new TypeError( 'The "emitter" argument must be of type EventEmitter. Received type ' + - typeof emitter + typeof emitter, ); } } diff --git a/src/node-fallbacks/net.js b/src/node-fallbacks/net.js index 8f58ce134..77afb4980 100644 --- a/src/node-fallbacks/net.js +++ b/src/node-fallbacks/net.js @@ -20,22 +20,24 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. // IPv4 Segment -const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'; +const v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; const v4Str = `(${v4Seg}[.]){3}${v4Seg}`; const IPv4Reg = new RegExp(`^${v4Str}$`); // IPv6 Segment -const v6Seg = '(?:[0-9a-fA-F]{1,4})'; -const IPv6Reg = new RegExp('^(' + - `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` + - `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` + - `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` + - `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` + - `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` + - `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` + - `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` + - `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + -')(%[0-9a-zA-Z-.:]{1,})?$'); +const v6Seg = "(?:[0-9a-fA-F]{1,4})"; +const IPv6Reg = new RegExp( + "^(" + + `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` + + `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` + + `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` + + `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` + + `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` + + `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` + + `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` + + `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + + ")(%[0-9a-zA-Z-.:]{1,})?$", +); export function isIPv4(s) { return IPv4Reg.test(s); @@ -55,4 +57,4 @@ export default { isIP, isIPv4, isIPv6, -}
\ No newline at end of file +}; diff --git a/src/react-refresh.js b/src/react-refresh.js index 65c44002f..d3453d591 100644 --- a/src/react-refresh.js +++ b/src/react-refresh.js @@ -4,6 +4,345 @@ // - inlined REACT_MEMO_TYPE & REACT_FORWARD_REF_TYPE // - minified -const F="for"in Symbol?Symbol.for("react.forward_ref"):60112,C="for"in Symbol?Symbol.for("react.memo"):60115,O=typeof WeakMap=="function"?WeakMap:Map,T=new Map,k=new O,m=new O,M=new O;let g=[];const b=new Map,w=new Map,c=new Set,p=new Set,R=typeof WeakMap=="function"?new WeakMap:null;let S=!1;function _(e){if(e.fullKey!==null)return e.fullKey;let t=e.ownKey,n;try{n=e.getCustomHooks()}catch{return e.forceReset=!0,e.fullKey=t,t}for(let o=0;o<n.length;o++){const l=n[o];if(typeof l!="function")return e.forceReset=!0,e.fullKey=t,t;const s=m.get(l);if(s===void 0)continue;const r=_(s);s.forceReset&&(e.forceReset=!0),t+=` +const F = "for" in Symbol ? Symbol.for("react.forward_ref") : 60112, + C = "for" in Symbol ? Symbol.for("react.memo") : 60115, + O = typeof WeakMap == "function" ? WeakMap : Map, + T = new Map(), + k = new O(), + m = new O(), + M = new O(); +let g = []; +const b = new Map(), + w = new Map(), + c = new Set(), + p = new Set(), + R = typeof WeakMap == "function" ? new WeakMap() : null; +let S = !1; +function _(e) { + if (e.fullKey !== null) return e.fullKey; + let t = e.ownKey, + n; + try { + n = e.getCustomHooks(); + } catch { + return (e.forceReset = !0), (e.fullKey = t), t; + } + for (let o = 0; o < n.length; o++) { + const l = n[o]; + if (typeof l != "function") return (e.forceReset = !0), (e.fullKey = t), t; + const s = m.get(l); + if (s === void 0) continue; + const r = _(s); + s.forceReset && (e.forceReset = !0), + (t += + ` --- -`+r}return e.fullKey=t,t}function D(e,t){const n=m.get(e),o=m.get(t);return n===void 0&&o===void 0?!0:!(n===void 0||o===void 0||_(n)!==_(o)||o.forceReset)}function B(e){return e.prototype&&e.prototype.isReactComponent}function v(e,t){return B(e)||B(t)?!1:!!D(e,t)}function I(e){return M.get(e)}function P(e){const t=new Map;return e.forEach((n,o)=>{t.set(o,n)}),t}function L(e){const t=new Set;return e.forEach(n=>{t.add(n)}),t}function H(e,t){try{return e[t]}catch{return}}function j(){if(g.length===0||S)return null;S=!0;try{const e=new Set,t=new Set,n=g;g=[],n.forEach(f=>{let[i,u]=f;const a=i.current;M.set(a,i),M.set(u,i),i.current=u,v(a,u)?t.add(i):e.add(i)});const o={updatedFamilies:t,staleFamilies:e};b.forEach(f=>{f.setRefreshHandler(I)});let l=!1,s=null;const r=L(p),h=L(c),d=P(w);if(r.forEach(f=>{const i=d.get(f);if(i===void 0)throw new Error("Could not find helpers for a root. This is a bug in React Refresh.");if(!p.has(f),R===null||!R.has(f))return;const u=R.get(f);try{i.scheduleRoot(f,u)}catch(a){l||(l=!0,s=a)}}),h.forEach(f=>{const i=d.get(f);if(i===void 0)throw new Error("Could not find helpers for a root. This is a bug in React Refresh.");!c.has(f);try{i.scheduleRefresh(f,o)}catch(u){l||(l=!0,s=u)}}),l)throw s;return o}finally{S=!1}}function K(e,t){if(e===null||typeof e!="function"&&typeof e!="object"||k.has(e))return;let n=T.get(t);if(n===void 0?(n={current:e},T.set(t,n)):g.push([n,e]),k.set(e,n),typeof e=="object"&&e!==null)switch(H(e,"$$typeof")){case F:K(e.render,t+"$render");break;case C:K(e.type,t+"$type");break}}function E(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=arguments.length>3?arguments[3]:void 0;if(m.has(e)||m.set(e,{forceReset:n,ownKey:t,fullKey:null,getCustomHooks:o||(()=>[])}),typeof e=="object"&&e!==null)switch(H(e,"$$typeof")){case F:E(e.render,t,n,o);break;case C:E(e.type,t,n,o);break}}function A(e){const t=m.get(e);t!==void 0&&_(t)}function $(e){return T.get(e)}function W(e){return k.get(e)}function x(e){const t=new Set;return c.forEach(n=>{const o=w.get(n);if(o===void 0)throw new Error("Could not find helpers for a root. This is a bug in React Refresh.");o.findHostInstancesForRefresh(n,e).forEach(s=>{t.add(s)})}),t}function z(e){let t=e.__REACT_DEVTOOLS_GLOBAL_HOOK__;if(t===void 0){let s=0;e.__REACT_DEVTOOLS_GLOBAL_HOOK__=t={renderers:new Map,supportsFiber:!0,inject(r){return s++},onScheduleFiberRoot(r,h,d){},onCommitFiberRoot(r,h,d,f){},onCommitFiberUnmount(){}}}if(t.isDisabled){console.warn("Something has shimmed the React DevTools global hook (__REACT_DEVTOOLS_GLOBAL_HOOK__). Fast Refresh is not compatible with this shim and will be disabled.");return}const n=t.inject;t.inject=function(s){const r=n.apply(this,arguments);return typeof s.scheduleRefresh=="function"&&typeof s.setRefreshHandler=="function"&&b.set(r,s),r},t.renderers.forEach((s,r)=>{typeof s.scheduleRefresh=="function"&&typeof s.setRefreshHandler=="function"&&b.set(r,s)});const o=t.onCommitFiberRoot,l=t.onScheduleFiberRoot||(()=>{});t.onScheduleFiberRoot=function(s,r,h){return S||(p.delete(r),R!==null&&R.set(r,h)),l.apply(this,arguments)},t.onCommitFiberRoot=function(s,r,h,d){const f=b.get(s);if(f!==void 0){w.set(r,f);const i=r.current,u=i.alternate;if(u!==null){const a=u.memoizedState!=null&&u.memoizedState.element!=null&&c.has(r),y=i.memoizedState!=null&&i.memoizedState.element!=null;!a&&y?(c.add(r),p.delete(r)):a&&y||(a&&!y?(c.delete(r),d?p.add(r):w.delete(r)):!a&&!y&&d&&p.add(r))}else c.add(r)}return o.apply(this,arguments)}}function G(){return!1}function N(){return c.size}function U(){let e,t,n=!1;return function(o,l,s,r){if(typeof l=="string")return e||(e=o,t=typeof r=="function"),o!=null&&(typeof o=="function"||typeof o=="object")&&E(o,l,s,r),o;!n&&t&&(n=!0,A(e))}}function V(e){switch(typeof e){case"function":{if(e.prototype!=null){if(e.prototype.isReactComponent)return!0;const n=Object.getOwnPropertyNames(e.prototype);if(n.length>1||n[0]!=="constructor"||e.prototype.__proto__!==Object.prototype)return!1}const t=e.name||e.displayName;return typeof t=="string"&&/^[A-Z]/.test(t)}case"object":{if(e!=null)switch(H(e,"$$typeof")){case F:case C:return!0;default:return!1}return!1}default:return!1}}export{N as _getMountedRootCount,A as collectCustomHooksForSignature,U as createSignatureFunctionForTransform,x as findAffectedHostInstances,$ as getFamilyByID,W as getFamilyByType,G as hasUnrecoverableErrors,z as injectIntoGlobalHook,V as isLikelyComponentType,j as performReactRefresh,K as register,E as setSignature}; +` + r); + } + return (e.fullKey = t), t; +} +function D(e, t) { + const n = m.get(e), + o = m.get(t); + return n === void 0 && o === void 0 + ? !0 + : !(n === void 0 || o === void 0 || _(n) !== _(o) || o.forceReset); +} +function B(e) { + return e.prototype && e.prototype.isReactComponent; +} +function v(e, t) { + return B(e) || B(t) ? !1 : !!D(e, t); +} +function I(e) { + return M.get(e); +} +function P(e) { + const t = new Map(); + return ( + e.forEach((n, o) => { + t.set(o, n); + }), + t + ); +} +function L(e) { + const t = new Set(); + return ( + e.forEach((n) => { + t.add(n); + }), + t + ); +} +function H(e, t) { + try { + return e[t]; + } catch { + return; + } +} +function j() { + if (g.length === 0 || S) return null; + S = !0; + try { + const e = new Set(), + t = new Set(), + n = g; + (g = []), + n.forEach((f) => { + let [i, u] = f; + const a = i.current; + M.set(a, i), + M.set(u, i), + (i.current = u), + v(a, u) ? t.add(i) : e.add(i); + }); + const o = { updatedFamilies: t, staleFamilies: e }; + b.forEach((f) => { + f.setRefreshHandler(I); + }); + let l = !1, + s = null; + const r = L(p), + h = L(c), + d = P(w); + if ( + (r.forEach((f) => { + const i = d.get(f); + if (i === void 0) + throw new Error( + "Could not find helpers for a root. This is a bug in React Refresh.", + ); + if ((!p.has(f), R === null || !R.has(f))) return; + const u = R.get(f); + try { + i.scheduleRoot(f, u); + } catch (a) { + l || ((l = !0), (s = a)); + } + }), + h.forEach((f) => { + const i = d.get(f); + if (i === void 0) + throw new Error( + "Could not find helpers for a root. This is a bug in React Refresh.", + ); + !c.has(f); + try { + i.scheduleRefresh(f, o); + } catch (u) { + l || ((l = !0), (s = u)); + } + }), + l) + ) + throw s; + return o; + } finally { + S = !1; + } +} +function K(e, t) { + if ( + e === null || + (typeof e != "function" && typeof e != "object") || + k.has(e) + ) + return; + let n = T.get(t); + if ( + (n === void 0 ? ((n = { current: e }), T.set(t, n)) : g.push([n, e]), + k.set(e, n), + typeof e == "object" && e !== null) + ) + switch (H(e, "$$typeof")) { + case F: + K(e.render, t + "$render"); + break; + case C: + K(e.type, t + "$type"); + break; + } +} +function E(e, t) { + let n = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : !1, + o = arguments.length > 3 ? arguments[3] : void 0; + if ( + (m.has(e) || + m.set(e, { + forceReset: n, + ownKey: t, + fullKey: null, + getCustomHooks: o || (() => []), + }), + typeof e == "object" && e !== null) + ) + switch (H(e, "$$typeof")) { + case F: + E(e.render, t, n, o); + break; + case C: + E(e.type, t, n, o); + break; + } +} +function A(e) { + const t = m.get(e); + t !== void 0 && _(t); +} +function $(e) { + return T.get(e); +} +function W(e) { + return k.get(e); +} +function x(e) { + const t = new Set(); + return ( + c.forEach((n) => { + const o = w.get(n); + if (o === void 0) + throw new Error( + "Could not find helpers for a root. This is a bug in React Refresh.", + ); + o.findHostInstancesForRefresh(n, e).forEach((s) => { + t.add(s); + }); + }), + t + ); +} +function z(e) { + let t = e.__REACT_DEVTOOLS_GLOBAL_HOOK__; + if (t === void 0) { + let s = 0; + e.__REACT_DEVTOOLS_GLOBAL_HOOK__ = t = { + renderers: new Map(), + supportsFiber: !0, + inject(r) { + return s++; + }, + onScheduleFiberRoot(r, h, d) {}, + onCommitFiberRoot(r, h, d, f) {}, + onCommitFiberUnmount() {}, + }; + } + if (t.isDisabled) { + console.warn( + "Something has shimmed the React DevTools global hook (__REACT_DEVTOOLS_GLOBAL_HOOK__). Fast Refresh is not compatible with this shim and will be disabled.", + ); + return; + } + const n = t.inject; + (t.inject = function (s) { + const r = n.apply(this, arguments); + return ( + typeof s.scheduleRefresh == "function" && + typeof s.setRefreshHandler == "function" && + b.set(r, s), + r + ); + }), + t.renderers.forEach((s, r) => { + typeof s.scheduleRefresh == "function" && + typeof s.setRefreshHandler == "function" && + b.set(r, s); + }); + const o = t.onCommitFiberRoot, + l = t.onScheduleFiberRoot || (() => {}); + (t.onScheduleFiberRoot = function (s, r, h) { + return ( + S || (p.delete(r), R !== null && R.set(r, h)), l.apply(this, arguments) + ); + }), + (t.onCommitFiberRoot = function (s, r, h, d) { + const f = b.get(s); + if (f !== void 0) { + w.set(r, f); + const i = r.current, + u = i.alternate; + if (u !== null) { + const a = + u.memoizedState != null && + u.memoizedState.element != null && + c.has(r), + y = i.memoizedState != null && i.memoizedState.element != null; + !a && y + ? (c.add(r), p.delete(r)) + : (a && y) || + (a && !y + ? (c.delete(r), d ? p.add(r) : w.delete(r)) + : !a && !y && d && p.add(r)); + } else c.add(r); + } + return o.apply(this, arguments); + }); +} +function G() { + return !1; +} +function N() { + return c.size; +} +function U() { + let e, + t, + n = !1; + return function (o, l, s, r) { + if (typeof l == "string") + return ( + e || ((e = o), (t = typeof r == "function")), + o != null && + (typeof o == "function" || typeof o == "object") && + E(o, l, s, r), + o + ); + !n && t && ((n = !0), A(e)); + }; +} +function V(e) { + switch (typeof e) { + case "function": { + if (e.prototype != null) { + if (e.prototype.isReactComponent) return !0; + const n = Object.getOwnPropertyNames(e.prototype); + if ( + n.length > 1 || + n[0] !== "constructor" || + e.prototype.__proto__ !== Object.prototype + ) + return !1; + } + const t = e.name || e.displayName; + return typeof t == "string" && /^[A-Z]/.test(t); + } + case "object": { + if (e != null) + switch (H(e, "$$typeof")) { + case F: + case C: + return !0; + default: + return !1; + } + return !1; + } + default: + return !1; + } +} +export { + N as _getMountedRootCount, + A as collectCustomHooksForSignature, + U as createSignatureFunctionForTransform, + x as findAffectedHostInstances, + $ as getFamilyByID, + W as getFamilyByType, + G as hasUnrecoverableErrors, + z as injectIntoGlobalHook, + V as isLikelyComponentType, + j as performReactRefresh, + K as register, + E as setSignature, +}; diff --git a/src/runtime.footer.node.js b/src/runtime.footer.node.js index a6e425e44..b32dc78fa 100644 --- a/src/runtime.footer.node.js +++ b/src/runtime.footer.node.js @@ -48,7 +48,7 @@ var process = target = process = _process; return Reflect.has(_process, prop, receiver); }, - } + }, ); var Buffer = @@ -81,5 +81,5 @@ var Buffer = target = Buffer = NewBuffer; return Reflect.has(NewBuffer, prop, receiver); }, - } + }, ); diff --git a/src/runtime.js b/src/runtime.js index fe2f5b9df..b39eaed9d 100644 --- a/src/runtime.js +++ b/src/runtime.js @@ -45,10 +45,10 @@ export var __toModule = (module) => { "default", module && module.__esModule && "default" in module ? { get: () => module.default, enumerable: true, configurable: true } - : { value: module, enumerable: true, configurable: true } - ) + : { value: module, enumerable: true, configurable: true }, + ), ), - module + module, ); }; @@ -83,12 +83,12 @@ export var __commonJS = (cb, name) => { Object.setPrototypeOf(mod_exports, __getProtoOf(origExports)); Object.defineProperties( mod_exports, - Object.getOwnPropertyDescriptors(origExports) + Object.getOwnPropertyDescriptors(origExports), ); } else { mod_exports = __create( __getProtoOf(mod_exports), - Object.getOwnPropertyDescriptors(mod_exports) + Object.getOwnPropertyDescriptors(mod_exports), ); } } @@ -237,13 +237,15 @@ export var __merge = (props, defaultProps) => { }; export var __decorateClass = (decorators, target, key, kind) => { - var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; + var result = + kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) - if (decorator = decorators[i]) - result = (kind ? decorator(target, key, result) : decorator(result)) || result; - if (kind && result) - __defProp(target, key, result); + if ((decorator = decorators[i])) + result = + (kind ? decorator(target, key, result) : decorator(result)) || result; + if (kind && result) __defProp(target, key, result); return result; }; -export var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
\ No newline at end of file +export var __decorateParam = (index, decorator) => (target, key) => + decorator(target, key, index); diff --git a/src/runtime/errors.ts b/src/runtime/errors.ts index ad54cc322..5affd14f1 100644 --- a/src/runtime/errors.ts +++ b/src/runtime/errors.ts @@ -1,3 +1,4 @@ +// @ts-nocheck var __BuildError; var __ResolveError; var __ImportKind; diff --git a/src/runtime/hmr.ts b/src/runtime/hmr.ts index 2882744db..96122feba 100644 --- a/src/runtime/hmr.ts +++ b/src/runtime/hmr.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { ByteBuffer } from "peechy"; import * as API from "../api/schema"; @@ -178,7 +179,7 @@ if (typeof window !== "undefined") { private findMatchingSupportsRule( rule: CSSSupportsRule, id: number, - sheet: CSSStyleSheet + sheet: CSSStyleSheet, ): CSSHMRInsertionPoint | null { switch (rule.type) { // 12 is result.SUPPORTS_RULE @@ -193,7 +194,7 @@ if (typeof window !== "undefined") { const int = parseInt( rule.conditionText.substring(startIndex, endIDRegion), - 10 + 10, ); if (int !== id) { @@ -202,14 +203,14 @@ if (typeof window !== "undefined") { let startFileRegion = rule.conditionText.indexOf( '(hmr-file:"', - endIDRegion + endIDRegion, ); if (startFileRegion === -1) return null; startFileRegion += '(hmr-file:"'.length + 1; const endFileRegion = rule.conditionText.indexOf( '"', - startFileRegion + startFileRegion, ); if (endFileRegion === -1) return null; // Empty file strings are invalid @@ -220,7 +221,7 @@ if (typeof window !== "undefined") { CSSLoader.cssLoadId.sheet = sheet; CSSLoader.cssLoadId.file = rule.conditionText.substring( startFileRegion - 1, - endFileRegion + endFileRegion, ); return CSSLoader.cssLoadId; @@ -273,23 +274,23 @@ if (typeof window !== "undefined") { const bundleIdEnd = bundleIdRule.conditionText.indexOf( ")", - "(hmr-bid:".length + 1 + "(hmr-bid:".length + 1, ); if (bundleIdEnd === -1) continue; CSSLoader.cssLoadId.bundle_id = parseInt( bundleIdRule.conditionText.substring( "(hmr-bid:".length, - bundleIdEnd + bundleIdEnd, ), - 10 + 10, ); for (let j = 1; j < ruleCount && match === null; j++) { match = this.findMatchingSupportsRule( cssRules[j] as CSSSupportsRule, id, - sheet + sheet, ); } } @@ -326,20 +327,20 @@ if (typeof window !== "undefined") { const bundleIdEnd = bundleIdRule.conditionText.indexOf( ")", - "(hmr-bid:".length + 1 + "(hmr-bid:".length + 1, ); if (bundleIdEnd === -1) continue; CSSLoader.cssLoadId.bundle_id = parseInt( bundleIdRule.conditionText.substring("(hmr-bid:".length, bundleIdEnd), - 10 + 10, ); for (let j = 1; j < ruleCount && match === null; j++) { match = this.findMatchingSupportsRule( cssRules[j] as CSSSupportsRule, id, - sheet + sheet, ); } } @@ -358,7 +359,7 @@ if (typeof window !== "undefined") { handleBuildSuccess( bytes: Uint8Array, build: API.WebsocketMessageBuildSuccess, - timestamp: number + timestamp: number, ) { const start = performance.now(); var update = this.findCSSLinkTag(build.id); @@ -389,7 +390,7 @@ if (typeof window !== "undefined") { "Reloaded in", `${localDuration + fsDuration}ms`, "-", - filepath + filepath, ); update = null; @@ -445,7 +446,7 @@ if (typeof window !== "undefined") { } filePath( - file_change_notification: API.WebsocketMessageFileChangeNotification + file_change_notification: API.WebsocketMessageFileChangeNotification, ): string | null { if (file_change_notification.loader !== API.Loader.css) return null; const tag = this.findCSSLinkTag(file_change_notification.id); @@ -481,7 +482,7 @@ if (typeof window !== "undefined") { start() { if (runOnce) { __hmrlog.warn( - "Attempted to start HMR client multiple times. This may be a bug." + "Attempted to start HMR client multiple times. This may be a bug.", ); return; } @@ -514,7 +515,7 @@ if (typeof window !== "undefined") { this.nextReconnectAttempt = setTimeout( this.attemptReconnect, - this.reconnectDelay + this.reconnectDelay, ); }; @@ -608,7 +609,7 @@ if (typeof window !== "undefined") { case CSSImportState.Loaded: { promise.then( () => {}, - () => {} + () => {}, ); break; } @@ -672,19 +673,19 @@ if (typeof window !== "undefined") { link.onerror = (evt) => { console.error( `[CSS Importer] Error loading CSS file: ${urlString}\n`, - evt.toString() + evt.toString(), ); reject(); }; document.head.appendChild(link); - }).then(() => Promise.resolve()) + }).then(() => Promise.resolve()), ); } static onError(event: ErrorEvent) { if ("error" in event && !!event.error) { BunError.render( event.error, - HMRClient.client ? HMRClient.client.cwd : "" + HMRClient.client ? HMRClient.client.cwd : "", ); } } @@ -757,7 +758,7 @@ if (typeof window !== "undefined") { BunError.render(failure, this.cwd); console.group( - `Build failed: ${failure.module_path} (${failure.log.errors} errors)` + `Build failed: ${failure.module_path} (${failure.log.errors} errors)`, ); this.needsConsoleClear = true; for (let msg of failure.log.msgs) { @@ -823,7 +824,7 @@ if (typeof window !== "undefined") { `Ignoring outdated update for "${build.module_path}".\n Expected: >=`, currentVersion, `\n Received:`, - build.from_timestamp + build.from_timestamp, ); } return; @@ -834,7 +835,7 @@ if (typeof window !== "undefined") { ? new Uint8Array( buffer.data.buffer, buffer.data.byteOffset + buffer.index, - build.blob_length + build.blob_length, ) : (empty ||= new Uint8Array(0)); @@ -876,7 +877,7 @@ if (typeof window !== "undefined") { if (end > 4 && buffer.data.length >= end + 4) { new Uint8Array(this.hashBuffer.buffer).set( - buffer.data.subarray(end, end + 4) + buffer.data.subarray(end, end + 4), ); hash = this.hashBuffer[0]; } @@ -889,7 +890,7 @@ if (typeof window !== "undefined") { build, bytes, ReloadBehavior.hotReload, - hash || 0 + hash || 0, ); bytes = null; reload.timings.notify = timestamp - build.from_timestamp; @@ -911,7 +912,7 @@ if (typeof window !== "undefined") { __hmrlog.log( `[${formatDuration(timings.total)}ms] Reloaded`, - filepath + filepath, ); }, (err) => { @@ -924,7 +925,7 @@ if (typeof window !== "undefined") { } __hmrlog.error("Hot Module Reload failed!", err); debugger; - } + }, ); } @@ -942,7 +943,7 @@ if (typeof window !== "undefined") { handleFileChangeNotification( buffer: ByteBuffer, timestamp: number, - copy_file_path: boolean + copy_file_path: boolean, ) { const notification = API.decodeWebsocketMessageFileChangeNotification(buffer); @@ -977,7 +978,7 @@ if (typeof window !== "undefined") { timestamp, notification, file_path, - copy_file_path + copy_file_path, ); } @@ -985,7 +986,7 @@ if (typeof window !== "undefined") { timestamp: number, notification: API.WebsocketMessageFileChangeNotification, file_path: string, - copy_file_path: boolean + copy_file_path: boolean, ) { const accept = file_path && file_path.length > 0; @@ -1072,10 +1073,10 @@ if (typeof window !== "undefined") { const out = textEncoder.encodeInto( file_path, - writeBuffer.subarray(13) + writeBuffer.subarray(13), ); this.socket.send( - this.buildCommandBufWithFilePath.subarray(0, 13 + out.written) + this.buildCommandBufWithFilePath.subarray(0, 13 + out.written), ); } else { this.socket.send(this.buildCommandBuf); @@ -1118,7 +1119,7 @@ if (typeof window !== "undefined") { const message_header_byte_buffer = new ByteBuffer(data); const header = API.decodeWebsocketMessage(message_header_byte_buffer); const buffer = new ByteBuffer( - data.subarray(message_header_byte_buffer.index) + data.subarray(message_header_byte_buffer.index), ); switch (header.kind) { @@ -1206,7 +1207,7 @@ if (typeof window !== "undefined") { timestamp, { id, loader }, file_path, - true + true, ); break; } @@ -1233,7 +1234,7 @@ if (typeof window !== "undefined") { __hmrlog.log( "HMR connected in", formatDuration(now - clientStartTime), - "ms" + "ms", ); break; } @@ -1241,7 +1242,7 @@ if (typeof window !== "undefined") { __hmrlog.log( "Live reload connected in", formatDuration(now - clientStartTime), - "ms" + "ms", ); break; } @@ -1249,7 +1250,7 @@ if (typeof window !== "undefined") { __hmrlog.log( "Bun connected in", formatDuration(now - clientStartTime), - "ms" + "ms", ); break; } @@ -1305,7 +1306,7 @@ if (typeof window !== "undefined") { build: HotReload["build"], bytes: Uint8Array, reloader: ReloadBehavior, - hash: number + hash: number, ) { this.module_id = module_id; this.module_index = module_index; @@ -1362,7 +1363,7 @@ if (typeof window !== "undefined") { try { const blob = new Blob( sourceMapURL.length > 0 ? [this.bytes, sourceMapURL] : [this.bytes], - { type: "text/javascript" } + { type: "text/javascript" }, ); blobURL = URL.createObjectURL(blob); HMRModule.dependencies.blobToID.set(blobURL, this.module_id); @@ -1380,7 +1381,7 @@ if (typeof window !== "undefined") { globalThis.__BunRenderHMRError( exception, oldModule.file_path, - oldModule.id + oldModule.id, ); } @@ -1405,7 +1406,7 @@ if (typeof window !== "undefined") { HMRModule.dependencies.modules[this.module_index].file_path, "in", formatDuration(this.timings.import), - ". Running callbacks" + ". Running callbacks", ); } @@ -1453,7 +1454,7 @@ if (typeof window !== "undefined") { const end = Math.min( this.module_index + 1, - HMRModule.dependencies.graph_used + HMRModule.dependencies.graph_used, ); // -- For generic hot reloading -- // ES Modules delay execution until all imports are parsed @@ -1516,8 +1517,8 @@ if (typeof window !== "undefined") { } else { return Promise.reject( new ThrottleModuleUpdateError( - `Expected pendingUpdateCount: ${currentPendingUpdateCount} but received: ${pendingUpdateCount}` - ) + `Expected pendingUpdateCount: ${currentPendingUpdateCount} but received: ${pendingUpdateCount}`, + ), ); } @@ -1538,7 +1539,7 @@ if (typeof window !== "undefined") { HMRModule.dependencies.modules[this.module_index].file_path, "in", formatDuration(this.timings.callbacks), - "ms" + "ms", ); } @@ -1625,7 +1626,7 @@ if (typeof window !== "undefined") { // Grow the dependencies graph if (HMRModule.dependencies.graph.length <= this.graph_index) { const new_graph = new Uint32Array( - HMRModule.dependencies.graph.length * 4 + HMRModule.dependencies.graph.length * 4, ); new_graph.set(HMRModule.dependencies.graph); HMRModule.dependencies.graph = new_graph; @@ -1730,7 +1731,7 @@ if (typeof window !== "undefined") { $r_(Component: any, id: string) { FastRefreshLoader.RefreshRuntime.register( Component, - this.refreshRuntimeBaseID + id + this.refreshRuntimeBaseID + id, ); } // $RefreshReg$(Component, Component.name || Component.displayName) diff --git a/src/runtime/index-with-refresh.ts b/src/runtime/index-with-refresh.ts index dc0c361f8..abea4c0f4 100644 --- a/src/runtime/index-with-refresh.ts +++ b/src/runtime/index-with-refresh.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export * from "./hmr"; export * from "./errors"; export * from "./index-without-hmr"; @@ -8,4 +9,4 @@ globalThis.process ||= { cwd() { return "/bun-fake-dir/"; }, -}; +} as any; diff --git a/src/runtime/index-without-hmr.ts b/src/runtime/index-without-hmr.ts index 858688130..5fcebbc28 100644 --- a/src/runtime/index-without-hmr.ts +++ b/src/runtime/index-without-hmr.ts @@ -1,2 +1,3 @@ +// @ts-nocheck export * from "../runtime.js"; export { default as regeneratorRuntime } from "./regenerator"; diff --git a/src/runtime/index.ts b/src/runtime/index.ts index 3eebc8d5b..3c35e361c 100644 --- a/src/runtime/index.ts +++ b/src/runtime/index.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export * from "./hmr"; export * from "./errors"; export * from "./index-without-hmr"; diff --git a/src/runtime/regenerator.ts b/src/runtime/regenerator.ts index ca3780f44..0940fb9f1 100644 --- a/src/runtime/regenerator.ts +++ b/src/runtime/regenerator.ts @@ -1,3 +1,4 @@ +// @ts-nocheck /** * Copyright (c) 2014-present, Facebook, Inc. * @@ -113,7 +114,7 @@ var runtime = (function (exports) { GeneratorFunction.displayName = define( GeneratorFunctionPrototype, toStringTagSymbol, - "GeneratorFunction" + "GeneratorFunction", ); // Helper for defining the .next, .throw, and .return methods of the @@ -174,7 +175,7 @@ var runtime = (function (exports) { }, function (err) { invoke("throw", err, resolve, reject); - } + }, ); } @@ -190,7 +191,7 @@ var runtime = (function (exports) { // If a rejected Promise was yielded, throw the rejection back // into the async generator function so it can be handled there. return invoke("throw", error, resolve, reject); - } + }, ); } } @@ -222,7 +223,7 @@ var runtime = (function (exports) { callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. - callInvokeWithMethodAndArg + callInvokeWithMethodAndArg, ) : callInvokeWithMethodAndArg()); } @@ -246,7 +247,7 @@ var runtime = (function (exports) { var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList), - PromiseImpl + PromiseImpl, ); return exports.isGeneratorFunction(outerFn) @@ -358,7 +359,7 @@ var runtime = (function (exports) { context.method = "throw"; context.arg = new TypeError( - "The iterator does not provide a 'throw' method" + "The iterator does not provide a 'throw' method", ); } @@ -741,7 +742,7 @@ var runtime = (function (exports) { // as the regeneratorRuntime namespace. Otherwise create a new empty // object. Either way, the resulting object will be used to initialize // the regeneratorRuntime variable at the top of this file. - typeof module === "object" ? module.exports : {} + typeof module === "object" ? module.exports : {}, ); try { diff --git a/src/test/fixtures/browsermap-false.ts b/src/test/fixtures/browsermap-false.ts index aac72e325..b4fc1ff32 100644 --- a/src/test/fixtures/browsermap-false.ts +++ b/src/test/fixtures/browsermap-false.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { Foo } from "browsermap"; console.log(Foo); diff --git a/src/test/fixtures/cannot-assign-to-import-bug.js b/src/test/fixtures/cannot-assign-to-import-bug.js index c14b96541..ccf2c6194 100644 --- a/src/test/fixtures/cannot-assign-to-import-bug.js +++ b/src/test/fixtures/cannot-assign-to-import-bug.js @@ -283,7 +283,7 @@ "Instead, assign to `this.state` directly or define a `state = {};` " + "class property with the desired state in the %s component.", callerName, - componentName + componentName, ); didWarnStateUpdateForUnmountedComponent[warningKey] = true; @@ -341,7 +341,7 @@ publicInstance, completeState, callback, - callerName + callerName, ) { warnNoop(publicInstance, "replaceState"); }, @@ -362,7 +362,7 @@ publicInstance, partialState, callback, - callerName + callerName, ) { warnNoop(publicInstance, "setState"); }, @@ -424,7 +424,7 @@ ) { { throw Error( - "setState(...): takes an object of state variables to update or a function which returns an object of state variables." + "setState(...): takes an object of state variables to update or a function which returns an object of state variables.", ); } } @@ -475,7 +475,7 @@ warn( "%s(...) is deprecated in plain JavaScript React classes. %s", info[0], - info[1] + info[1], ); return undefined; @@ -549,7 +549,7 @@ if (typeof type.tag === "number") { error( "Received an unexpected object in getComponentName(). " + - "This is likely a bug in React. Please file an issue." + "This is likely a bug in React. Please file an issue.", ); } } @@ -672,7 +672,7 @@ "in `undefined` being returned. If you need to access the same " + "value within the child component, you should pass it as a different " + "prop. (https://reactjs.org/link/special-props)", - displayName + displayName, ); } } @@ -696,7 +696,7 @@ "in `undefined` being returned. If you need to access the same " + "value within the child component, you should pass it as a different " + "prop. (https://reactjs.org/link/special-props)", - displayName + displayName, ); } } @@ -728,7 +728,7 @@ "Learn more about using refs safely here: " + "https://reactjs.org/link/strict-mode-string-ref", componentName, - config.ref + config.ref, ); didWarnAboutStringRefs[componentName] = true; @@ -905,7 +905,7 @@ self, source, ReactCurrentOwner.current, - props + props, ); } function cloneAndReplaceKey(oldElement, newKey) { @@ -916,7 +916,7 @@ oldElement._self, oldElement._source, oldElement._owner, - oldElement.props + oldElement.props, ); return newElement; } @@ -931,7 +931,7 @@ throw Error( "React.cloneElement(...): The argument must be a React element, but you passed " + element + - "." + ".", ); } } @@ -1125,7 +1125,7 @@ (mappedChild.key && (!_child || _child.key !== mappedChild.key) // $FlowFixMe Flow incorrectly thinks existing element's key can be a number ? escapeUserProvidedKey("" + mappedChild.key) + "/" : "") + - childKey + childKey, ); } @@ -1151,7 +1151,7 @@ array, escapedPrefix, nextName, - callback + callback, ); } } else { @@ -1166,7 +1166,7 @@ if (!didWarnAboutMaps) { warn( "Using Maps as children is not supported. " + - "Use an array of keyed ReactElements instead." + "Use an array of keyed ReactElements instead.", ); } @@ -1186,7 +1186,7 @@ array, escapedPrefix, nextName, - callback + callback, ); } } else if (type === "object") { @@ -1201,7 +1201,7 @@ Object.keys(children).join(", ") + "}" : childrenString) + - "). If you meant to render a collection of children, use an array instead." + "). If you meant to render a collection of children, use an array instead.", ); } } @@ -1272,7 +1272,7 @@ function () { forEachFunc.apply(this, arguments); // Don't return anything. }, - forEachContext + forEachContext, ); } /** @@ -1308,7 +1308,7 @@ if (!isValidElement(children)) { { throw Error( - "React.Children.only expected to receive a single React element child." + "React.Children.only expected to receive a single React element child.", ); } } @@ -1328,7 +1328,7 @@ error( "createContext: Expected the optional second argument to be a " + "function. Instead received: %s", - calculateChangedBits + calculateChangedBits, ); } } @@ -1377,7 +1377,7 @@ error( "Rendering <Context.Consumer.Provider> is not supported and will be removed in " + - "a future major release. Did you mean to render <Context.Provider> instead?" + "a future major release. Did you mean to render <Context.Provider> instead?", ); } @@ -1418,7 +1418,7 @@ error( "Rendering <Context.Consumer.Consumer> is not supported and will be removed in " + - "a future major release. Did you mean to render <Context.Consumer> instead?" + "a future major release. Did you mean to render <Context.Consumer> instead?", ); } @@ -1434,7 +1434,7 @@ warn( "Setting `displayName` on Context.Consumer has no effect. " + "You should set it directly on the context with Context.displayName = '%s'.", - displayName + displayName, ); hasWarnedAboutDisplayNameOnConsumer = true; @@ -1479,7 +1479,7 @@ "Instead received: %s\n\nYour code should look like: \n " + // Break up imports to avoid accidentally parsing them as dependencies. "const MyComponent = lazy(() => imp" + "ort('./MyComponent'))", - moduleObject + moduleObject, ); } } // Transition to the next state. @@ -1496,7 +1496,7 @@ rejected._status = Rejected; rejected._result = error; } - } + }, ); } @@ -1534,7 +1534,7 @@ error( "React.lazy(...): It is not supported to assign `defaultProps` to " + "a lazy component import. Either specify them where the component " + - "is defined, or create a wrapping component around it." + "is defined, or create a wrapping component around it.", ); defaultProps = newDefaultProps; // Match production behavior more closely: @@ -1554,7 +1554,7 @@ error( "React.lazy(...): It is not supported to assign `propTypes` to " + "a lazy component import. Either specify them where the component " + - "is defined, or create a wrapping component around it." + "is defined, or create a wrapping component around it.", ); propTypes = newPropTypes; // Match production behavior more closely: @@ -1577,12 +1577,12 @@ error( "forwardRef requires a render function but received a `memo` " + "component. Instead of forwardRef(memo(...)), use " + - "memo(forwardRef(...))." + "memo(forwardRef(...)).", ); } else if (typeof render !== "function") { error( "forwardRef requires a render function but was given %s.", - render === null ? "null" : typeof render + render === null ? "null" : typeof render, ); } else { if (render.length !== 0 && render.length !== 2) { @@ -1590,7 +1590,7 @@ "forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" - : "Any additional parameter will be undefined." + : "Any additional parameter will be undefined.", ); } } @@ -1599,7 +1599,7 @@ if (render.defaultProps != null || render.propTypes != null) { error( "forwardRef render functions do not support propTypes or defaultProps. " + - "Did you accidentally pass a React component?" + "Did you accidentally pass a React component?", ); } } @@ -1677,7 +1677,7 @@ error( "memo: The first argument must be a component. Instead " + "received: %s", - type === null ? "null" : typeof type + type === null ? "null" : typeof type, ); } } @@ -1715,7 +1715,7 @@ if (!(dispatcher !== null)) { { throw Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.", ); } } @@ -1738,7 +1738,7 @@ ? "\n\nDid you call array.map(useContext)? " + "Calling Hooks inside a loop is not supported. " + "Learn more at https://reactjs.org/link/rules-of-hooks" - : "" + : "", ); } // TODO: add a more generic warning for invalid values. @@ -1749,12 +1749,12 @@ if (realContext.Consumer === Context) { error( "Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be " + - "removed in a future major release. Did you mean to call useContext(Context) instead?" + "removed in a future major release. Did you mean to call useContext(Context) instead?", ); } else if (realContext.Provider === Context) { error( "Calling useContext(Context.Provider) is not supported. " + - "Did you mean to call useContext(Context) instead?" + "Did you mean to call useContext(Context) instead?", ); } } @@ -1892,7 +1892,7 @@ if (disabledDepth < 0) { error( "disabledDepth fell below zero. " + - "This is a bug in React. Please file an issue." + "This is a bug in React. Please file an issue.", ); } } @@ -2117,7 +2117,7 @@ return describeUnknownElementTypeFrameInDEV( type.type, source, - ownerFn + ownerFn, ); case REACT_BLOCK_TYPE: @@ -2133,7 +2133,7 @@ return describeUnknownElementTypeFrameInDEV( init(payload), source, - ownerFn + ownerFn, ); } catch (x) {} } @@ -2153,7 +2153,7 @@ var stack = describeUnknownElementTypeFrameInDEV( element.type, element._source, - owner ? owner.type : null + owner ? owner.type : null, ); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { @@ -2187,7 +2187,7 @@ "it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`." + - "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." + "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.", ); err.name = "Invariant Violation"; throw err; @@ -2199,7 +2199,7 @@ componentName, location, null, - "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" + "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED", ); } catch (ex) { error$1 = ex; @@ -2218,7 +2218,7 @@ componentName || "React class", location, typeSpecName, - typeof error$1 + typeof error$1, ); setCurrentlyValidatingElement(null); @@ -2249,7 +2249,7 @@ var stack = describeUnknownElementTypeFrameInDEV( element.type, element._source, - owner ? owner.type : null + owner ? owner.type : null, ); setExtraStackFrame(stack); } else { @@ -2367,7 +2367,7 @@ 'Each child in a list should have a unique "key" prop.' + "%s%s See https://reactjs.org/link/warning-keys for more information.", currentComponentErrorInfo, - childOwner + childOwner, ); setCurrentlyValidatingElement$1(null); @@ -2464,7 +2464,7 @@ error( "Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", - _name || "Unknown" + _name || "Unknown", ); } @@ -2474,7 +2474,7 @@ ) { error( "getDefaultProps is only used on classic React.createClass " + - "definitions. Use a static property named `defaultProps` instead." + "definitions. Use a static property named `defaultProps` instead.", ); } } @@ -2497,7 +2497,7 @@ error( "Invalid prop `%s` supplied to `React.Fragment`. " + "React.Fragment can only have `key` and `children` props.", - key + key, ); setCurrentlyValidatingElement$1(null); @@ -2560,7 +2560,7 @@ "built-in components) or a class/function (for composite " + "components) but got: %s.%s", typeString, - info + info, ); } } @@ -2602,7 +2602,7 @@ warn( "React.createFactory() is deprecated and will be removed in " + "a future major release. Consider using JSX " + - "or use React.createElement() directly instead." + "or use React.createElement() directly instead.", ); } // Legacy hook: remove it @@ -2611,7 +2611,7 @@ get: function () { warn( "Factory.type is deprecated. Access the class directly " + - "before passing it to createFactory." + "before passing it to createFactory.", ); Object.defineProperty(this, "type", { @@ -2730,7 +2730,7 @@ console["error"]( "This browser doesn't support requestAnimationFrame. " + "Make sure that you load a " + - "polyfill in older browsers. https://reactjs.org/link/react-polyfills" + "polyfill in older browsers. https://reactjs.org/link/react-polyfills", ); } @@ -2739,7 +2739,7 @@ console["error"]( "This browser doesn't support cancelAnimationFrame. " + "Make sure that you load a " + - "polyfill in older browsers. https://reactjs.org/link/react-polyfills" + "polyfill in older browsers. https://reactjs.org/link/react-polyfills", ); } } @@ -2769,7 +2769,7 @@ // Using console['error'] to evade Babel and ESLint console["error"]( "forceFrameRate takes a positive int between 0 and 125, " + - "forcing frame rates higher than 125 fps is not supported" + "forcing frame rates higher than 125 fps is not supported", ); return; } @@ -2794,7 +2794,7 @@ try { var hasMoreWork = scheduledHostCallback( hasTimeRemaining, - currentTime + currentTime, ); if (!hasMoreWork) { diff --git a/src/test/fixtures/class-with-property.ts b/src/test/fixtures/class-with-property.ts index 9c9aee2d4..9d555fa2f 100644 --- a/src/test/fixtures/class-with-property.ts +++ b/src/test/fixtures/class-with-property.ts @@ -1,3 +1,4 @@ +// @ts-nocheck class Foo { prop: string; } diff --git a/src/test/fixtures/default_export_hmr_identifier_ref.tsx b/src/test/fixtures/default_export_hmr_identifier_ref.tsx index 4c742c6ef..a6a961532 100644 --- a/src/test/fixtures/default_export_hmr_identifier_ref.tsx +++ b/src/test/fixtures/default_export_hmr_identifier_ref.tsx @@ -1,3 +1,4 @@ +// @ts-nocheck const Button = forwardRef<HTMLButtonElement, Props>(({}, ref) => {}); Button.displayName = "Button"; diff --git a/src/test/fixtures/exports-bug.js b/src/test/fixtures/exports-bug.js index 081b8cfa0..66574686a 100644 --- a/src/test/fixtures/exports-bug.js +++ b/src/test/fixtures/exports-bug.js @@ -213,7 +213,7 @@ function WebGLRenderer(parameters) { if (_gl === null) { if (_canvas.getContext("webgl") !== null) { throw new Error( - "Error creating WebGL context with your selected attributes." + "Error creating WebGL context with your selected attributes.", ); } else { throw new Error("Error creating WebGL context."); @@ -261,10 +261,10 @@ function WebGLRenderer(parameters) { state = new WebGLState(_gl, extensions, utils, capabilities); state.scissor( - _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor() + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(), ); state.viewport( - _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor() + _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(), ); info = new WebGLInfo(_gl); @@ -276,7 +276,7 @@ function WebGLRenderer(parameters) { properties, capabilities, utils, - info + info, ); attributes = new WebGLAttributes(_gl); geometries = new WebGLGeometries(_gl, attributes, info); @@ -290,20 +290,20 @@ function WebGLRenderer(parameters) { _this, state, objects, - _premultipliedAlpha + _premultipliedAlpha, ); bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, - capabilities + capabilities, ); indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, - capabilities + capabilities, ); info.programs = programCache.programs; @@ -334,7 +334,7 @@ function WebGLRenderer(parameters) { var shadowMap = new WebGLShadowMap( _this, objects, - capabilities.maxTextureSize + capabilities.maxTextureSize, ); this.shadowMap = shadowMap; @@ -374,7 +374,7 @@ function WebGLRenderer(parameters) { this.getSize = function (target) { if (target === undefined) { console.warn( - "WebGLRenderer: .getsize() now requires a Vector2 as an argument" + "WebGLRenderer: .getsize() now requires a Vector2 as an argument", ); target = new Vector2(); @@ -386,7 +386,7 @@ function WebGLRenderer(parameters) { this.setSize = function (width, height, updateStyle) { if (vr.isPresenting()) { console.warn( - "THREE.WebGLRenderer: Can't change size while VR device is presenting." + "THREE.WebGLRenderer: Can't change size while VR device is presenting.", ); return; } @@ -408,7 +408,7 @@ function WebGLRenderer(parameters) { this.getDrawingBufferSize = function (target) { if (target === undefined) { console.warn( - "WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument" + "WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument", ); target = new Vector2(); @@ -432,7 +432,7 @@ function WebGLRenderer(parameters) { this.getCurrentViewport = function (target) { if (target === undefined) { console.warn( - "WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument" + "WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument", ); target = new Vector4(); @@ -453,7 +453,7 @@ function WebGLRenderer(parameters) { } state.viewport( - _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor() + _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(), ); }; @@ -469,7 +469,7 @@ function WebGLRenderer(parameters) { } state.scissor( - _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor() + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(), ); }; @@ -528,7 +528,7 @@ function WebGLRenderer(parameters) { _canvas.removeEventListener( "webglcontextrestored", onContextRestore, - false + false, ); renderLists.dispose(); @@ -618,7 +618,7 @@ function WebGLRenderer(parameters) { _gl.FLOAT, false, 0, - 0 + 0, ); } @@ -633,7 +633,7 @@ function WebGLRenderer(parameters) { _gl.FLOAT, false, 0, - 0 + 0, ); } @@ -656,7 +656,7 @@ function WebGLRenderer(parameters) { _gl.FLOAT, false, 0, - 0 + 0, ); } @@ -673,7 +673,7 @@ function WebGLRenderer(parameters) { geometry, material, object, - group + group, ) { var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; @@ -811,7 +811,7 @@ function WebGLRenderer(parameters) { ) { if (extensions.get("ANGLE_instanced_arrays") === null) { console.error( - "THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays." + "THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.", ); return; } @@ -853,7 +853,7 @@ function WebGLRenderer(parameters) { if (data && data.isInstancedInterleavedBuffer) { state.enableAttributeAndDivisor( programAttribute, - data.meshPerAttribute + data.meshPerAttribute, ); if (geometry.maxInstancedCount === undefined) { @@ -870,13 +870,13 @@ function WebGLRenderer(parameters) { type, normalized, stride * bytesPerElement, - offset * bytesPerElement + offset * bytesPerElement, ); } else { if (geometryAttribute.isInstancedBufferAttribute) { state.enableAttributeAndDivisor( programAttribute, - geometryAttribute.meshPerAttribute + geometryAttribute.meshPerAttribute, ); if (geometry.maxInstancedCount === undefined) { @@ -894,7 +894,7 @@ function WebGLRenderer(parameters) { type, normalized, 0, - 0 + 0, ); } } else if (materialDefaultAttributeValues !== undefined) { @@ -984,21 +984,21 @@ function WebGLRenderer(parameters) { if (arguments[2] !== undefined) { console.warn( - "THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead." + "THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.", ); renderTarget = arguments[2]; } if (arguments[3] !== undefined) { console.warn( - "THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead." + "THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.", ); forceClear = arguments[3]; } if (!(camera && camera.isCamera)) { console.error( - "THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera." + "THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.", ); return; } @@ -1034,12 +1034,12 @@ function WebGLRenderer(parameters) { _this, scene, camera, - renderTarget || _currentRenderTarget + renderTarget || _currentRenderTarget, ); _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, - camera.matrixWorldInverse + camera.matrixWorldInverse, ); _frustum.setFromMatrix(_projScreenMatrix); @@ -1047,7 +1047,7 @@ function WebGLRenderer(parameters) { _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, - camera + camera, ); currentRenderList = renderLists.get(scene, camera); @@ -1174,7 +1174,7 @@ function WebGLRenderer(parameters) { material, groupOrder, _vector3.z, - null + null, ); } } @@ -1191,7 +1191,7 @@ function WebGLRenderer(parameters) { object.material, groupOrder, _vector3.z, - null + null, ); } else if (object.isMesh || object.isLine || object.isPoints) { if (object.isSkinnedMesh) { @@ -1222,7 +1222,7 @@ function WebGLRenderer(parameters) { groupMaterial, groupOrder, _vector3.z, - group + group, ); } } @@ -1233,7 +1233,7 @@ function WebGLRenderer(parameters) { material, groupOrder, _vector3.z, - null + null, ); } } @@ -1287,7 +1287,7 @@ function WebGLRenderer(parameters) { object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, - object.matrixWorld + object.matrixWorld, ); object.normalMatrix.getNormalMatrix(object.modelViewMatrix); @@ -1308,7 +1308,7 @@ function WebGLRenderer(parameters) { geometry, material, object, - group + group, ); } @@ -1331,7 +1331,7 @@ function WebGLRenderer(parameters) { fog, _clipping.numPlanes, _clipping.numIntersection, - object + object, ); var code = programCache.getProgramCode(material, parameters); @@ -1385,7 +1385,7 @@ function WebGLRenderer(parameters) { material, materialProperties.shader, parameters, - code + code, ); materialProperties.program = program; @@ -1478,7 +1478,7 @@ function WebGLRenderer(parameters) { material.clipShadows, camera, materialProperties, - useCache + useCache, ); } } @@ -1534,7 +1534,7 @@ function WebGLRenderer(parameters) { p_uniforms.setValue( _gl, "logDepthBufFC", - 2.0 / (Math.log(camera.far + 1.0) / Math.LN2) + 2.0 / (Math.log(camera.far + 1.0) / Math.LN2), ); } @@ -1563,7 +1563,7 @@ function WebGLRenderer(parameters) { if (uCamPos !== undefined) { uCamPos.setValue( _gl, - _vector3.setFromMatrixPosition(camera.matrixWorld) + _vector3.setFromMatrixPosition(camera.matrixWorld), ); } } @@ -1614,7 +1614,7 @@ function WebGLRenderer(parameters) { size, size, RGBAFormat, - FloatType + FloatType, ); boneTexture.needsUpdate = true; @@ -1627,7 +1627,7 @@ function WebGLRenderer(parameters) { _gl, "boneTexture", skeleton.boneTexture, - textures + textures, ); p_uniforms.setValue(_gl, "boneTextureSize", skeleton.boneTextureSize); } else { @@ -1640,12 +1640,12 @@ function WebGLRenderer(parameters) { p_uniforms.setValue( _gl, "toneMappingExposure", - _this.toneMappingExposure + _this.toneMappingExposure, ); p_uniforms.setValue( _gl, "toneMappingWhitePoint", - _this.toneMappingWhitePoint + _this.toneMappingWhitePoint, ); if (material.lights) { @@ -1728,7 +1728,7 @@ function WebGLRenderer(parameters) { _gl, materialProperties.uniformsList, m_uniforms, - textures + textures, ); } @@ -1737,7 +1737,7 @@ function WebGLRenderer(parameters) { _gl, materialProperties.uniformsList, m_uniforms, - textures + textures, ); material.uniformsNeedUpdate = false; } @@ -1795,7 +1795,7 @@ function WebGLRenderer(parameters) { uniforms.refractionRatio.value = material.refractionRatio; uniforms.maxMipLevel.value = properties.get( - material.envMap + material.envMap, ).__maxMipLevel; } @@ -2108,7 +2108,7 @@ function WebGLRenderer(parameters) { this.setRenderTarget = function ( renderTarget, activeCubeFace, - activeMipmapLevel + activeMipmapLevel, ) { _currentRenderTarget = renderTarget; _currentActiveCubeFace = activeCubeFace; @@ -2162,7 +2162,7 @@ function WebGLRenderer(parameters) { _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + (activeCubeFace || 0), textureProperties.__webglTexture, - activeMipmapLevel || 0 + activeMipmapLevel || 0, ); } }; @@ -2174,11 +2174,11 @@ function WebGLRenderer(parameters) { width, height, buffer, - activeCubeFaceIndex + activeCubeFaceIndex, ) { if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { console.error( - "THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget." + "THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.", ); return; } @@ -2212,7 +2212,7 @@ function WebGLRenderer(parameters) { _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT) ) { console.error( - "THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format." + "THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.", ); return; } @@ -2235,7 +2235,7 @@ function WebGLRenderer(parameters) { ) ) { console.error( - "THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type." + "THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.", ); return; } @@ -2259,12 +2259,12 @@ function WebGLRenderer(parameters) { height, utils.convert(textureFormat), utils.convert(textureType), - buffer + buffer, ); } } else { console.error( - "THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete." + "THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.", ); } } finally { @@ -2290,7 +2290,7 @@ function WebGLRenderer(parameters) { position.y, width, height, - 0 + 0, ); }; @@ -2298,7 +2298,7 @@ function WebGLRenderer(parameters) { position, srcTexture, dstTexture, - level + level, ) { var width = srcTexture.image.width; var height = srcTexture.image.height; @@ -2317,7 +2317,7 @@ function WebGLRenderer(parameters) { height, glFormat, glType, - srcTexture.image.data + srcTexture.image.data, ); } else { _gl.texSubImage2D( @@ -2327,14 +2327,14 @@ function WebGLRenderer(parameters) { position.y, glFormat, glType, - srcTexture.image + srcTexture.image, ); } }; if (typeof __THREE_DEVTOOLS__ !== "undefined") { __THREE_DEVTOOLS__.dispatchEvent( - new CustomEvent("observe", { detail: this }) + new CustomEvent("observe", { detail: this }), ); // eslint-disable-line no-undef } } diff --git a/src/test/fixtures/json-parser-in-typescript.js b/src/test/fixtures/json-parser-in-typescript.js index b81b6d820..51636bfee 100644 --- a/src/test/fixtures/json-parser-in-typescript.js +++ b/src/test/fixtures/json-parser-in-typescript.js @@ -3,5 +3,4 @@ // } & { // "twitter": "https://twitter.com/buildsghost" // } -export default class Foo { -} +export default class Foo {} diff --git a/src/test/fixtures/json-parser-in-typescript.ts b/src/test/fixtures/json-parser-in-typescript.ts index 8987a5f7f..6b0f9ccc2 100644 --- a/src/test/fixtures/json-parser-in-typescript.ts +++ b/src/test/fixtures/json-parser-in-typescript.ts @@ -7,11 +7,11 @@ type EatWhitespace<State extends string> = string extends State type AddKeyValue< Memo extends Record<string, any>, Key extends string, - Value extends any + Value extends any, > = Memo & { [K in Key]: Value }; type ParseJsonObject< State extends string, - Memo extends Record<string, any> = {} + Memo extends Record<string, any> = {}, > = string extends State ? ParserError<"ParseJsonObject got generic string type"> : EatWhitespace<State> extends `}${infer State}` @@ -27,18 +27,20 @@ type ParseJsonObject< : ParserError<`ParseJsonValue returned unexpected value for: ${State}`> : ParserError<`ParseJsonObject received unexpected token: ${State}`> : ParserError<`ParseJsonObject received unexpected token: ${State}`>; -type ParseJsonArray<State extends string, Memo extends any[] = []> = - string extends State - ? ParserError<"ParseJsonArray got generic string type"> +type ParseJsonArray< + State extends string, + Memo extends any[] = [], +> = string extends State + ? ParserError<"ParseJsonArray got generic string type"> + : EatWhitespace<State> extends `]${infer State}` + ? [Memo, State] + : ParseJsonValue<State> extends [infer Value, `${infer State}`] + ? EatWhitespace<State> extends `,${infer State}` + ? ParseJsonArray<EatWhitespace<State>, [...Memo, Value]> : EatWhitespace<State> extends `]${infer State}` - ? [Memo, State] - : ParseJsonValue<State> extends [infer Value, `${infer State}`] - ? EatWhitespace<State> extends `,${infer State}` - ? ParseJsonArray<EatWhitespace<State>, [...Memo, Value]> - : EatWhitespace<State> extends `]${infer State}` - ? [[...Memo, Value], State] - : ParserError<`ParseJsonArray received unexpected token: ${State}`> - : ParserError<`ParseJsonValue returned unexpected value for: ${State}`>; + ? [[...Memo, Value], State] + : ParserError<`ParseJsonArray received unexpected token: ${State}`> + : ParserError<`ParseJsonValue returned unexpected value for: ${State}`>; type ParseJsonValue<State extends string> = string extends State ? ParserError<"ParseJsonValue got generic string type"> : EatWhitespace<State> extends `null${infer State}` diff --git a/src/test/fixtures/main-field.ts b/src/test/fixtures/main-field.ts index 5f69721c8..ad159b518 100644 --- a/src/test/fixtures/main-field.ts +++ b/src/test/fixtures/main-field.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Algolia from "algoliasearch/lite"; console.log(Algolia); diff --git a/src/test/fixtures/namespaced-validators.ts b/src/test/fixtures/namespaced-validators.ts index fcafcb139..ec070e8ec 100644 --- a/src/test/fixtures/namespaced-validators.ts +++ b/src/test/fixtures/namespaced-validators.ts @@ -65,7 +65,7 @@ for (let s of strings) { console.log( `"${s}" - ${ validators[name].isAcceptable(s) ? "matches" : "does not match" - } ${name}` + } ${name}`, ); } } diff --git a/src/test/fixtures/out.esbuild.js b/src/test/fixtures/out.esbuild.js index 8afef3006..1ebec8919 100644 --- a/src/test/fixtures/out.esbuild.js +++ b/src/test/fixtures/out.esbuild.js @@ -1,2 +1 @@ -(() => { -})(); +(() => {})(); diff --git a/src/test/fixtures/simple-150x.jsx b/src/test/fixtures/simple-150x.jsx index 385d28bab..64cb88b1b 100644 --- a/src/test/fixtures/simple-150x.jsx +++ b/src/test/fixtures/simple-150x.jsx @@ -121,7 +121,7 @@ import { SPACING } from "../helpers/styles"; evt.preventDefault(); Router.pushRoute( - `/sign-up/verify?${qs.stringify({ email: this.state.email })}` + `/sign-up/verify?${qs.stringify({ email: this.state.email })}`, ); }; @@ -439,6 +439,6 @@ import { SPACING } from "../helpers/styles"; } const HomepageWithStore = withRedux(initStore, null, (dispatch) => - bindActionCreators({ updateEntities, setCurrentUser }, dispatch) + bindActionCreators({ updateEntities, setCurrentUser }, dispatch), )(LoginGate(Homepage)); })(); diff --git a/src/test/fixtures/simple.jsx b/src/test/fixtures/simple.jsx index 5ece00d59..63873fe8d 100644 --- a/src/test/fixtures/simple.jsx +++ b/src/test/fixtures/simple.jsx @@ -119,7 +119,7 @@ class SignupForm extends React.Component { evt.preventDefault(); Router.pushRoute( - `/sign-up/verify?${qs.stringify({ email: this.state.email })}` + `/sign-up/verify?${qs.stringify({ email: this.state.email })}`, ); }; @@ -429,7 +429,7 @@ class Homepage extends React.Component { } const HomepageWithStore = withRedux(initStore, null, (dispatch) => - bindActionCreators({ updateEntities, setCurrentUser }, dispatch) + bindActionCreators({ updateEntities, setCurrentUser }, dispatch), )(LoginGate(Homepage)); export default HomepageWithStore; diff --git a/src/test/fixtures/tsconfig.json b/src/test/fixtures/tsconfig.json index 04a8d8eb9..5bf130a29 100644 --- a/src/test/fixtures/tsconfig.json +++ b/src/test/fixtures/tsconfig.json @@ -1,9 +1,13 @@ { "compilerOptions": { "baseUrl": "/Users/jarredsumner/Code/bun/src/test/fixtures", + "strict": true, + "noImplicitAny": false, "paths": { - "components/*": ["components/*"] + "components/*": [ + "components/*" + ] }, "jsx": "preserve", } -} +}
\ No newline at end of file diff --git a/src/test/fixtures/type-only-import.ts b/src/test/fixtures/type-only-import.ts index af7c11a12..8ae8fda13 100644 --- a/src/test/fixtures/type-only-import.ts +++ b/src/test/fixtures/type-only-import.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { Foo } from "bacon"; import React from "react"; import * as Boom from "react"; @@ -5,7 +6,7 @@ import { createElement } from "react"; export const hello: Foo = React.createElement("div"); export const bacon: (foo: (what: Foo) => (the: Foo) => Foo) => Foo = ( - foo: Foo + foo: Foo, ) => { return createElement(true); }; diff --git a/src/test/fixtures/typescript-is-turing-complete.ts b/src/test/fixtures/typescript-is-turing-complete.ts index 11f9d5be0..5abd46b73 100644 --- a/src/test/fixtures/typescript-is-turing-complete.ts +++ b/src/test/fixtures/typescript-is-turing-complete.ts @@ -1,3 +1,4 @@ +// @ts-nocheck type StringBool = "true" | "false"; interface AnyNumber { @@ -33,7 +34,7 @@ type Subt<T1 extends AnyNumber, T2 extends AnyNumber> = { interface SubtResult< TIsOverflow extends StringBool, - TResult extends AnyNumber + TResult extends AnyNumber, > { isOverflowing: TIsOverflow; result: TResult; @@ -95,7 +96,7 @@ type Mod<TNumber extends AnyNumber, TModNumber extends AnyNumber> = { type Mod2< TNumber extends AnyNumber, TModNumber extends AnyNumber, - TSubtResult extends SubtResult<any, any> + TSubtResult extends SubtResult<any, any>, > = { true: TNumber; false: Mod<TSubtResult["result"], TModNumber>; @@ -109,7 +110,7 @@ type Equals<TNumber1 extends AnyNumber, TNumber2 extends AnyNumber> = Equals2< type Equals2< TNumber1 extends AnyNumber, TNumber2 extends AnyNumber, - TSubtResult extends SubtResult<any, any> + TSubtResult extends SubtResult<any, any>, > = { true: "false"; false: IsZero<TSubtResult["result"]>; diff --git a/test/bun.js/arraybuffersink.test.ts b/test/bun.js/arraybuffersink.test.ts index a658556a5..a0c25ceb9 100644 --- a/test/bun.js/arraybuffersink.test.ts +++ b/test/bun.js/arraybuffersink.test.ts @@ -11,14 +11,14 @@ describe("ArrayBufferSink", () => { [ ["abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"], new TextEncoder().encode( - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", ), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", ], [ ["😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌"], new TextEncoder().encode( - "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ), "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ], @@ -29,7 +29,7 @@ describe("ArrayBufferSink", () => { ], new TextEncoder().encode( "abcdefghijklmnopqrstuvwxyz" + - "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ), "abcdefghijklmnopqrstuvwxyz" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", @@ -43,7 +43,7 @@ describe("ArrayBufferSink", () => { ], new TextEncoder().encode( "abcdefghijklmnopqrstuvwxyz" + - "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ), "(rope) " + "abcdefghijklmnopqrstuvwxyz" + @@ -58,19 +58,22 @@ describe("ArrayBufferSink", () => { ], new TextEncoder().encode( "abcdefghijklmnopqrstuvwxyz" + - "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ), "(array) " + "abcdefghijklmnopqrstuvwxyz" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ], - ]; + ] as const; for (const [input, expected, label] of fixtures) { it(`${JSON.stringify(label)}`, () => { const sink = new ArrayBufferSink(); for (let i = 0; i < input.length; i++) { - sink.write(input[i]); + const el = input[i]; + if (typeof el !== "number") { + sink.write(el); + } } const output = new Uint8Array(sink.end()); for (let i = 0; i < expected.length; i++) { diff --git a/test/bun.js/bigint.test.js b/test/bun.js/bigint.test.js index 8842c49fb..46ad50b84 100644 --- a/test/bun.js/bigint.test.js +++ b/test/bun.js/bigint.test.js @@ -2,13 +2,13 @@ import { describe, expect, it } from "bun:test"; describe("BigInt", () => { it("compares correctly (literal)", () => { - expect(42n).toBe(42n); + expect(42n).toBe(42n); }); it("compares correctly (object)", () => { - expect(BigInt(42n)).toBe(BigInt(42n)); - expect(42n).toBe(BigInt(42n)); - expect(BigInt(Bun.inspect(42n).substring(0, 2))).toBe(BigInt(42n)); - expect(BigInt(42n).valueOf()).toBe(BigInt(42n)); + expect(BigInt(42n)).toBe(BigInt(42n)); + expect(42n).toBe(BigInt(42n)); + expect(BigInt(Bun.inspect(42n).substring(0, 2))).toBe(BigInt(42n)); + expect(BigInt(42n).valueOf()).toBe(BigInt(42n)); }); -}) +}); diff --git a/test/bun.js/body-mixin-errors.test.ts b/test/bun.js/body-mixin-errors.test.ts index cec812c3f..f57bbc56c 100644 --- a/test/bun.js/body-mixin-errors.test.ts +++ b/test/bun.js/body-mixin-errors.test.ts @@ -10,7 +10,7 @@ describe("body-mixin-errors", () => { try { await res.text(); throw new Error("should not get here"); - } catch (e) { + } catch (e: any) { expect(e.message).toBe("Body already used"); } }); diff --git a/test/bun.js/body-stream.test.ts b/test/bun.js/body-stream.test.ts index ec0130fbf..bc6dc10f8 100644 --- a/test/bun.js/body-stream.test.ts +++ b/test/bun.js/body-stream.test.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { file, gc, serve, ServeOptions } from "bun"; import { afterEach, describe, expect, it, test } from "bun:test"; import { readFileSync } from "fs"; @@ -15,9 +16,9 @@ var port = 4020; ]; const useRequestObjectValues = [true, false]; - for (let RequestPrototyeMixin of BodyMixin) { + for (let RequestPrototypeMixin of BodyMixin) { for (let useRequestObject of useRequestObjectValues) { - describe(`Request.prototoype.${RequestPrototyeMixin.name}() ${ + describe(`Request.prototoype.${RequestPrototypeMixin.name}() ${ useRequestObject ? "fetch(req)" : "fetch(url)" }`, () => { const inputFixture = [ @@ -33,42 +34,43 @@ var port = 4020; [ JSON.stringify( "EXTREMELY LONG VERY LONG STRING WOW SO LONG YOU WONT BELIEVE IT! ".repeat( - 100 - ) + 100, + ), ), Buffer.from( JSON.stringify( "EXTREMELY LONG VERY LONG STRING WOW SO LONG YOU WONT BELIEVE IT! ".repeat( - 100 - ) - ) + 100, + ), + ), ), ], [ JSON.stringify( "EXTREMELY LONG 🔥 UTF16 🔥 VERY LONG STRING WOW SO LONG YOU WONT BELIEVE IT! ".repeat( - 100 - ) + 100, + ), ), Buffer.from( JSON.stringify( "EXTREMELY LONG 🔥 UTF16 🔥 VERY LONG STRING WOW SO LONG YOU WONT BELIEVE IT! ".repeat( - 100 - ) - ) + 100, + ), + ), ), ], ]; + for (const [name, input] of inputFixture) { test(`${name.slice( 0, - Math.min(name.length ?? name.byteLength, 64) + Math.min(name.length ?? name.byteLength, 64), )}`, async () => { await runInServer( { async fetch(req) { - var result = await RequestPrototyeMixin.call(req); - if (RequestPrototyeMixin === Request.prototype.json) { + var result = await RequestPrototypeMixin.call(req); + if (RequestPrototypeMixin === Request.prototype.json) { result = JSON.stringify(result); } if (typeof result === "string") { @@ -76,15 +78,15 @@ var port = 4020; expect(result).toBe(name); } else if (result && result instanceof Blob) { expect(result.size).toBe( - new TextEncoder().encode(name).byteLength + new TextEncoder().encode(name).byteLength, ); expect(await result.text()).toBe(name); } else { expect(result.byteLength).toBe( - Buffer.from(input).byteLength + Buffer.from(input).byteLength, ); expect(Bun.SHA1.hash(result, "base64")).toBe( - Bun.SHA1.hash(input, "base64") + Bun.SHA1.hash(input, "base64"), ); } return new Response(result, { @@ -106,7 +108,7 @@ var port = 4020; headers: { "content-type": "text/plain", }, - }) + }), ); } else { response = await fetch(url, { @@ -120,7 +122,7 @@ var port = 4020; expect(response.status).toBe(200); expect(response.headers.get("content-length")).toBe( - String(Buffer.from(input).byteLength) + String(Buffer.from(input).byteLength), ); expect(response.headers.get("content-type")).toBe("text/plain"); expect(await response.text()).toBe(name); @@ -137,7 +139,7 @@ var port = 4020; "content-type": "text/plain", "x-counter": i, }, - }) + }), ); } else { promises[i] = await fetch(url, { @@ -156,15 +158,15 @@ var port = 4020; const response = results[i]; expect(response.status).toBe(200); expect(response.headers.get("content-length")).toBe( - String(Buffer.from(input).byteLength) + String(Buffer.from(input).byteLength), ); expect(response.headers.get("content-type")).toBe( - "text/plain" + "text/plain", ); expect(response.headers.get("x-counter")).toBe(String(i)); expect(await response.text()).toBe(name); } - } + }, ); }); } @@ -175,7 +177,7 @@ var port = 4020; async function runInServer( opts: ServeOptions, - cb: (url: string) => void | Promise<void> + cb: (url: string) => void | Promise<void>, ) { var server; server = Bun.serve({ @@ -276,7 +278,7 @@ describe("reader", function () { new Float32Array(bytes).subarray(1), new Float32Array(bytes).subarray( 0, - new Float32Array(bytes).byteLength - 1 + new Float32Array(bytes).byteLength - 1, ), new Int16Array(bytes).subarray(0, 1), new Int32Array(bytes).subarray(0, 1), @@ -295,7 +297,7 @@ describe("reader", function () { huge instanceof Blob ? Bun.SHA1.hash( new Uint8Array(await huge.arrayBuffer()), - "base64" + "base64", ) : Bun.SHA1.hash(huge, "base64"); const expectedSize = @@ -308,14 +310,14 @@ describe("reader", function () { expect(req.headers.get("x-custom")).toBe("hello"); expect(req.headers.get("content-type")).toBe("text/plain"); expect(req.headers.get("user-agent")).toBe( - navigator.userAgent + navigator.userAgent, ); gc(); expect(req.headers.get("x-custom")).toBe("hello"); expect(req.headers.get("content-type")).toBe("text/plain"); expect(req.headers.get("user-agent")).toBe( - navigator.userAgent + navigator.userAgent, ); var reader = req.body.getReader(); @@ -330,12 +332,12 @@ describe("reader", function () { gc(); expect(out.size).toBe(expectedSize); expect(Bun.SHA1.hash(await out.arrayBuffer(), "base64")).toBe( - expectedHash + expectedHash, ); expect(req.headers.get("x-custom")).toBe("hello"); expect(req.headers.get("content-type")).toBe("text/plain"); expect(req.headers.get("user-agent")).toBe( - navigator.userAgent + navigator.userAgent, ); gc(); return new Response(out, { @@ -361,7 +363,7 @@ describe("reader", function () { huge = undefined; expect(response.status).toBe(200); const response_body = new Uint8Array( - await response.arrayBuffer() + await response.arrayBuffer(), ); expect(response_body.byteLength).toBe(expectedSize); @@ -370,7 +372,7 @@ describe("reader", function () { gc(); expect(response.headers.get("content-type")).toBe("text/plain"); gc(); - } + }, ); expect(called).toBe(true); gc(); @@ -392,7 +394,7 @@ describe("reader", function () { huge instanceof Blob ? Bun.SHA1.hash( new Uint8Array(await huge.arrayBuffer()), - "base64" + "base64", ) : Bun.SHA1.hash(huge, "base64"); const expectedSize = @@ -415,19 +417,19 @@ describe("reader", function () { expect(req.headers.get("x-custom")).toBe("hello"); expect(req.headers.get("content-type")).toBe( - "text/plain" + "text/plain", ); expect(req.headers.get("user-agent")).toBe( - navigator.userAgent + navigator.userAgent, ); gc(); expect(req.headers.get("x-custom")).toBe("hello"); expect(req.headers.get("content-type")).toBe( - "text/plain" + "text/plain", ); expect(req.headers.get("user-agent")).toBe( - navigator.userAgent + navigator.userAgent, ); const direct = { @@ -464,7 +466,7 @@ describe("reader", function () { new ReadableStream(isDirectStream ? direct : web), { headers: req.headers, - } + }, ); } catch (e) { console.error(e); @@ -486,26 +488,26 @@ describe("reader", function () { huge = undefined; expect(response.status).toBe(200); const response_body = new Uint8Array( - await response.arrayBuffer() + await response.arrayBuffer(), ); expect(response_body.byteLength).toBe(expectedSize); expect(Bun.SHA1.hash(response_body, "base64")).toBe( - expectedHash + expectedHash, ); gc(); if (!response.headers.has("content-type")) { console.error( - Object.fromEntries(response.headers.entries()) + Object.fromEntries(response.headers.entries()), ); } expect(response.headers.get("content-type")).toBe( - "text/plain" + "text/plain", ); gc(); - } + }, ); expect(called).toBe(true); gc(); diff --git a/test/bun.js/buffer.test.js b/test/bun.js/buffer.test.js index 4433cf64f..5a367f725 100644 --- a/test/bun.js/buffer.test.js +++ b/test/bun.js/buffer.test.js @@ -9,7 +9,7 @@ it("Buffer.toJSON()", () => { JSON.stringify({ type: "Buffer", data: [104, 101, 108, 108, 111], - }) + }), ); }); @@ -26,7 +26,7 @@ it("buffer", () => { expect(buf.toString("utf8", 0, "hello world ".length)).toBe("hello world "); gc(); expect(buf.toString("base64url", 0, "hello world ".length)).toBe( - btoa("hello world ") + btoa("hello world "), ); gc(); expect(buf instanceof Uint8Array).toBe(true); @@ -65,7 +65,7 @@ it("Buffer", () => { it("Buffer.byteLength", () => { expect(Buffer.byteLength("😀😃😄😁😆😅😂🤣☺️😊😊😇")).toBe( - new TextEncoder().encode("😀😃😄😁😆😅😂🤣☺️😊😊😇").byteLength + new TextEncoder().encode("😀😃😄😁😆😅😂🤣☺️😊😊😇").byteLength, ); }); @@ -120,7 +120,7 @@ it("Buffer.toBuffer works", () => { expect(buf.toString("utf8", 0, "hello world ".length)).toBe("hello world "); gc(); expect(buf.toString("base64url", 0, "hello world ".length)).toBe( - btoa("hello world ") + btoa("hello world "), ); gc(); @@ -149,10 +149,10 @@ it("writeInt", () => { it("Buffer.from", () => { expect(Buffer.from("hello world").toString("utf8")).toBe("hello world"); expect(Buffer.from("hello world", "ascii").toString("utf8")).toBe( - "hello world" + "hello world", ); expect(Buffer.from("hello world", "latin1").toString("utf8")).toBe( - "hello world" + "hello world", ); gc(); expect(Buffer.from([254]).join(",")).toBe("254"); @@ -166,15 +166,15 @@ it("Buffer.from", () => { expect(Buffer.from(123).join(",")).toBe(Uint8Array.from(123).join(",")); expect(Buffer.from({ length: 124 }).join(",")).toBe( - Uint8Array.from({ length: 124 }).join(",") + Uint8Array.from({ length: 124 }).join(","), ); expect(Buffer.from(new ArrayBuffer(1024), 0, 512).join(",")).toBe( - new Uint8Array(512).join(",") + new Uint8Array(512).join(","), ); expect(Buffer.from(new Buffer(new ArrayBuffer(1024), 0, 512)).join(",")).toBe( - new Uint8Array(512).join(",") + new Uint8Array(512).join(","), ); gc(); }); @@ -254,7 +254,7 @@ it("Buffer.compare", () => { [buf.slice(i), Buffer.from(s.slice(i))], [buf.slice(0, i), Buffer.from(s.slice(0, i))], [buf.slice(-i), Buffer.from(s.slice(-i))], - [buf.slice(0, -i), Buffer.from(s.slice(0, -i))] + [buf.slice(0, -i), Buffer.from(s.slice(0, -i))], ); } @@ -375,14 +375,14 @@ it("Buffer.concat", () => { array3.fill(300); gc(); expect(Buffer.concat([array1, array2, array3]).join("")).toBe( - array1.join("") + array2.join("") + array3.join("") + array1.join("") + array2.join("") + array3.join(""), ); expect(Buffer.concat([array1, array2, array3], 222).length).toBe(222); expect( - Buffer.concat([array1, array2, array3], 222).subarray(0, 128).join("") + Buffer.concat([array1, array2, array3], 222).subarray(0, 128).join(""), ).toBe("100".repeat(128)); expect( - Buffer.concat([array1, array2, array3], 222).subarray(129, 222).join("") + Buffer.concat([array1, array2, array3], 222).subarray(129, 222).join(""), ).toBe("200".repeat(222 - 129)); }); diff --git a/test/bun.js/bun-write.test.js b/test/bun.js/bun-write.test.js index e78c05e66..e7d724572 100644 --- a/test/bun.js/bun-write.test.js +++ b/test/bun.js/bun-write.test.js @@ -6,14 +6,14 @@ import { gcTick } from "./gc"; it("Bun.write blob", async () => { await Bun.write( Bun.file("/tmp/response-file.test.txt"), - Bun.file(path.join(import.meta.dir, "fetch.js.txt")) + Bun.file(path.join(import.meta.dir, "fetch.js.txt")), ); await gcTick(); await Bun.write(Bun.file("/tmp/response-file.test.txt"), "blah blah blha"); await gcTick(); await Bun.write( Bun.file("/tmp/response-file.test.txt"), - new Uint32Array(1024) + new Uint32Array(1024), ); await gcTick(); await Bun.write("/tmp/response-file.test.txt", new Uint32Array(1024)); @@ -21,8 +21,8 @@ it("Bun.write blob", async () => { expect( await Bun.write( new TextEncoder().encode("/tmp/response-file.test.txt"), - new Uint32Array(1024) - ) + new Uint32Array(1024), + ), ).toBe(new Uint32Array(1024).byteLength); await gcTick(); }); @@ -32,7 +32,7 @@ describe("large file", () => { [ `/tmp/bun-test-large-file-${Date.now()}.txt`, "https://www.iana.org/assignments/media-types/media-types.xhtml,".repeat( - 10000 + 10000, ), ], ]; @@ -59,8 +59,8 @@ describe("large file", () => { expect(written).toBe(bytes.byteLength); expect( new Buffer(await Bun.file(filename + ".bytes").arrayBuffer()).equals( - bytes - ) + bytes, + ), ).toBe(true); try { @@ -130,7 +130,7 @@ it("Bun.file -> Bun.file", async () => { { const result = await Bun.write( Bun.file("/tmp/fetch.js.out"), - Bun.file("/tmp/fetch.js.in") + Bun.file("/tmp/fetch.js.in"), ); await gcTick(); expect(await Bun.file("/tmp/fetch.js.out").text()).toBe(text); @@ -140,10 +140,10 @@ it("Bun.file -> Bun.file", async () => { { await Bun.write( Bun.file("/tmp/fetch.js.in").slice(0, (text.length / 2) | 0), - Bun.file("/tmp/fetch.js.out") + Bun.file("/tmp/fetch.js.out"), ); expect(await Bun.file("/tmp/fetch.js.in").text()).toBe( - text.substring(0, (text.length / 2) | 0) + text.substring(0, (text.length / 2) | 0), ); } @@ -266,8 +266,8 @@ it("Bun.write(Bun.stdout, new TextEncoder().encode('Bun.write STDOUT TEST'))", a expect( await Bun.write( Bun.stdout, - new TextEncoder().encode("\nBun.write STDOUT TEST\n\n") - ) + new TextEncoder().encode("\nBun.write STDOUT TEST\n\n"), + ), ).toBe(24); }); @@ -275,8 +275,8 @@ it("Bun.write(Bun.stderr, 'new TextEncoder().encode(Bun.write STDERR TEST'))", a expect( await Bun.write( Bun.stderr, - new TextEncoder().encode("\nBun.write STDERR TEST\n\n") - ) + new TextEncoder().encode("\nBun.write STDERR TEST\n\n"), + ), ).toBe(24); }); @@ -294,6 +294,6 @@ it("Bun.write('output.html', HTMLRewriter.transform(Bun.file)))", async () => { const outpath = `/tmp/html-rewriter.${Date.now()}.html`; await Bun.write(outpath, output); expect(await Bun.file(outpath).text()).toBe( - "<div><blink>it worked!</blink></div>" + "<div><blink>it worked!</blink></div>", ); }); diff --git a/test/bun.js/bundled/tsconfig.json b/test/bun.js/bundled/tsconfig.json index 358cb5526..3ccb11ae4 100644 --- a/test/bun.js/bundled/tsconfig.json +++ b/test/bun.js/bundled/tsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { "paths": {}, - "baseUrl": "." + "baseUrl": ".", } -} +}
\ No newline at end of file diff --git a/test/bun.js/child_process-node.test.js b/test/bun.js/child_process-node.test.js index 3ac9b2fd1..17b2c4cfb 100644 --- a/test/bun.js/child_process-node.test.js +++ b/test/bun.js/child_process-node.test.js @@ -62,7 +62,7 @@ describe("ChildProcess.spawn()", () => { // message: // 'The "options" argument must be of type object.' + // `${common.invalidArgTypeHelper(options)}`, - } + }, ); }); }); @@ -81,7 +81,7 @@ describe("ChildProcess.spawn()", () => { // message: // 'The "options.file" property must be of type string.' + // `${common.invalidArgTypeHelper(file)}`, - } + }, ); }); }); @@ -104,7 +104,7 @@ describe("ChildProcess.spawn()", () => { // message: // 'The "options.envPairs" property must be an instance of Array.' + // common.invalidArgTypeHelper(envPairs), - } + }, ); }); }); @@ -124,7 +124,7 @@ describe("ChildProcess.spawn()", () => { // message: // 'The "options.args" property must be an instance of Array.' + // common.invalidArgTypeHelper(args), - } + }, ); }); }); @@ -153,7 +153,7 @@ describe("ChildProcess.spawn", () => { () => { child.kill("foo"); }, - { code: "ERR_UNKNOWN_SIGNAL", name: "TypeError" } + { code: "ERR_UNKNOWN_SIGNAL", name: "TypeError" }, ); }); @@ -194,7 +194,7 @@ describe("ChildProcess spawn bad stdio", () => { strictEqual(stdout, ""); strictEqual(stderr, ""); }, - done + done, ); }); @@ -207,7 +207,7 @@ describe("ChildProcess spawn bad stdio", () => { strictEqual(stdout, ""); strictEqual(stderr, ""); }, - done + done, ); child.emit("error", error); @@ -221,7 +221,7 @@ describe("ChildProcess spawn bad stdio", () => { strictEqual(stdout, ""); strictEqual(stderr, ""); }, - done + done, ); }); }); @@ -234,7 +234,7 @@ describe("child_process cwd", () => { function testCwd( options, { expectPidType, expectCode = 0, expectData }, - done = () => {} + done = () => {}, ) { const createDone = createDoneDotAll(done); const { mustCall } = createCallCheckCtx(createDone(1500)); @@ -268,7 +268,7 @@ describe("child_process cwd", () => { "close", mustCall(() => { expectData && strictEqual(data.trim(), expectData); - }) + }), ); return child; @@ -326,7 +326,7 @@ describe("child_process cwd", () => { expectCode: 0, expectData: platformTmpDir, }, - createDone(1500) + createDone(1500), ); const shouldExistDir = "/dev"; testCwd( @@ -336,7 +336,7 @@ describe("child_process cwd", () => { expectCode: 0, expectData: shouldExistDir, }, - createDone(1500) + createDone(1500), ); testCwd( { cwd: Bun.pathToFileURL(tmpdir.path) }, @@ -345,7 +345,7 @@ describe("child_process cwd", () => { expectCode: 0, expectData: platformTmpDir, }, - createDone(1500) + createDone(1500), ); }); @@ -375,7 +375,7 @@ describe("child_process default options", () => { assertOk( response.includes(`TMPDIR=${process.env.TMPDIR}`), "spawn did not use process.env as default " + - `(process.env.TMPDIR = ${process.env.TMPDIR})` + `(process.env.TMPDIR = ${process.env.TMPDIR})`, ); done(); }); @@ -398,7 +398,7 @@ describe("child_process double pipe", () => { if (!grep.stdin.write(data)) { echo.stdout.pause(); } - }) + }), ); // TODO(Derrick): We don't implement the full API for this yet, @@ -415,28 +415,28 @@ describe("child_process double pipe", () => { mustCall(() => { debug("echo stdout end"); grep.stdin.end(); - }) + }), ); echo.on( "exit", mustCall(() => { debug("echo exit"); - }) + }), ); grep.on( "exit", mustCall(() => { debug("grep exit"); - }) + }), ); sed.on( "exit", mustCall(() => { debug("sed exit"); - }) + }), ); // pipe grep | sed @@ -447,7 +447,7 @@ describe("child_process double pipe", () => { if (!sed.stdin.write(data)) { grep.stdout.pause(); } - }) + }), ); // // TODO(@jasnell): This does not appear to ever be @@ -462,7 +462,7 @@ describe("child_process double pipe", () => { mustCall((code) => { debug("grep stdout end"); sed.stdin.end(); - }) + }), ); let result = ""; @@ -473,7 +473,7 @@ describe("child_process double pipe", () => { mustCallAtLeast((data) => { result += data.toString("utf8"); debug(data); - }) + }), ); sed.stdout.on( @@ -481,7 +481,7 @@ describe("child_process double pipe", () => { mustCall(() => { debug("result: " + result); strictEqual(result, `hellO\nnOde\nwOrld\n`); - }) + }), ); }); }); diff --git a/test/bun.js/child_process.test.ts b/test/bun.js/child_process.test.ts index 536f4947b..fecc5b961 100644 --- a/test/bun.js/child_process.test.ts +++ b/test/bun.js/child_process.test.ts @@ -57,7 +57,9 @@ describe("spawn()", () => { let child; let child2; try { + // @ts-ignore child = spawn(123); + // @ts-ignore child2 = spawn(["echo", "hello"]); } catch (e) {} expect(!!child).toBe(false); @@ -203,12 +205,17 @@ describe("spawn()", () => { describe("execFile()", () => { it("should execute a file", async () => { const result: Buffer = await new Promise((resolve, reject) => { - execFile("bun", ["-v"], (error, stdout, stderr) => { - if (error) { - reject(error); - } - resolve(stdout); - }); + execFile( + "bun", + ["-v"], + { encoding: "buffer" }, + (error, stdout, stderr) => { + if (error) { + reject(error); + } + resolve(stdout); + }, + ); }); expect(SEMVER_REGEX.test(result.toString().trim())).toBe(true); }); @@ -217,7 +224,7 @@ describe("execFile()", () => { describe("exec()", () => { it("should execute a command in a shell", async () => { const result: Buffer = await new Promise((resolve, reject) => { - exec("bun -v", (error, stdout, stderr) => { + exec("bun -v", { encoding: "buffer" }, (error, stdout, stderr) => { if (error) { reject(error); } diff --git a/test/bun.js/concat.test.js b/test/bun.js/concat.test.js index a965fdb94..35cec4f8b 100644 --- a/test/bun.js/concat.test.js +++ b/test/bun.js/concat.test.js @@ -28,19 +28,19 @@ describe("concat", () => { it("works with one element", () => { expect(concatToString([new Uint8Array([123])])).toBe( - polyfillToString([new Uint8Array([123])]) + polyfillToString([new Uint8Array([123])]), ); }); it("works with two elements", () => { expect( - concatToString([Uint8Array.from([123]), Uint8Array.from([456])]) + concatToString([Uint8Array.from([123]), Uint8Array.from([456])]), ).toBe(polyfillToString([Uint8Array.from([123]), Uint8Array.from([456])])); }); it("works with mix of ArrayBuffer and TypedArray elements", () => { expect( - concatToString([Uint8Array.from([123]).buffer, Uint8Array.from([456])]) + concatToString([Uint8Array.from([123]).buffer, Uint8Array.from([456])]), ).toBe(polyfillToString([Uint8Array.from([123]), Uint8Array.from([456])])); }); }); diff --git a/test/bun.js/console-log.js b/test/bun.js/console-log.js index 5c110f8b0..6252d6773 100644 --- a/test/bun.js/console-log.js +++ b/test/bun.js/console-log.js @@ -36,7 +36,7 @@ console.time("Check"); console.log( "Is it a bug or a feature that formatting numbers like %d is colored", - 123 + 123, ); console.log(globalThis); @@ -46,7 +46,7 @@ console.log( "456", "%s", "What", - "okay" + "okay", ); const infinteLoop = { @@ -57,4 +57,4 @@ const infinteLoop = { infinteLoop.bar = infinteLoop; console.log(infinteLoop, "am"); -console.log(new Array(4).fill({})) +console.log(new Array(4).fill({})); diff --git a/test/bun.js/decorators.test.ts b/test/bun.js/decorators.test.ts index 545030ef1..554904107 100644 --- a/test/bun.js/decorators.test.ts +++ b/test/bun.js/decorators.test.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { test, expect } from "bun:test"; test("decorator order of evaluation", () => { @@ -264,7 +265,7 @@ test("parameter decorators", () => { two: string, three: boolean, @d1 @d2 width: number, - @d3 height: number + @d3 height: number, ) { this.width = width; this.height = height; @@ -336,7 +337,7 @@ test("parameter decorators", () => { constructor( @m1 private x: number, @m2 public y: boolean, - @m3 protected z: string + @m3 protected z: string, ) {} } diff --git a/test/bun.js/escapeHTML.test.js b/test/bun.js/escapeHTML.test.js index 5ea202a75..af119c6e3 100644 --- a/test/bun.js/escapeHTML.test.js +++ b/test/bun.js/escapeHTML.test.js @@ -14,10 +14,10 @@ describe("escapeHTML", () => { // 8. Returns the same string when there's no need to escape it("works", () => { expect(escapeHTML("absolutely nothing to do here")).toBe( - "absolutely nothing to do here" + "absolutely nothing to do here", ); expect(escapeHTML("<script>alert(1)</script>")).toBe( - "<script>alert(1)</script>" + "<script>alert(1)</script>", ); expect(escapeHTML("<")).toBe("<"); expect(escapeHTML(">")).toBe(">"); @@ -36,66 +36,66 @@ describe("escapeHTML", () => { expect(escapeHTML("<script><script>")).toBe("<script><script>"); expect(escapeHTML("lalala" + "<script>alert(1)</script>" + "lalala")).toBe( - "lalala<script>alert(1)</script>lalala" + "lalala<script>alert(1)</script>lalala", ); expect(escapeHTML("<script>alert(1)</script>" + "lalala")).toBe( - "<script>alert(1)</script>lalala" + "<script>alert(1)</script>lalala", ); expect(escapeHTML("lalala" + "<script>alert(1)</script>")).toBe( - "lalala" + "<script>alert(1)</script>" + "lalala" + "<script>alert(1)</script>", ); expect(escapeHTML("What does 😊 mean?")).toBe("What does 😊 mean?"); const output = escapeHTML("<What does 😊"); expect(output).toBe("<What does 😊"); expect(escapeHTML("<div>What does 😊 mean in text?")).toBe( - "<div>What does 😊 mean in text?" + "<div>What does 😊 mean in text?", ); expect( escapeHTML( - ("lalala" + "<script>alert(1)</script>" + "lalala").repeat(900) - ) + ("lalala" + "<script>alert(1)</script>" + "lalala").repeat(900), + ), ).toBe("lalala<script>alert(1)</script>lalala".repeat(900)); expect( - escapeHTML(("<script>alert(1)</script>" + "lalala").repeat(900)) + escapeHTML(("<script>alert(1)</script>" + "lalala").repeat(900)), ).toBe("<script>alert(1)</script>lalala".repeat(900)); expect( - escapeHTML(("lalala" + "<script>alert(1)</script>").repeat(900)) + escapeHTML(("lalala" + "<script>alert(1)</script>").repeat(900)), ).toBe(("lalala" + "<script>alert(1)</script>").repeat(900)); // the positions of the unicode codepoint are important // our simd code for U16 is at 8 bytes, so we need to especially check the boundaries expect( - escapeHTML("😊lalala" + "<script>alert(1)</script>" + "lalala") + escapeHTML("😊lalala" + "<script>alert(1)</script>" + "lalala"), ).toBe("😊lalala<script>alert(1)</script>lalala"); expect(escapeHTML("<script>😊alert(1)</script>" + "lalala")).toBe( - "<script>😊alert(1)</script>lalala" + "<script>😊alert(1)</script>lalala", ); expect(escapeHTML("<script>alert(1)😊</script>" + "lalala")).toBe( - "<script>alert(1)😊</script>lalala" + "<script>alert(1)😊</script>lalala", ); expect(escapeHTML("<script>alert(1)</script>" + "😊lalala")).toBe( - "<script>alert(1)</script>😊lalala" + "<script>alert(1)</script>😊lalala", ); expect(escapeHTML("<script>alert(1)</script>" + "lal😊ala")).toBe( - "<script>alert(1)</script>lal😊ala" + "<script>alert(1)</script>lal😊ala", ); expect( - escapeHTML("<script>alert(1)</script>" + "lal😊ala".repeat(10)) + escapeHTML("<script>alert(1)</script>" + "lal😊ala".repeat(10)), ).toBe("<script>alert(1)</script>" + "lal😊ala".repeat(10)); for (let i = 1; i < 10; i++) expect(escapeHTML("<script>alert(1)</script>" + "la😊".repeat(i))).toBe( - "<script>alert(1)</script>" + "la😊".repeat(i) + "<script>alert(1)</script>" + "la😊".repeat(i), ); expect(escapeHTML("la😊" + "<script>alert(1)</script>")).toBe( - "la😊" + "<script>alert(1)</script>" + "la😊" + "<script>alert(1)</script>", ); expect( - escapeHTML(("lalala" + "<script>alert(1)</script>😊").repeat(1)) + escapeHTML(("lalala" + "<script>alert(1)</script>😊").repeat(1)), ).toBe(("lalala" + "<script>alert(1)</script>😊").repeat(1)); expect(escapeHTML("😊".repeat(100))).toBe("😊".repeat(100)); diff --git a/test/bun.js/event-emitter.test.ts b/test/bun.js/event-emitter.test.ts index 952805cf8..f7c73e66a 100644 --- a/test/bun.js/event-emitter.test.ts +++ b/test/bun.js/event-emitter.test.ts @@ -1,4 +1,5 @@ import { test, describe, expect } from "bun:test"; +import fs from "node:fs"; // this is also testing that imports with default and named imports in the same statement work // our transpiler transform changes this to a var with import.meta.require diff --git a/test/bun.js/fetch.test.js b/test/bun.js/fetch.test.js index 603cdfb3c..ebcdcbc8b 100644 --- a/test/bun.js/fetch.test.js +++ b/test/bun.js/fetch.test.js @@ -5,7 +5,7 @@ import { gc } from "./gc"; const exampleFixture = fs.readFileSync( import.meta.path.substring(0, import.meta.path.lastIndexOf("/")) + "/fetch.js.txt", - "utf8" + "utf8", ); describe("fetch", () => { @@ -74,7 +74,7 @@ function testBlobInterface(blobbyConstructor, hasBlobFn) { var response = blobbyConstructor(JSON.stringify(jsonObject)); if (withGC) gc(); expect(JSON.stringify(await response.json())).toBe( - JSON.stringify(jsonObject) + JSON.stringify(jsonObject), ); if (withGC) gc(); }); @@ -84,11 +84,11 @@ function testBlobInterface(blobbyConstructor, hasBlobFn) { } arrayBuffer -> json${withGC ? " (with gc) " : ""}`, async () => { if (withGC) gc(); var response = blobbyConstructor( - new TextEncoder().encode(JSON.stringify(jsonObject)) + new TextEncoder().encode(JSON.stringify(jsonObject)), ); if (withGC) gc(); expect(JSON.stringify(await response.json())).toBe( - JSON.stringify(jsonObject) + JSON.stringify(jsonObject), ); if (withGC) gc(); }); @@ -108,7 +108,7 @@ function testBlobInterface(blobbyConstructor, hasBlobFn) { } arrayBuffer -> text${withGC ? " (with gc) " : ""}`, async () => { if (withGC) gc(); var response = blobbyConstructor( - new TextEncoder().encode(JSON.stringify(jsonObject)) + new TextEncoder().encode(JSON.stringify(jsonObject)), ); if (withGC) gc(); expect(await response.text()).toBe(JSON.stringify(jsonObject)); @@ -144,7 +144,7 @@ function testBlobInterface(blobbyConstructor, hasBlobFn) { if (withGC) gc(); var response = blobbyConstructor( - new TextEncoder().encode(JSON.stringify(jsonObject)) + new TextEncoder().encode(JSON.stringify(jsonObject)), ); if (withGC) gc(); @@ -219,13 +219,13 @@ describe("Blob", () => { [ new Blob([ new TextEncoder().encode( - "😀 😃 😄 😁 😆 😅 😂 🤣 🥲 ☺️ 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😗 😙 😚 😋 😛 😝 😜 🤪 🤨 🧐 🤓 😎 🥸 🤩 🥳" + "😀 😃 😄 😁 😆 😅 😂 🤣 🥲 ☺️ 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😗 😙 😚 😋 😛 😝 😜 🤪 🤨 🧐 🤓 😎 🥸 🤩 🥳", ), ]), ], [ new TextEncoder().encode( - "😀 😃 😄 😁 😆 😅 😂 🤣 🥲 ☺️ 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😗 😙 😚 😋 😛 😝 😜 🤪 🤨 🧐 🤓 😎 🥸 🤩 🥳" + "😀 😃 😄 😁 😆 😅 😂 🤣 🥲 ☺️ 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😗 😙 😚 😋 😛 😝 😜 🤪 🤨 🧐 🤓 😎 🥸 🤩 🥳", ), ], ]; @@ -253,7 +253,7 @@ describe("Blob", () => { .split("") .map((a) => a.charCodeAt(0))}, received: ${res .split("") - .map((a) => a.charCodeAt(0))}` + .map((a) => a.charCodeAt(0))}`, ); } @@ -274,7 +274,7 @@ describe("Blob", () => { expect( await combined .slice(str.indexOf(part), str.indexOf(part) + part.length) - .text() + .text(), ).toBe(part); if (withGC) gc(); } @@ -284,7 +284,7 @@ describe("Blob", () => { expect( await combined .slice(str.indexOf(part), str.indexOf(part) + part.length) - .text() + .text(), ).toBe(part); if (withGC) gc(); } @@ -358,7 +358,7 @@ describe("Response", () => { let response = Response.json("hello"); expect(response.type).toBe("basic"); expect(response.headers.get("content-type")).toBe( - "application/json;charset=utf-8" + "application/json;charset=utf-8", ); expect(response.status).toBe(200); }); @@ -366,7 +366,7 @@ describe("Response", () => { let response = Response.json("hello", 407); expect(response.type).toBe("basic"); expect(response.headers.get("content-type")).toBe( - "application/json;charset=utf-8" + "application/json;charset=utf-8", ); expect(response.status).toBe(407); }); @@ -485,7 +485,7 @@ describe("Request", () => { testBlobInterface( (data) => new Request("https://hello.com", { body: data }), - true + true, ); }); diff --git a/test/bun.js/ffi.test.fixture.callback.c b/test/bun.js/ffi.test.fixture.callback.c index 9c3c088ce..ec83dee80 100644 --- a/test/bun.js/ffi.test.fixture.callback.c +++ b/test/bun.js/ffi.test.fixture.callback.c @@ -285,9 +285,6 @@ ZIG_REPR_TYPE JSFunctionCall(void* jsGlobalObject, void* callFrame); bool my_callback_function(void* arg0); bool my_callback_function(void* arg0) { -#ifdef INJECT_BEFORE -INJECT_BEFORE; -#endif ZIG_REPR_TYPE arguments[1]; arguments[0] = PTR_TO_JSVALUE(arg0).asZigRepr; return (bool)JSVALUE_TO_BOOL(_FFI_Callback_call((void*)0x0UL, 1, arguments)); diff --git a/test/bun.js/ffi.test.js b/test/bun.js/ffi.test.js index 65b29b788..e3e858b1f 100644 --- a/test/bun.js/ffi.test.js +++ b/test/bun.js/ffi.test.js @@ -29,8 +29,8 @@ it("ffi print", async () => { returns: "bool", args: ["ptr"], }, - true - ) + true, + ), ); await Bun.write( import.meta.dir + "/ffi.test.fixture.receiver.c", @@ -41,8 +41,8 @@ it("ffi print", async () => { args: ["float"], }, }, - false - )[0] + false, + )[0], ); expect( viewSource( @@ -50,8 +50,8 @@ it("ffi print", async () => { returns: "int8_t", args: [], }, - true - ).length > 0 + true, + ).length > 0, ).toBe(true); expect( viewSource( @@ -61,8 +61,8 @@ it("ffi print", async () => { args: [], }, }, - false - ).length > 0 + false, + ).length > 0, ).toBe(true); }); @@ -423,17 +423,17 @@ function ffiRunner(fast) { var bigIntArray = new BigInt64Array(bigArray.buffer); expect(identity_uint64_t(bigArray[0])).toBe(bigArray[0]); expect(identity_uint64_t(bigArray[0] - BigInt(1))).toBe( - bigArray[0] - BigInt(1) + bigArray[0] - BigInt(1), ); if (fast) { expect(add_uint64_t(BigInt(-1) * bigArray[0], bigArray[0])).toBe(0); expect( - add_uint64_t(BigInt(-1) * bigArray[0] + BigInt(10), bigArray[0]) + add_uint64_t(BigInt(-1) * bigArray[0] + BigInt(10), bigArray[0]), ).toBe(10); } else { expect(add_uint64_t(BigInt(-1) * bigArray[0], bigArray[0])).toBe(0n); expect( - add_uint64_t(BigInt(-1) * bigArray[0] + BigInt(10), bigArray[0]) + add_uint64_t(BigInt(-1) * bigArray[0] + BigInt(10), bigArray[0]), ).toBe(10n); } if (fast) { @@ -450,7 +450,7 @@ function ffiRunner(fast) { expect(identity_int64_t(bigIntArray[0])).toBe(bigIntArray[0]); expect(identity_int64_t(bigIntArray[0] - BigInt(1))).toBe( - bigIntArray[0] - BigInt(1) + bigIntArray[0] - BigInt(1), ); } Bun.gc(true); @@ -475,7 +475,7 @@ function ffiRunner(fast) { const buffer = toBuffer(cptr, 0, 4); expect(buffer.readInt32(0)).toBe(42); expect(new DataView(toArrayBuffer(cptr, 0, 4), 0, 4).getInt32(0, true)).toBe( - 42 + 42, ); expect(ptr(buffer)).toBe(cptr); expect(new CString(cptr, 0, 1).toString()).toBe("*"); @@ -515,7 +515,7 @@ function ffiRunner(fast) { { returns: returnName, args: [returnName], - } + }, ).ptr, returns: returnName, args: [returnName], @@ -531,7 +531,7 @@ function ffiRunner(fast) { { returns: "bool", args: ["bool"], - } + }, ); expect(toClose.ptr > 0).toBe(true); toClose.close(); @@ -559,7 +559,7 @@ function ffiRunner(fast) { { args: [name], threadsafe: true, - } + }, ).ptr, returns: "void", args: [name], @@ -603,10 +603,10 @@ it("read", () => { for (let i = 0; i < buffer.length; i++) { buffer[i] = BigInt(i); expect(read.intptr(addr, i * 8)).toBe( - Number(dataView.getBigInt64(i * 8, true)) + Number(dataView.getBigInt64(i * 8, true)), ); expect(read.ptr(addr, i * 8)).toBe( - Number(dataView.getBigUint64(i * 8, true)) + Number(dataView.getBigUint64(i * 8, true)), ); expect(read.f64(addr, i + 8)).toBe(dataView.getFloat64(i + 8, true)); expect(read.i64(addr, i * 8)).toBe(dataView.getBigInt64(i * 8, true)); diff --git a/test/bun.js/fileUrl.test.js b/test/bun.js/fileUrl.test.js index 4799f4228..7efa8f235 100644 --- a/test/bun.js/fileUrl.test.js +++ b/test/bun.js/fileUrl.test.js @@ -3,7 +3,7 @@ import { pathToFileURL, fileURLToPath } from "bun"; describe("pathToFileURL", () => { it("should convert a path to a file url", () => { expect(pathToFileURL("/path/to/file.js").href).toBe( - "file:///path/to/file.js" + "file:///path/to/file.js", ); }); }); @@ -14,7 +14,7 @@ describe("fileURLToPath", () => { }); it("should convert a URL to a path", () => { expect(fileURLToPath(new URL("file:///path/to/file.js"))).toBe( - "/path/to/file.js" + "/path/to/file.js", ); }); }); diff --git a/test/bun.js/filesink.test.ts b/test/bun.js/filesink.test.ts index 28d51a173..b3b3a7e74 100644 --- a/test/bun.js/filesink.test.ts +++ b/test/bun.js/filesink.test.ts @@ -11,14 +11,14 @@ describe("FileSink", () => { [ ["abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"], new TextEncoder().encode( - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", ), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", ], [ ["😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌"], new TextEncoder().encode( - "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ), "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ], @@ -29,7 +29,7 @@ describe("FileSink", () => { ], new TextEncoder().encode( "abcdefghijklmnopqrstuvwxyz" + - "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ), "abcdefghijklmnopqrstuvwxyz" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", @@ -43,7 +43,7 @@ describe("FileSink", () => { ], new TextEncoder().encode( "abcdefghijklmnopqrstuvwxyz" + - "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ), "(rope) " + "abcdefghijklmnopqrstuvwxyz" + @@ -58,13 +58,13 @@ describe("FileSink", () => { ], new TextEncoder().encode( "abcdefghijklmnopqrstuvwxyz" + - "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ), "(array) " + "abcdefghijklmnopqrstuvwxyz" + "😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌", ], - ]; + ] as const; for (const [input, expected, label] of fixtures) { it(`${JSON.stringify(label)}`, async () => { diff --git a/test/bun.js/fs-stream.js b/test/bun.js/fs-stream.js index 4b71c95b7..1ef3ee71c 100644 --- a/test/bun.js/fs-stream.js +++ b/test/bun.js/fs-stream.js @@ -10,7 +10,7 @@ await new Promise((resolve, reject) => { const real = readFileSync("/tmp/fs-stream.js", "utf8"); if (copied !== real) { reject( - new Error("fs-stream.js is not the same as fs-stream.copy.js") + new Error("fs-stream.js is not the same as fs-stream.copy.js"), ); return; } diff --git a/test/bun.js/fs.test.js b/test/bun.js/fs.test.js index 3976ba372..5c80505ef 100644 --- a/test/bun.js/fs.test.js +++ b/test/bun.js/fs.test.js @@ -1,5 +1,5 @@ import { describe, expect, it } from "bun:test"; -import { gc, gcTick } from "gc"; +import { gc, gcTick } from "./gc"; import { closeSync, existsSync, @@ -31,14 +31,14 @@ describe("copyFileSync", () => { const tempdir = `/tmp/fs.test.js/${Date.now()}/1234/hi`; expect(existsSync(tempdir)).toBe(false); expect(tempdir.includes(mkdirSync(tempdir, { recursive: true }))).toBe( - true + true, ); // that don't exist copyFileSync(import.meta.path, tempdir + "/copyFileSync.js"); expect(existsSync(tempdir + "/copyFileSync.js")).toBe(true); expect(readFileSync(tempdir + "/copyFileSync.js", "utf-8")).toBe( - readFileSync(import.meta.path, "utf-8") + readFileSync(import.meta.path, "utf-8"), ); // that do exist @@ -53,7 +53,7 @@ describe("copyFileSync", () => { const tempdir = `/tmp/fs.test.js/${Date.now()}-1/1234/hi`; expect(existsSync(tempdir)).toBe(false); expect(tempdir.includes(mkdirSync(tempdir, { recursive: true }))).toBe( - true + true, ); var buffer = new Int32Array(128 * 1024); for (let i = 0; i < buffer.length; i++) { @@ -67,20 +67,20 @@ describe("copyFileSync", () => { expect(existsSync(tempdir + "/copyFileSync.src.blob")).toBe(true); copyFileSync( tempdir + "/copyFileSync.src.blob", - tempdir + "/copyFileSync.dest.blob" + tempdir + "/copyFileSync.dest.blob", ); expect(Bun.hash(readFileSync(tempdir + "/copyFileSync.dest.blob"))).toBe( - hash + hash, ); buffer[0] = 255; writeFileSync(tempdir + "/copyFileSync.src.blob", buffer.buffer); copyFileSync( tempdir + "/copyFileSync.src.blob", - tempdir + "/copyFileSync.dest.blob" + tempdir + "/copyFileSync.dest.blob", ); expect(Bun.hash(readFileSync(tempdir + "/copyFileSync.dest.blob"))).toBe( - Bun.hash(buffer.buffer) + Bun.hash(buffer.buffer), ); }); }); @@ -90,7 +90,7 @@ describe("mkdirSync", () => { const tempdir = `/tmp/fs.test.js/${Date.now()}/1234/hi`; expect(existsSync(tempdir)).toBe(false); expect(tempdir.includes(mkdirSync(tempdir, { recursive: true }))).toBe( - true + true, ); expect(existsSync(tempdir)).toBe(true); }); @@ -134,7 +134,7 @@ it("readdirSync works on empty directories", () => { it("readdirSync works on directories with under 32 files", () => { const path = `/tmp/fs-test-one-dir-${(Math.random() * 100000 + 100).toString( - 32 + 32, )}`; mkdirSync(path, { recursive: true }); writeFileSync(`${path}/a`, "a"); @@ -172,7 +172,7 @@ it("readdirSync throws when given a file path with trailing slash", () => { describe("readSync", () => { const firstFourBytes = new Uint32Array( - new TextEncoder().encode("File").buffer + new TextEncoder().encode("File").buffer, )[0]; it("works with a position set to 0", () => { const fd = openSync(import.meta.dir + "/readFileSync.txt", "r"); @@ -234,7 +234,7 @@ describe("readFileSync", () => { gc(); const text = readFileSync( new URL("file://" + import.meta.dir + "/readFileSync.txt"), - "utf8" + "utf8", ); gc(); expect(text).toBe("File read successfully"); @@ -338,7 +338,7 @@ describe("lstat", () => { const fileStats = lstatSync( new URL("./fs-stream.js", import.meta.url) .toString() - .slice("file://".length - 1) + .slice("file://".length - 1), ); expect(fileStats.isSymbolicLink()).toBe(false); expect(fileStats.isFile()).toBe(true); @@ -349,7 +349,7 @@ describe("lstat", () => { const fileStats = lstatSync( new URL("../../test", import.meta.url) .toString() - .slice("file://".length - 1) + .slice("file://".length - 1), ); expect(fileStats.isSymbolicLink()).toBe(false); expect(fileStats.isFile()).toBe(false); @@ -360,7 +360,7 @@ describe("lstat", () => { const linkStats = lstatSync( new URL("./fs-stream.link.js", import.meta.url) .toString() - .slice("file://".length - 1) + .slice("file://".length - 1), ); expect(linkStats.isSymbolicLink()).toBe(true); expect(linkStats.isFile()).toBe(false); @@ -373,7 +373,7 @@ describe("stat", () => { const fileStats = statSync( new URL("./fs-stream.js", import.meta.url) .toString() - .slice("file://".length - 1) + .slice("file://".length - 1), ); expect(fileStats.isSymbolicLink()).toBe(false); expect(fileStats.isFile()).toBe(true); @@ -384,7 +384,7 @@ describe("stat", () => { const fileStats = statSync( new URL("../../test", import.meta.url) .toString() - .slice("file://".length - 1) + .slice("file://".length - 1), ); expect(fileStats.isSymbolicLink()).toBe(false); expect(fileStats.isFile()).toBe(false); @@ -478,7 +478,7 @@ describe("createWriteStream", () => { stream.on("finish", () => { expect(readFileSync(path, "utf8")).toBe( - "Test file written successfully" + "Test file written successfully", ); resolve(true); }); diff --git a/test/bun.js/html-rewriter.test.js b/test/bun.js/html-rewriter.test.js index 29b765c2f..008ced791 100644 --- a/test/bun.js/html-rewriter.test.js +++ b/test/bun.js/html-rewriter.test.js @@ -74,11 +74,11 @@ describe("HTMLRewriter", () => { }, }); var input = new Response( - '<div first second="alrihgt" third="123" fourth=5 fifth=helloooo>hello</div>' + '<div first second="alrihgt" third="123" fourth=5 fifth=helloooo>hello</div>', ); var output = rewriter.transform(input); expect(await output.text()).toBe( - '<div first second="alrihgt" third="123" fourth=5 fifth=helloooo>hello</div>' + '<div first second="alrihgt" third="123" fourth=5 fifth=helloooo>hello</div>', ); expect(expected.length).toBe(0); }); @@ -104,7 +104,7 @@ describe("HTMLRewriter", () => { "<span>append</span>", "<span>append html</span>", "</p>", - ].join("") + ].join(""), ); // setInnerContent @@ -202,92 +202,92 @@ describe("HTMLRewriter", () => { await checkSelector( "p:nth-child(2)", "<div><p>1</p><p>2</p><p>3</p></div>", - "<div><p>1</p><p>new</p><p>3</p></div>" + "<div><p>1</p><p>new</p><p>3</p></div>", ); await checkSelector( "p:first-child", "<div><p>1</p><p>2</p><p>3</p></div>", - "<div><p>new</p><p>2</p><p>3</p></div>" + "<div><p>new</p><p>2</p><p>3</p></div>", ); await checkSelector( "p:nth-of-type(2)", "<div><p>1</p><h1>2</h1><p>3</p><h1>4</h1><p>5</p></div>", - "<div><p>1</p><h1>2</h1><p>new</p><h1>4</h1><p>5</p></div>" + "<div><p>1</p><h1>2</h1><p>new</p><h1>4</h1><p>5</p></div>", ); await checkSelector( "p:first-of-type", "<div><h1>1</h1><p>2</p><p>3</p></div>", - "<div><h1>1</h1><p>new</p><p>3</p></div>" + "<div><h1>1</h1><p>new</p><p>3</p></div>", ); await checkSelector( "p:not(:first-child)", "<div><p>1</p><p>2</p><p>3</p></div>", - "<div><p>1</p><p>new</p><p>new</p></div>" + "<div><p>1</p><p>new</p><p>new</p></div>", ); await checkSelector( "p.red", '<p class="red">1</p><p>2</p>', - '<p class="red">new</p><p>2</p>' + '<p class="red">new</p><p>2</p>', ); await checkSelector( "h1#header", '<h1 id="header">1</h1><h1>2</h1>', - '<h1 id="header">new</h1><h1>2</h1>' + '<h1 id="header">new</h1><h1>2</h1>', ); await checkSelector( "p[data-test]", "<p data-test>1</p><p>2</p>", - "<p data-test>new</p><p>2</p>" + "<p data-test>new</p><p>2</p>", ); await checkSelector( 'p[data-test="one"]', '<p data-test="one">1</p><p data-test="two">2</p>', - '<p data-test="one">new</p><p data-test="two">2</p>' + '<p data-test="one">new</p><p data-test="two">2</p>', ); await checkSelector( 'p[data-test="one" i]', '<p data-test="one">1</p><p data-test="OnE">2</p><p data-test="two">3</p>', - '<p data-test="one">new</p><p data-test="OnE">new</p><p data-test="two">3</p>' + '<p data-test="one">new</p><p data-test="OnE">new</p><p data-test="two">3</p>', ); await checkSelector( 'p[data-test="one" s]', '<p data-test="one">1</p><p data-test="OnE">2</p><p data-test="two">3</p>', - '<p data-test="one">new</p><p data-test="OnE">2</p><p data-test="two">3</p>' + '<p data-test="one">new</p><p data-test="OnE">2</p><p data-test="two">3</p>', ); await checkSelector( 'p[data-test~="two"]', '<p data-test="one two three">1</p><p data-test="one two">2</p><p data-test="one">3</p>', - '<p data-test="one two three">new</p><p data-test="one two">new</p><p data-test="one">3</p>' + '<p data-test="one two three">new</p><p data-test="one two">new</p><p data-test="one">3</p>', ); await checkSelector( 'p[data-test^="a"]', '<p data-test="a1">1</p><p data-test="a2">2</p><p data-test="b1">3</p>', - '<p data-test="a1">new</p><p data-test="a2">new</p><p data-test="b1">3</p>' + '<p data-test="a1">new</p><p data-test="a2">new</p><p data-test="b1">3</p>', ); await checkSelector( 'p[data-test$="1"]', '<p data-test="a1">1</p><p data-test="a2">2</p><p data-test="b1">3</p>', - '<p data-test="a1">new</p><p data-test="a2">2</p><p data-test="b1">new</p>' + '<p data-test="a1">new</p><p data-test="a2">2</p><p data-test="b1">new</p>', ); await checkSelector( 'p[data-test*="b"]', '<p data-test="abc">1</p><p data-test="ab">2</p><p data-test="a">3</p>', - '<p data-test="abc">new</p><p data-test="ab">new</p><p data-test="a">3</p>' + '<p data-test="abc">new</p><p data-test="ab">new</p><p data-test="a">3</p>', ); await checkSelector( 'p[data-test|="a"]', '<p data-test="a">1</p><p data-test="a-1">2</p><p data-test="a2">3</p>', - '<p data-test="a">new</p><p data-test="a-1">new</p><p data-test="a2">3</p>' + '<p data-test="a">new</p><p data-test="a-1">new</p><p data-test="a2">3</p>', ); await checkSelector( "div span", "<div><h1><span>1</span></h1><span>2</span><b>3</b></div>", - "<div><h1><span>new</span></h1><span>new</span><b>3</b></div>" + "<div><h1><span>new</span></h1><span>new</span><b>3</b></div>", ); await checkSelector( "div > span", "<div><h1><span>1</span></h1><span>2</span><b>3</b></div>", - "<div><h1><span>1</span></h1><span>new</span><b>3</b></div>" + "<div><h1><span>1</span></h1><span>new</span><b>3</b></div>", ); }); }); diff --git a/test/bun.js/import-meta.test.js b/test/bun.js/import-meta.test.js index a1ead978e..a6d663061 100644 --- a/test/bun.js/import-meta.test.js +++ b/test/bun.js/import-meta.test.js @@ -10,7 +10,7 @@ it("primordials are not here!", () => { it("import.meta.resolveSync", () => { expect( - import.meta.resolveSync("./" + import.meta.file, import.meta.path) + import.meta.resolveSync("./" + import.meta.file, import.meta.path), ).toBe(path); const require = Module.createRequire(import.meta.path); expect(require.resolve(import.meta.path)).toBe(path); @@ -18,7 +18,7 @@ it("import.meta.resolveSync", () => { // check it works with URL objects expect( - Module.createRequire(new URL(import.meta.url)).resolve(import.meta.path) + Module.createRequire(new URL(import.meta.url)).resolve(import.meta.path), ).toBe(import.meta.path); }); diff --git a/test/bun.js/inspect.test.js b/test/bun.js/inspect.test.js index 65ba67edf..b49265f53 100644 --- a/test/bun.js/inspect.test.js +++ b/test/bun.js/inspect.test.js @@ -34,7 +34,7 @@ it("utf16 property name", () => { var { Database } = require("bun:sqlite"); const db = Database.open(":memory:"); expect(Bun.inspect(db.prepare("select '😀' as 笑").all())).toBe( - '[ { "笑": "😀" } ]' + '[ { "笑": "😀" } ]', ); }); @@ -53,7 +53,7 @@ it("Request object", () => { Request (0 KB) { method: "GET", url: "https://example.com" -}`.trim() +}`.trim(), ); }); @@ -62,7 +62,7 @@ it("MessageEvent", () => { `MessageEvent { type: "message", data: 123 -}` +}`, ); }); @@ -83,13 +83,13 @@ it("TypedArray prints", () => { const input = Bun.inspect(buffer); expect(input).toBe( - `${TypedArray.name}(${buffer.length}) [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]` + `${TypedArray.name}(${buffer.length}) [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]`, ); for (let i = 1; i < buffer.length + 1; i++) { expect(Bun.inspect(buffer.subarray(i))).toBe( `${TypedArray.name}(${buffer.length - i}) [ ` + [...buffer.subarray(i)].join(", ") + - " ]" + " ]", ); } } @@ -101,13 +101,13 @@ it("BigIntArray", () => { const input = Bun.inspect(buffer); expect(input).toBe( - `${TypedArray.name}(${buffer.length}) [ 1n, 2n, 3n, 4n, 5n, 6n, 7n, 8n, 9n, 10n ]` + `${TypedArray.name}(${buffer.length}) [ 1n, 2n, 3n, 4n, 5n, 6n, 7n, 8n, 9n, 10n ]`, ); for (let i = 1; i < buffer.length + 1; i++) { expect(Bun.inspect(buffer.subarray(i))).toBe( `${TypedArray.name}(${buffer.length - i}) [ ` + [...buffer.subarray(i)].map((a) => a.toString(10) + "n").join(", ") + - " ]" + " ]", ); } } @@ -120,14 +120,14 @@ it("FloatArray", () => { expect(input).toBe( `${TypedArray.name}(${buffer.length}) [ ${[Math.fround(42.68)].join( - ", " - )} ]` + ", ", + )} ]`, ); for (let i = 1; i < buffer.length + 1; i++) { expect(Bun.inspect(buffer.subarray(i))).toBe( `${TypedArray.name}(${buffer.length - i}) [ ` + [...buffer.subarray(i)].join(", ") + - " ]" + " ]", ); } } @@ -138,7 +138,7 @@ it("jsx with two elements", () => { <div hello="quoted"> <input type="text" value={"123"} /> string inside child - </div> + </div>, ); const output = `<div hello="quoted"> @@ -169,7 +169,7 @@ it("jsx with fragment", () => { it("inspect", () => { expect(Bun.inspect(new TypeError("what")).includes("TypeError: what")).toBe( - true + true, ); expect("hi").toBe("hi"); expect(Bun.inspect(1)).toBe("1"); @@ -182,10 +182,10 @@ it("inspect", () => { expect(Bun.inspect({ hello: 1 })).toBe("{ hello: 1 }"); expect(Bun.inspect({ hello: 1, there: 2 })).toBe("{ hello: 1, there: 2 }"); expect(Bun.inspect({ hello: "1", there: 2 })).toBe( - '{ hello: "1", there: 2 }' + '{ hello: "1", there: 2 }', ); expect(Bun.inspect({ 'hello-"there': "1", there: 2 })).toBe( - '{ "hello-\\"there": "1", there: 2 }' + '{ "hello-\\"there": "1", there: 2 }', ); var str = "123"; while (str.length < 4096) { @@ -204,29 +204,29 @@ it("inspect", () => { expect(Bun.inspect(new Set())).toBe("Set {}"); expect(Bun.inspect(new Map())).toBe("Map {}"); expect(Bun.inspect(new Map([["foo", "bar"]]))).toBe( - 'Map(1) {\n "foo": "bar",\n}' + 'Map(1) {\n "foo": "bar",\n}', ); expect(Bun.inspect(new Set(["bar"]))).toBe('Set(1) {\n "bar",\n}'); expect(Bun.inspect(<div>foo</div>)).toBe("<div>foo</div>"); expect(Bun.inspect(<div hello>foo</div>)).toBe("<div hello=true>foo</div>"); expect(Bun.inspect(<div hello={1}>foo</div>)).toBe("<div hello=1>foo</div>"); expect(Bun.inspect(<div hello={123}>hi</div>)).toBe( - "<div hello=123>hi</div>" + "<div hello=123>hi</div>", ); expect(Bun.inspect(<div hello="quoted">quoted</div>)).toBe( - '<div hello="quoted">quoted</div>' + '<div hello="quoted">quoted</div>', ); expect( Bun.inspect( <div hello="quoted"> <input type="text" value={"123"} /> - </div> - ) + </div>, + ), ).toBe( ` <div hello="quoted"> <input type="text" value="123" /> -</div>`.trim() +</div>`.trim(), ); expect(Bun.inspect(BigInt(32))).toBe("32n"); }); diff --git a/test/bun.js/log-test.test.ts b/test/bun.js/log-test.test.ts index bdb6cbe42..272dc7ef2 100644 --- a/test/bun.js/log-test.test.ts +++ b/test/bun.js/log-test.test.ts @@ -14,7 +14,7 @@ it("should not log .env when quiet", async () => { cwd: "/tmp/log-test-silent", }); - expect(stderr.toString()).toBe(""); + expect(stderr!.toString()).toBe(""); }); it("should log .env by default", async () => { @@ -29,7 +29,7 @@ it("should log .env by default", async () => { cwd: "/tmp/log-test-silent", }); - expect(stderr.toString().includes(".env")).toBe(true); + expect(stderr?.toString().includes(".env")).toBe(true); }); function writeDirectoryTree(base, paths) { diff --git a/test/bun.js/microtask.test.js b/test/bun.js/microtask.test.js index 18956b1e5..dba84f36c 100644 --- a/test/bun.js/microtask.test.js +++ b/test/bun.js/microtask.test.js @@ -60,7 +60,7 @@ it("queueMicrotask", async () => { if (!passed) throw new Error( - "queueMicrotask should throw a TypeError if the argument is not a function" + "queueMicrotask should throw a TypeError if the argument is not a function", ); } @@ -74,7 +74,7 @@ it("queueMicrotask", async () => { if (!passed) throw new Error( - "queueMicrotask should throw a TypeError if the argument is empty" + "queueMicrotask should throw a TypeError if the argument is empty", ); } }); diff --git a/test/bun.js/node-test-helpers.test.js b/test/bun.js/node-test-helpers.test.js index 7fb2de320..766dfc176 100644 --- a/test/bun.js/node-test-helpers.test.js +++ b/test/bun.js/node-test-helpers.test.js @@ -5,7 +5,7 @@ import { strictEqual, createCallCheckCtx, createDoneDotAll, -} from "node-test-helpers"; +} from "./node-test-helpers"; describe("OurAssert.throws()", () => { it("should pass when the function throws", () => { diff --git a/test/bun.js/oniguruma-regexp.test.ts b/test/bun.js/oniguruma-regexp.test.ts index 372e8eb99..9fe3d7be8 100644 --- a/test/bun.js/oniguruma-regexp.test.ts +++ b/test/bun.js/oniguruma-regexp.test.ts @@ -1,3 +1,4 @@ +// @ts-ignore import { OnigurumaRegExp } from "bun"; import { expect, it, test } from "bun:test"; import { gc as gcTrace } from "./gc"; @@ -7,8 +8,8 @@ it("repeated match and exec calls", () => { let r1 = new OnigurumaRegExp("//.+?/[^?]+", "sg"); let r2 = new RegExp("//.+?/[^?]+", "sg"); let s1 = "https://dylan-conway.com/profile"; - expect(s1.match(r1)[0] === s1.match(r2)[0]).toBe(true); - expect(r1.exec(s1)[0] === r2.exec(s1)[0]).toBe(true); + expect(s1.match(r1)![0] === s1.match(r2)![0]).toBe(true); + expect(r1.exec(s1)![0] === r2.exec(s1)![0]).toBe(true); } }); @@ -17,8 +18,8 @@ it("repeated match and exec calls no global flag", () => { let r1 = new OnigurumaRegExp("//.+?/[^?]+", "s"); let r2 = new RegExp("//.+?/[^?]+", "s"); let s1 = "https://dylan-conway.com/profile"; - expect(r1.exec(s1)[0] === r2.exec(s1)[0]).toBe(true); - expect(s1.match(r1)[0] === s1.match(r2)[0]).toBe(true); + expect(r1.exec(s1)![0] === r2.exec(s1)![0]).toBe(true); + expect(s1.match(r1)![0] === s1.match(r2)![0]).toBe(true); } }); @@ -27,53 +28,53 @@ const rb2 = new RegExp("//.+?/[^?]+", "s"); it("repeated match calls with global regex without global flag", () => { for (let i = 0; i < 20000; i++) { let s1 = "https://dylan-conway.com/profile"; - expect(rb1.exec(s1)[0] === rb2.exec(s1)[0]).toBe(true); - expect(s1.match(rb1)[0] === s1.match(rb2)[0]).toBe(true); + expect(rb1.exec(s1)![0] === rb2.exec(s1)![0]).toBe(true); + expect(s1.match(rb1)![0] === s1.match(rb2)![0]).toBe(true); } }); it("escaped characters in character classes", () => { expect( - new RegExp("[a-z]").exec("a")[0] === - new OnigurumaRegExp("[a-z]").exec("a")[0] + new RegExp("[a-z]").exec("a")![0] === + new OnigurumaRegExp("[a-z]").exec("a")![0], ).toBe(true); Bun.gc(true); expect( - new RegExp("[a-z]").exec("b")[0] === - new OnigurumaRegExp("[a-z]").exec("b")[0] + new RegExp("[a-z]").exec("b")![0] === + new OnigurumaRegExp("[a-z]").exec("b")![0], ).toBe(true); Bun.gc(true); - expect(new RegExp("[a-zA-Z0-9_]+").exec("B9")[0]).toBe( - new OnigurumaRegExp("[a-zA-Z0-9_]+").exec("B9")[0] + expect(new RegExp("[a-zA-Z0-9_]+").exec("B9")![0]).toBe( + new OnigurumaRegExp("[a-zA-Z0-9_]+").exec("B9")![0], ); Bun.gc(true); expect(new RegExp("[a-z]").exec("-")).toBe(null); Bun.gc(true); expect(new OnigurumaRegExp("[a-z]").exec("-")).toBe(null); Bun.gc(true); - expect(new RegExp("[a\\-z]").exec("-")[0]).toBe("-"); + expect(new RegExp("[a\\-z]").exec("-")![0]).toBe("-"); Bun.gc(true); - expect(new OnigurumaRegExp("[a\\-z]").exec("-")[0]).toBe("-"); + expect(new OnigurumaRegExp("[a\\-z]").exec("-")![0]).toBe("-"); Bun.gc(true); - expect(new RegExp("[a\\-z]").exec("a")[0]).toBe("a"); + expect(new RegExp("[a\\-z]").exec("a")![0]).toBe("a"); Bun.gc(true); - expect(new OnigurumaRegExp("[a\\-z]").exec("a")[0]).toBe("a"); + expect(new OnigurumaRegExp("[a\\-z]").exec("a")![0]).toBe("a"); Bun.gc(true); - expect(new RegExp("[a\\-z]").exec("z")[0]).toBe("z"); + expect(new RegExp("[a\\-z]").exec("z")![0]).toBe("z"); Bun.gc(true); - expect(new OnigurumaRegExp("[a\\-z]").exec("z")[0]).toBe("z"); + expect(new OnigurumaRegExp("[a\\-z]").exec("z")![0]).toBe("z"); Bun.gc(true); expect(new RegExp("[a\\-z]").exec("b")).toBe(null); Bun.gc(true); expect(new OnigurumaRegExp("[a\\-z]").exec("b")).toBe(null); Bun.gc(true); - expect(new RegExp("[^b-c]").exec("a")[0]).toBe( - new OnigurumaRegExp("[^b-c]").exec("a")[0] + expect(new RegExp("[^b-c]").exec("a")![0]).toBe( + new OnigurumaRegExp("[^b-c]").exec("a")![0], ); Bun.gc(true); @@ -81,16 +82,16 @@ it("escaped characters in character classes", () => { expect(new OnigurumaRegExp("[\\^b-c]").exec("a")).toBe(null); Bun.gc(true); - expect(new RegExp("[\\^b-c]").exec("^c")[0]).toBe("^"); - expect(new OnigurumaRegExp("[\\^b-c]").exec("^c")[0]).toBe("^"); + expect(new RegExp("[\\^b-c]").exec("^c")![0]).toBe("^"); + expect(new OnigurumaRegExp("[\\^b-c]").exec("^c")![0]).toBe("^"); Bun.gc(true); - expect(new RegExp("[a^b-c]").exec("a^")[0]).toBe("a"); - expect(new OnigurumaRegExp("[a^b-c]").exec("a^")[0]).toBe("a"); + expect(new RegExp("[a^b-c]").exec("a^")![0]).toBe("a"); + expect(new OnigurumaRegExp("[a^b-c]").exec("a^")![0]).toBe("a"); Bun.gc(true); - expect(new RegExp("[\\\\]").exec("\\")[0]).toBe("\\"); - expect(new OnigurumaRegExp("[\\\\]").exec("\\")[0]).toBe("\\"); + expect(new RegExp("[\\\\]").exec("\\")![0]).toBe("\\"); + expect(new OnigurumaRegExp("[\\\\]").exec("\\")![0]).toBe("\\"); Bun.gc(true); let p = "//.+?[^?]+"; @@ -98,15 +99,15 @@ it("escaped characters in character classes", () => { const b1 = new RegExp(p, "gs"); const b2 = new OnigurumaRegExp(p, "gs"); Bun.gc(true); - expect(s.match(b1)[0] === s.match(b2)[0]).toBe(true); + expect(s.match(b1)![0] === s.match(b2)![0]).toBe(true); Bun.gc(true); const b3 = new RegExp("[\\^]"); const b4 = new OnigurumaRegExp("[\\^]"); Bun.gc(true); expect( - "https://dylan-co^nway.com/profile".match(b3)[0] === - "https://dylan-co^nway.com/profile".match(b4)[0] + "https://dylan-co^nway.com/profile".match(b3)![0] === + "https://dylan-co^nway.com/profile".match(b4)![0], ).toBe(true); Bun.gc(true); @@ -114,132 +115,132 @@ it("escaped characters in character classes", () => { p = "\/\/.+?\/[^?]+"; s = "https://dylan-conway.com/profile"; Bun.gc(true); - expect(s.match(new OnigurumaRegExp(p, "gs"))[0]).toBe( - new RegExp(p, "gs").exec(s)[0] + expect(s.match(new OnigurumaRegExp(p, "gs"))![0]).toBe( + new RegExp(p, "gs").exec(s)![0], ); Bun.gc(true); // middle no escape p = "[.i^e]+"; s = "https://dylan-co^nway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); // middle with escape p = "[.i\\^e]+"; s = "https://dylan-co^nway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); // end with escape p = "[.ie\\^]+"; s = "https://dylan-co^nway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); // end no escape p = "[.ie^]+"; s = "https://dylan-co^nway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); // start no escape p = "[^.ie]+"; s = "https://dylan-co^nway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); // start with escape p = "[\\^.ie]+"; s = "https://dylan-co^nway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); // middle with escape p = "[.i\\-e]+"; s = "https://dylan-conway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); // end with escape p = "[.ie\\-]+"; s = "https://dylan-conway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); // end no escape p = "[.ie-]+"; s = "https://dylan-conway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); // start no escape p = "[-.ie]+"; s = "https://dylan-conway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); // start with escape p = "[\\-.ie]+"; s = "https://dylan-conway.com/profile"; - expect(new OnigurumaRegExp(p).exec(s)[0]).toBe(new RegExp(p).exec(s)[0]); + expect(new OnigurumaRegExp(p).exec(s)![0]).toBe(new RegExp(p).exec(s)![0]); - let r1 = new RegExp("^([[(]-?[\\d]+)?,?(-?[\\d]+[\\])])?$").exec("(1,1]"); + let r1 = new RegExp("^([[(]-?[\\d]+)?,?(-?[\\d]+[\\])])?$").exec("(1,1]")!; Bun.gc(true); let r2 = new OnigurumaRegExp("^([[(]-?[\\d]+)?,?(-?[\\d]+[\\])])?$").exec( - "(1,1]" + "(1,1]", ); Bun.gc(true); expect(r1[0]).toBe(r2[0]); Bun.gc(true); - let r3 = new RegExp("[\\d],[\\d]").exec("1,2"); + let r3 = new RegExp("[\\d],[\\d]").exec("1,2")!; let r4 = new OnigurumaRegExp("[\\d],[\\d]").exec("1,2"); expect(r3[0]).toBe(r4[0]); - let r5 = new RegExp("^[(],[)]?$").exec("(,"); + let r5 = new RegExp("^[(],[)]?$").exec("(,")!; let r6 = new OnigurumaRegExp("^[(],[)]?$").exec("(,"); expect(r5[0]).toBe(r6[0]); - let r9 = new RegExp("[([],[)\\]]").exec("[,]"); + let r9 = new RegExp("[([],[)\\]]").exec("[,]")!; let r10 = new OnigurumaRegExp("[([],[)\\]]").exec("[,]"); expect(r9[0]).toBe(r10[0]); - let r13 = new RegExp("\\[").exec("["); + let r13 = new RegExp("\\[").exec("[")!; let r14 = new OnigurumaRegExp("\\[").exec("["); expect(r13[0]).toBe(r14[0]); - let r15 = new RegExp("\\]").exec("]"); + let r15 = new RegExp("\\]").exec("]")!; let r16 = new OnigurumaRegExp("\\]").exec("]"); expect(r15[0]).toBe(r16[0]); - let r17 = new RegExp("]").exec("]"); + let r17 = new RegExp("]").exec("]")!; let r18 = new OnigurumaRegExp("]").exec("]"); expect(r17[0]).toBe(r18[0]); - let r21 = new RegExp("[\\]]").exec("]"); + let r21 = new RegExp("[\\]]").exec("]")!; let r22 = new OnigurumaRegExp("[\\]]").exec("]"); expect(r21[0]).toBe(r22[0]); - let r23 = new RegExp("[\\[]").exec("["); + let r23 = new RegExp("[\\[]").exec("[")!; let r24 = new OnigurumaRegExp("[\\[]").exec("["); expect(r23[0]).toBe(r24[0]); - let r25 = new RegExp("[[][[]").exec("[["); + let r25 = new RegExp("[[][[]").exec("[[")!; let r26 = new OnigurumaRegExp("[[][[]").exec("[["); expect(r25[0]).toBe(r26[0]); - let r27 = new RegExp("[[\\]][[\\]]").exec("[]"); + let r27 = new RegExp("[[\\]][[\\]]").exec("[]")!; let r28 = new OnigurumaRegExp("[[\\]][[\\]]").exec("[]"); expect(r27[0]).toBe(r28[0]); - let r29 = new RegExp("[[\\]][[\\]]").exec("]["); + let r29 = new RegExp("[[\\]][[\\]]").exec("][")!; let r30 = new OnigurumaRegExp("[[\\]][[\\]]").exec("]["); expect(r29[0]).toBe(r30[0]); - let r31 = new RegExp("[[\\]][[\\]]").exec("]]"); + let r31 = new RegExp("[[\\]][[\\]]").exec("]]")!; let r32 = new OnigurumaRegExp("[[\\]][[\\]]").exec("]]"); expect(r31[0]).toBe(r32[0]); - let r33 = new RegExp("[\\]][\\]]").exec("]]"); + let r33 = new RegExp("[\\]][\\]]").exec("]]")!; let r34 = new OnigurumaRegExp("[\\]][\\]]").exec("]]"); expect(r33[0]).toBe(r34[0]); - let r35 = new RegExp("[a-z&&[^aeiou]").exec("a"); + let r35 = new RegExp("[a-z&&[^aeiou]").exec("a")!; let r36 = new OnigurumaRegExp("[a-z&&[^aeiou]").exec("a"); expect(r35[0]).toBe(r36[0]); - let r37 = new RegExp("[a-z&&[^aeiou]]").exec("a]"); + let r37 = new RegExp("[a-z&&[^aeiou]]").exec("a]")!; let r38 = new OnigurumaRegExp("[a-z&&[^aeiou]]").exec("a]"); expect(r37[0]).toBe(r38[0]); }); @@ -251,7 +252,7 @@ it("OnigurumaRegExp.prototype.exec()", () => { let a2 = new RegExp("\x3e", "gd"); let a2_1 = a2.exec("table fo\x3eotball, fo\x3eosball"); - a2_1 = a2.exec("table fo\x3eotball, fo\x3eosball"); + a2_1 = a2.exec("table fo\x3eotball, fo\x3eosball")!; expect(a1_1[0]).toBe(a2_1[0]); expect(a1_1[1]).toBe(a2_1[1]); @@ -259,7 +260,9 @@ it("OnigurumaRegExp.prototype.exec()", () => { expect(a1_1.input).toBe(a2_1.input); expect(a1.lastIndex).toBe(a2.lastIndex); expect(a1_1.groups).toBe(a2_1.groups); + // @ts-ignore remove when `indices` is added to lib/dom expect(a1_1.indices[0][0]).toBe(a2_1.indices[0][0]); + // @ts-ignore expect(a1_1.indices[0][1]).toBe(a2_1.indices[0][1]); }); @@ -269,8 +272,8 @@ test("OnigurumaRegExp.prototype.exec() 2", () => { a1_1 = a1.exec("table fo\x3e\x5eotball, fo\x3e\x5eosball"); let a2 = new RegExp("\x3e\\x5e", "gd"); - let a2_1 = a2.exec("table fo\x3e\x5eotball, fo\x3e\x5eosball"); - a2_1 = a2.exec("table fo\x3e\x5eotball, fo\x3e\x5eosball"); + let a2_1 = a2.exec("table fo\x3e\x5eotball, fo\x3e\x5eosball")!; + a2_1 = a2.exec("table fo\x3e\x5eotball, fo\x3e\x5eosball")!; expect(a1_1[0]).toBe(a2_1[0]); expect(a1_1[1]).toBe(a2_1[1]); @@ -278,7 +281,9 @@ test("OnigurumaRegExp.prototype.exec() 2", () => { expect(a1_1.input).toBe(a2_1.input); expect(a1.lastIndex).toBe(a2.lastIndex); expect(a1_1.groups).toBe(a2_1.groups); + // @ts-ignore expect(a1_1.indices[0][0]).toBe(a2_1.indices[0][0]); + // @ts-ignore expect(a1_1.indices[0][1]).toBe(a2_1.indices[0][1]); }); @@ -291,7 +296,7 @@ test("OnigurumaRegExp.prototype.exec() 3", () => { let a1_1 = a1.exec("table fo\\x3\x5eotball, fo\\x3\x5eosball"); let a2 = new RegExp("\\x3\\x5e", "gd"); - let a2_1 = a2.exec("table fo\\x3\x5eotball, fo\\x3\x5eosball"); + let a2_1 = a2.exec("table fo\\x3\x5eotball, fo\\x3\x5eosball")!; expect(a1_1[0]).toBe(a2_1[0]); expect(a1_1[1]).toBe(a2_1[1]); @@ -299,7 +304,9 @@ test("OnigurumaRegExp.prototype.exec() 3", () => { expect(a1_1.input).toBe(a2_1.input); expect(a1.lastIndex).toBe(a2.lastIndex); expect(a1_1.groups).toBe(a2_1.groups); + // @ts-ignore expect(a1_1.indices[0][0]).toBe(a2_1.indices[0][0]); + // @ts-ignore expect(a1_1.indices[0][1]).toBe(a2_1.indices[0][1]); }); @@ -320,7 +327,7 @@ test("OnigurumaRegExp.prototype.exec() 4", () => { expect(new RegExpConstructor("\\x3\\x5\\j").source).toBe("\\x3\\x5\\j"); expect(new RegExpConstructor("\\x3\\x7\\xa").source).toBe("\\x3\\x7\\xa"); expect(new RegExpConstructor("\\j323\\x7\\xa").source).toBe( - "\\j323\\x7\\xa" + "\\j323\\x7\\xa", ); expect(new RegExpConstructor("\\x56").test("V")).toBe(true); } @@ -329,19 +336,19 @@ test("OnigurumaRegExp.prototype.exec() 4", () => { test("OnigurumaRegExp.prototype.test()", () => { expect(new RegExp("\\\\(?![*+?^${}(|)[\\]])", "g").test("\\")).toBe(true); expect(new OnigurumaRegExp("\\\\(?![*+?^${}(|)[\\]])", "g").test("\\")).toBe( - true + true, ); expect(new RegExp("\\x56").test("V")).toBe(true); expect(new OnigurumaRegExp("\\x56").test("V")).toBe(true); expect( - new RegExp("//").compile("\\\\(?![*+?^${}(|)[\\]])", "g").test("\\") + new RegExp("//").compile("\\\\(?![*+?^${}(|)[\\]])", "g").test("\\"), ).toBe(true); let r = new OnigurumaRegExp("//"); expect(r.compile("\\\\(?![*+?^${}(|)[\\]])", "g").test("\\")).toBe(true); expect( - new OnigurumaRegExp("").compile("\\\\(?![*+?^${}(|)[\\]])", "g").test("\\") + new OnigurumaRegExp("").compile("\\\\(?![*+?^${}(|)[\\]])", "g").test("\\"), ).toBe(true); }); @@ -358,11 +365,12 @@ test("OnigurumaRegExp.prototype.source", () => { expect(new OnigurumaRegExp("/").source).toBe("\\/"); expect(new RegExp("/").source).toBe("\\/"); + // @ts-ignore TS doesn't allow empty constructor expect(new OnigurumaRegExp().source).toBe(new RegExp().source); expect(new OnigurumaRegExp("").source).toBe(new RegExp("").source); expect(new OnigurumaRegExp("a").source).toBe(new RegExp("a").source); expect(new OnigurumaRegExp("a", "g").source).toBe( - new RegExp("a", "g").source + new RegExp("a", "g").source, ); expect(new OnigurumaRegExp("/").source).toBe(new RegExp("/").source); expect(new OnigurumaRegExp("\n").source).toBe(new RegExp("\n").source); @@ -370,25 +378,26 @@ test("OnigurumaRegExp.prototype.source", () => { }); test("OnigurumaRegExp.prototype.toString()", () => { + // @ts-ignore expect(new OnigurumaRegExp().toString()).toBe(new RegExp().toString()); expect(new OnigurumaRegExp("").toString()).toBe(new RegExp("").toString()); expect(new OnigurumaRegExp("a").toString()).toBe(new RegExp("a").toString()); expect(new OnigurumaRegExp("a", "g").toString()).toBe( - new RegExp("a", "g").toString() + new RegExp("a", "g").toString(), ); expect(new OnigurumaRegExp("/").toString()).toBe(new RegExp("/").toString()); expect(new OnigurumaRegExp("\n").toString()).toBe( - new RegExp("\n").toString() + new RegExp("\n").toString(), ); expect(new OnigurumaRegExp("\r").toString()).toBe( - new RegExp("\r").toString() + new RegExp("\r").toString(), ); expect( new OnigurumaRegExp( - "jf/.a.,voejpjoajglz;/qwjopeiv\\//\\/jpoqaj/Zdkj" - ).toString() + "jf/.a.,voejpjoajglz;/qwjopeiv\\//\\/jpoqaj/Zdkj", + ).toString(), ).toBe( - new RegExp("jf/.a.,voejpjoajglz;/qwjopeiv\\//\\/jpoqaj/Zdkj").toString() + new RegExp("jf/.a.,voejpjoajglz;/qwjopeiv\\//\\/jpoqaj/Zdkj").toString(), ); }); @@ -429,10 +438,10 @@ test("OnigurumaRegExp flags", () => { // case insensitive option for (const RegExpConstructor of [OnigurumaRegExp, RegExp]) { expect(new RegExpConstructor("Is ThIs SqL?").test("IS THIS SQL?")).toBe( - false + false, ); expect( - new RegExpConstructor("Is ThIs SqL?", "i").test("IS THIS SQL?") + new RegExpConstructor("Is ThIs SqL?", "i").test("IS THIS SQL?"), ).toBe(true); } @@ -505,56 +514,56 @@ test("OnigurumaRegExp errors", () => { let b = new OnigurumaRegExp("l", "m"); try { r.compile(b, "g"); - } catch (e) { + } catch (e: any) { expect(e.message).toBe( - "Cannot supply flags when constructing one RegExp from another." + "Cannot supply flags when constructing one RegExp from another.", ); } try { r.compile("ll", "a"); - } catch (e) { + } catch (e: any) { expect(e.message).toBe("Invalid flags supplied to RegExp constructor."); } try { new OnigurumaRegExp("c", "a"); - } catch (e) { + } catch (e: any) { expect(e.message).toBe("Invalid flags supplied to RegExp constructor."); } const invalidRegExpError = "Invalid regular expression: "; try { new OnigurumaRegExp("?", "g"); - } catch (e) { + } catch (e: any) { expect(e.message.substring(0, invalidRegExpError.length)).toBe( - invalidRegExpError + invalidRegExpError, ); } try { new OnigurumaRegExp("?"); - } catch (e) { + } catch (e: any) { expect(e.message.substring(0, invalidRegExpError.length)).toBe( - invalidRegExpError + invalidRegExpError, ); } try { r.compile("?", "g"); - } catch (e) { + } catch (e: any) { expect(e.message.substring(0, invalidRegExpError.length)).toBe( - invalidRegExpError + invalidRegExpError, ); } try { r.compile("?"); - } catch (e) { + } catch (e: any) { expect(e.message.substring(0, invalidRegExpError.length)).toBe( - invalidRegExpError + invalidRegExpError, ); } try { new OnigurumaRegExp("\\"); - } catch (e) { + } catch (e: any) { expect(e.message.substring(0, invalidRegExpError.length)).toBe( - invalidRegExpError + invalidRegExpError, ); } }); @@ -607,7 +616,9 @@ test("OnigurumaRegExp random", () => { expect(new OnigurumaRegExp("a", "i").sticky).toBe(false); expect(new OnigurumaRegExp("a", "u").unicode).toBe(true); expect(new OnigurumaRegExp("a", "d").unicode).toBe(false); + // @ts-ignore expect(new RegExp("a", "d").hasIndices).toBe(true); + // @ts-ignore expect(new RegExp("a", "i").hasIndices).toBe(false); expect(new RegExp("a", "s").dotAll).toBe(true); expect(new RegExp("a", "i").dotAll).toBe(false); @@ -634,7 +645,7 @@ it("String.prototype.replace", () => { expect(offset).toBe(0); expect(string).toBe("a"); return "b"; - }) + }), ).toBe("b"); } @@ -652,13 +663,13 @@ it("Strings.prototype.match", () => { let str = "The rain in SPAIN stays mainly in the plain"; for (let RegExpConstructor of [OnigurumaRegExp, RegExp]) { let r1 = new RegExpConstructor("ain", "g"); - let m1 = str.match(r1); + let m1 = str.match(r1)!; expect(m1[0]).toBe("ain"); expect(m1[1]).toBe("ain"); expect(m1[2]).toBe("ain"); r1.compile("ain", "ig"); - m1 = str.match(r1); + m1 = str.match(r1)!; expect(m1[0]).toBe("ain"); expect(m1[1]).toBe("AIN"); expect(m1[2]).toBe("ain"); @@ -709,37 +720,37 @@ it("String.prototype.split", () => { it("escapes characters, unicode, and hex", () => { for (const RegExpConstructor of [OnigurumaRegExp, RegExp]) { expect(new RegExpConstructor("[\\x00-\\x1F]").toString()).toBe( - "/[\\x00-\\x1F]/" + "/[\\x00-\\x1F]/", ); expect(new RegExpConstructor("[\\u0000-\\u001F]").toString()).toBe( - "/[\\u0000-\\u001F]/" + "/[\\u0000-\\u001F]/", ); var s = /\\x{7HHHHHHH}(?=\\u{1233})/; let a = new RegExpConstructor("\u{0001F46E}"); - expect(a.exec("👮")[0]).toBe("👮"); + expect(a.exec("👮")![0]).toBe("👮"); } let y = new OnigurumaRegExp("[👮\\x7F](?<=👮)"); - expect(y.exec("👮\\x{7F}")[0]).toBe("👮"); + expect(y.exec("👮\\x{7F}")![0]).toBe("👮"); let by = new OnigurumaRegExp("[👮\\cx7f](?<=👮)"); - expect(y.exec("👮\\x{7F}")[0]).toBe("👮"); + expect(y.exec("👮\\x{7F}")![0]).toBe("👮"); let bz = new OnigurumaRegExp("[👮\\x7](?<=👮)"); let d = new OnigurumaRegExp("[\u{0001F46E}\x7F](?<=\u{0001F46E})"); - expect(d.exec("👮\x7F")[0]).toBe("👮"); + expect(d.exec("👮\x7F")![0]).toBe("👮"); let y_2 = /[[👮\x7F](?<=👮)]/; - expect(y_2.exec("👮]")[0]).toBe("👮]"); + expect(y_2.exec("👮]")![0]).toBe("👮]"); let a1 = new OnigurumaRegExp("(f\xf3oo)", "gd"); let a1_1 = a1.exec("table f\xf3ootball, f\xf3oosball"); a1_1 = a1.exec("table f\xf3ootball, f\xf3oosball"); let a2 = new RegExp("(f\xf3oo)", "dg"); - let a2_1 = a2.exec("table f\xf3ootball, f\xf3oosball"); - a2_1 = a2.exec("table f\xf3ootball, f\xf3oosball"); + let a2_1 = a2.exec("table f\xf3ootball, f\xf3oosball")!; + a2_1 = a2.exec("table f\xf3ootball, f\xf3oosball")!; expect(a1_1[0]).toBe(a2_1[0]); expect(a1_1[1]).toBe(a2_1[1]); @@ -747,9 +758,13 @@ it("escapes characters, unicode, and hex", () => { expect(a1_1.input).toBe(a2_1.input); expect(a1.lastIndex).toBe(a2.lastIndex); expect(a1_1.groups).toBe(a2_1.groups); + // @ts-ignore expect(a1_1.indices[0][0]).toBe(a2_1.indices[0][0]); + // @ts-ignore expect(a1_1.indices[0][1]).toBe(a2_1.indices[0][1]); + // @ts-ignore expect(a1_1.indices[1][0]).toBe(a2_1.indices[1][0]); + // @ts-ignore expect(a1_1.indices[1][1]).toBe(a2_1.indices[1][1]); }); @@ -768,20 +783,20 @@ it("lookbehinds", () => { expect( /[\x00-\x1F\x27\x5C\x7F-\x9F]|[\uD800-\uDBFF]\(?<=[\uDC00-\uDFFF]\)|(?!.*[\uD800-\uDBFF][\uDC00-\uDFFF]).*[\uDC00-\uDFFF]/ instanceof - RegExp + RegExp, ).toBe(true); expect( /[\x00-\x1F\x27\x5C\x7F-\x9F]|[\uD800-\uDBFF](?<=[\uDC00-\uDFFF])|(?!.*[\uD800-\uDBFF][\uDC00-\uDFFF]).*[\uDC00-\uDFFF]/ instanceof - OnigurumaRegExp + OnigurumaRegExp, ).toBe(true); expect(/(?<=\1d(o))/ instanceof OnigurumaRegExp).toBe(true); expect(/\(?<=\1d(o)\)/ instanceof OnigurumaRegExp).toBe(false); expect( - /(?!.*[\uD800-\uDBFF][\uDC00-\uDFFF]).*[\uDC00-\uDFFF]/ instanceof RegExp + /(?!.*[\uD800-\uDBFF][\uDC00-\uDFFF]).*[\uDC00-\uDFFF]/ instanceof RegExp, ).toBe(true); expect( - /\(?!.*[\uD800-\uDBFF][\uDC00-\uDFFF]\).*[\uDC00-\uDFFF]/ instanceof RegExp + /\(?!.*[\uD800-\uDBFF][\uDC00-\uDFFF]\).*[\uDC00-\uDFFF]/ instanceof RegExp, ).toBe(true); let e = new OnigurumaRegExp("(?<=)"); diff --git a/test/bun.js/os.test.js b/test/bun.js/os.test.js index c368298cb..792d2cf40 100644 --- a/test/bun.js/os.test.js +++ b/test/bun.js/os.test.js @@ -41,11 +41,11 @@ it("tmpdir", () => { if (process.platform === "win32") { expect(os.tmpdir()).toBe(process.env.TEMP || process.env.TMP); expect(os.tmpdir()).toBe( - `${process.env.SystemRoot || process.env.windir}\\temp` + `${process.env.SystemRoot || process.env.windir}\\temp`, ); } else { expect(os.tmpdir()).toBe( - process.env.TMPDIR || process.env.TMP || process.env.TEMP || "/tmp" + process.env.TMPDIR || process.env.TMP || process.env.TEMP || "/tmp", ); } }); @@ -57,8 +57,8 @@ it("hostname", () => { it("platform", () => { expect( ["win32", "darwin", "linux", "wasm"].some( - (platform) => os.platform() === platform - ) + (platform) => os.platform() === platform, + ), ).toBe(true); }); @@ -68,7 +68,7 @@ it("release", () => { it("type", () => { expect( - ["Windows_NT", "Darwin", "Linux"].some((type) => os.type() === type) + ["Windows_NT", "Darwin", "Linux"].some((type) => os.type() === type), ).toBe(true); }); diff --git a/test/bun.js/path.test.js b/test/bun.js/path.test.js index 72dad93d2..97132512c 100644 --- a/test/bun.js/path.test.js +++ b/test/bun.js/path.test.js @@ -66,7 +66,7 @@ it("path.basename", () => { // On unix a backslash is just treated as any other character. strictEqual( path.posix.basename("\\dir\\basename.ext"), - "\\dir\\basename.ext" + "\\dir\\basename.ext", ); strictEqual(path.posix.basename("\\basename.ext"), "\\basename.ext"); strictEqual(path.posix.basename("basename.ext"), "basename.ext"); @@ -79,7 +79,7 @@ it("path.basename", () => { const controlCharFilename = `Icon${String.fromCharCode(13)}`; strictEqual( path.posix.basename(`/a/b/${controlCharFilename}`), - controlCharFilename + controlCharFilename, ); }); @@ -215,7 +215,7 @@ it("path.join", () => { if (actual !== expected && actualAlt !== expected) { const delimiter = test[0].map(JSON.stringify).join(","); const message = `path.${os}.join(${delimiter})\n expect=${JSON.stringify( - expected + expected, )}\n actual=${JSON.stringify(actual)}`; failures.push(`\n${message}`); } @@ -295,7 +295,7 @@ it("path.relative", () => { .slice(0, 2) .map(JSON.stringify) .join(",")})\n expect=${JSON.stringify( - expected + expected, )}\n actual=${JSON.stringify(actual)}`; failures.push(`\n${message}`); } @@ -355,7 +355,7 @@ it("path.normalize", () => { strictEqual( path.posix.normalize("./fixtures///b/../b/c.js"), - "fixtures/b/c.js" + "fixtures/b/c.js", ); strictEqual(path.posix.normalize("/foo/../../../bar"), "/bar"); strictEqual(path.posix.normalize("a//b//../b"), "a/b"); @@ -372,19 +372,19 @@ it("path.normalize", () => { strictEqual(path.posix.normalize("../.../.././.../../../bar"), "../../bar"); strictEqual( path.posix.normalize("../../../foo/../../../bar"), - "../../../../../bar" + "../../../../../bar", ); strictEqual( path.posix.normalize("../../../foo/../../../bar/../../"), - "../../../../../../" + "../../../../../../", ); strictEqual( path.posix.normalize("../foobar/barfoo/foo/../../../bar/../../"), - "../../" + "../../", ); strictEqual( path.posix.normalize("../.../../foobar/../../../bar/../../baz"), - "../../../../baz" + "../../../../baz", ); strictEqual(path.posix.normalize("foo/bar\\baz"), "foo/bar\\baz"); }); @@ -446,7 +446,7 @@ it("path.resolve", () => { const message = `path.${os}.resolve(${test .map(JSON.stringify) .join(",")})\n expect=${JSON.stringify( - expected + expected, )}\n actual=${JSON.stringify(actual)}`; if (actual !== expected && actualAlt !== expected) failures.push(message); }); diff --git a/test/bun.js/peek.test.ts b/test/bun.js/peek.test.ts index 90a7748f5..1c3920a4b 100644 --- a/test/bun.js/peek.test.ts +++ b/test/bun.js/peek.test.ts @@ -22,11 +22,14 @@ test("peek", () => { // If we peek a rejected promise, it: // - returns the error // - does not mark the promise as handled - const rejected = Promise.reject( - new Error("Succesfully tested promise rejection") + const rejected = Promise.reject<Error>( + new Error("Succesfully tested promise rejection"), + ); + const peeked = peek(rejected); + expect(peeked instanceof Error).toBe(true); + expect((peeked as Error).message).toBe( + "Succesfully tested promise rejection", ); - expect(peek(rejected).message).toBe("Succesfully tested promise rejection"); - rejected.catch(() => {}); }); test("peek.status", () => { diff --git a/test/bun.js/performance.test.js b/test/bun.js/performance.test.js index 0ff75b945..51479209c 100644 --- a/test/bun.js/performance.test.js +++ b/test/bun.js/performance.test.js @@ -19,6 +19,6 @@ it("performance.now() should be monotonic", () => { it("performance.timeOrigin + performance.now() should be similar to Date.now()", () => { expect( - Math.abs(performance.timeOrigin + performance.now() - Date.now()) < 1000 + Math.abs(performance.timeOrigin + performance.now() - Date.now()) < 1000, ).toBe(true); }); diff --git a/test/bun.js/plugins.d.ts b/test/bun.js/plugins.d.ts new file mode 100644 index 000000000..aebfd952b --- /dev/null +++ b/test/bun.js/plugins.d.ts @@ -0,0 +1,11 @@ +declare var objectModuleResult: any; +declare var laterCode: any; + +declare module "beep:*"; +declare module "async:*"; +declare module "asyncret:*"; +declare module "asyncfail:*"; +declare module "async-obj:*"; +declare module "obj:*"; +declare module "delay:*"; +declare module "./*.svelte"; diff --git a/test/bun.js/plugins.test.ts b/test/bun.js/plugins.test.ts index 6593b077d..1d0b0821a 100644 --- a/test/bun.js/plugins.test.ts +++ b/test/bun.js/plugins.test.ts @@ -1,3 +1,4 @@ +/// <reference types="./plugins" /> import { plugin } from "bun"; import { describe, expect, it } from "bun:test"; import { resolve } from "path"; @@ -45,7 +46,7 @@ plugin({ })); builder.onLoad( { filter: /.*/, namespace: "fail" }, - () => globalThis.failingObject + () => globalThis.failingObject, ); }, }); @@ -106,7 +107,7 @@ plugin({ }); }, 1); }); - } + }, ); builder.onResolve({ filter: /.*/, namespace: "asyncfail" }, ({ path }) => ({ @@ -121,7 +122,7 @@ plugin({ await Promise.resolve(1); await 1; throw globalThis.asyncfail; - } + }, ); builder.onResolve({ filter: /.*/, namespace: "asyncret" }, ({ path }) => ({ @@ -136,7 +137,7 @@ plugin({ await 100; await Promise.resolve(10); return await globalThis.asyncret; - } + }, ); }, }); @@ -170,7 +171,8 @@ describe("require", () => { describe("dynamic import", () => { it("SSRs `<h1>Hello world!</h1>` with Svelte", async () => { - const { default: App } = await import("./hello.svelte"); + const { default: App }: any = await import("./hello.svelte"); + const { html } = App.render(); expect(html).toBe("<h1>Hello world!</h1>"); @@ -240,7 +242,7 @@ describe("errors", () => { try { require(`fail:my-file-${loader}`); throw -1; - } catch (e) { + } catch (e: any) { if (e === -1) { throw new Error("Expected error"); } @@ -259,7 +261,7 @@ describe("errors", () => { try { require(`fail:my-file-${loader}-3`); throw -1; - } catch (e) { + } catch (e: any) { if (e === -1) { throw new Error("Expected error"); } @@ -273,7 +275,7 @@ describe("errors", () => { globalThis.asyncret = { wat: true }; await import("asyncret:my-file"); throw -1; - } catch (e) { + } catch (e: any) { if (e === -1) { throw new Error("Expected error"); } @@ -287,7 +289,7 @@ describe("errors", () => { globalThis.asyncfail = new Error("async error"); await import("asyncfail:my-file"); throw -1; - } catch (e) { + } catch (e: any) { if (e === -1) { throw new Error("Expected error"); } @@ -307,7 +309,7 @@ describe("errors", () => { try { require(`fail:my-file-${i}-2`); throw -1; - } catch (e) { + } catch (e: any) { if (e === -1) { throw new Error("Expected error"); } @@ -321,7 +323,7 @@ describe("errors", () => { globalThis.asyncOnLoad = `const x: string = -NaNAn../!!;`; await import("async:fail"); throw -1; - } catch (e) { + } catch (e: any) { if (e === -1) { throw new Error("Expected error"); } diff --git a/test/bun.js/print-process-args.js b/test/bun.js/print-process-args.js index 3d4540053..0ab238122 100644 --- a/test/bun.js/print-process-args.js +++ b/test/bun.js/print-process-args.js @@ -1,4 +1,4 @@ -var writer = Bun.stdout.writer() +var writer = Bun.stdout.writer(); writer.write(JSON.stringify(process.argv)); await writer.flush(true); -process.exit(0);
\ No newline at end of file +process.exit(0); diff --git a/test/bun.js/process-args.test.js b/test/bun.js/process-args.test.js index 6bdfbf9e0..512b6b92c 100644 --- a/test/bun.js/process-args.test.js +++ b/test/bun.js/process-args.test.js @@ -1,33 +1,41 @@ - import { spawn } from "bun"; import { test, expect } from "bun:test"; test("args exclude run", async () => { - const arg0 = process.argv[0]; - const arg1 = import.meta.dir + '/print-process-args.js'; + const arg0 = process.argv[0]; + const arg1 = import.meta.dir + "/print-process-args.js"; - const exe = process.versions.bun.includes("debug") ? "bun-debug" : "bun"; + const exe = process.versions.bun.includes("debug") ? "bun-debug" : "bun"; - const { stdout: s1 } = spawn([exe, "print-process-args.js"], { cwd: import.meta.dir }); - const t1 = JSON.parse(await new Response(s1).text()); - expect(t1[0]).toBe(arg0); - expect(t1[1]).toBe(arg1); + const { stdout: s1 } = spawn([exe, "print-process-args.js"], { + cwd: import.meta.dir, + }); + const t1 = JSON.parse(await new Response(s1).text()); + expect(t1[0]).toBe(arg0); + expect(t1[1]).toBe(arg1); - const { stdout: s2 } = spawn([exe, "print-process-args.js", "arg1"], { cwd: import.meta.dir }); - const t2 = JSON.parse(await new Response(s2).text()); - expect(t2[0]).toBe(arg0); - expect(t2[1]).toBe(arg1); - expect(t2[2]).toBe("arg1"); + const { stdout: s2 } = spawn([exe, "print-process-args.js", "arg1"], { + cwd: import.meta.dir, + }); + const t2 = JSON.parse(await new Response(s2).text()); + expect(t2[0]).toBe(arg0); + expect(t2[1]).toBe(arg1); + expect(t2[2]).toBe("arg1"); - const { stdout: s3 } = spawn([exe, "run", "print-process-args.js"], { cwd: import.meta.dir }); - const t3 = JSON.parse(await new Response(s3).text()); - expect(t3[0]).toBe(arg0); - expect(t3[1]).toBe(arg1); + const { stdout: s3 } = spawn([exe, "run", "print-process-args.js"], { + cwd: import.meta.dir, + }); + const t3 = JSON.parse(await new Response(s3).text()); + expect(t3[0]).toBe(arg0); + expect(t3[1]).toBe(arg1); - const { stdout: s4 } = spawn([exe, "run", "print-process-args.js", "arg1", "arg2"], { cwd: import.meta.dir }); - const t4 = JSON.parse(await new Response(s4).text()); - expect(t4[0]).toBe(arg0); - expect(t4[1]).toBe(arg1); - expect(t4[2]).toBe("arg1"); - expect(t4[3]).toBe("arg2"); -});
\ No newline at end of file + const { stdout: s4 } = spawn( + [exe, "run", "print-process-args.js", "arg1", "arg2"], + { cwd: import.meta.dir }, + ); + const t4 = JSON.parse(await new Response(s4).text()); + expect(t4[0]).toBe(arg0); + expect(t4[1]).toBe(arg1); + expect(t4[2]).toBe("arg1"); + expect(t4[3]).toBe("arg2"); +}); diff --git a/test/bun.js/process-nexttick.js b/test/bun.js/process-nexttick.js index 337977c0a..ea9d0581e 100644 --- a/test/bun.js/process-nexttick.js +++ b/test/bun.js/process-nexttick.js @@ -59,7 +59,7 @@ await new Promise((resolve, reject) => { if (!passed) throw new Error( - "queueMicrotask should throw a TypeError if the argument is not a function" + "queueMicrotask should throw a TypeError if the argument is not a function", ); } @@ -73,7 +73,7 @@ await new Promise((resolve, reject) => { if (!passed) throw new Error( - "queueMicrotask should throw a TypeError if the argument is empty" + "queueMicrotask should throw a TypeError if the argument is empty", ); } @@ -86,6 +86,6 @@ await new Promise((resolve, reject) => { resolve(true); }, 12345, - "hello" + "hello", ); }); diff --git a/test/bun.js/process-nexttick.test.js b/test/bun.js/process-nexttick.test.js index f6d2b7663..a1b1b84b0 100644 --- a/test/bun.js/process-nexttick.test.js +++ b/test/bun.js/process-nexttick.test.js @@ -61,7 +61,7 @@ it("process.nextTick", async () => { if (!passed) throw new Error( - "queueMicrotask should throw a TypeError if the argument is not a function" + "queueMicrotask should throw a TypeError if the argument is not a function", ); } @@ -75,7 +75,7 @@ it("process.nextTick", async () => { if (!passed) throw new Error( - "queueMicrotask should throw a TypeError if the argument is empty" + "queueMicrotask should throw a TypeError if the argument is empty", ); } }); @@ -89,7 +89,7 @@ it("process.nextTick 2 args", async () => { resolve(true); }, 12345, - "hello" + "hello", ); }); }); diff --git a/test/bun.js/process.test.js b/test/bun.js/process.test.js index 3ca93c983..296e786cf 100644 --- a/test/bun.js/process.test.js +++ b/test/bun.js/process.test.js @@ -40,7 +40,7 @@ it("process", () => { if (typeof JSON.parse(JSON.stringify(process.env)).toJSON !== "undefined") { throw new Error( - "process.env should call toJSON to hide its internal state" + "process.env should call toJSON to hide its internal state", ); } @@ -72,6 +72,6 @@ it("process.release", () => { expect(process.release.sourceUrl).toBe( `https://github.com/oven-sh/bun/release/bun-v${process.versions.bun}/bun-${ process.platform - }-${{ arm64: "aarch64", x64: "x64" }[process.arch] || process.arch}.zip` + }-${{ arm64: "aarch64", x64: "x64" }[process.arch] || process.arch}.zip`, ); }); diff --git a/test/bun.js/react-dom-server.bun.cjs b/test/bun.js/react-dom-server.bun.cjs index 9cc42cc6a..6367ee8aa 100644 --- a/test/bun.js/react-dom-server.bun.cjs +++ b/test/bun.js/react-dom-server.bun.cjs @@ -1,5 +1,5 @@ /** -* @license React + * @license React * react-dom-server.bun.production.min.js * * Copyright (c) Meta Platforms, Inc. and affiliates. @@ -8,131 +8,2995 @@ * LICENSE file in the root directory of this source tree. */ -'use strict';var ba=require("react"),ca=require("react-dom");function l(a,b){0!==b.length&&a.write(b)}function da(a,b){"function"===typeof a.error?a.error(b):a.close()} -var r=Object.prototype.hasOwnProperty,ea=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,fa={},ha={}; -function ia(a){if(r.call(ha,a))return!0;if(r.call(fa,a))return!1;if(ea.test(a))return ha[a]=!0;fa[a]=!0;return!1}function t(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var v={},ja="children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" "); -ja.push("innerText","textContent");ja.forEach(function(a){v[a]=new t(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];v[b]=new t(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){v[a]=new t(a,2,!1,a.toLowerCase(),null,!1,!1)}); -["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){v[a]=new t(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){v[a]=new t(a,3,!1,a.toLowerCase(),null,!1,!1)}); -["checked","multiple","muted","selected"].forEach(function(a){v[a]=new t(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){v[a]=new t(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){v[a]=new t(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){v[a]=new t(a,5,!1,a.toLowerCase(),null,!1,!1)});var ka=/[\-:]([a-z])/g;function la(a){return a[1].toUpperCase()} -"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ka, -la);v[b]=new t(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ka,la);v[b]=new t(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ka,la);v[b]=new t(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){v[a]=new t(a,1,!1,a.toLowerCase(),null,!1,!1)}); -v.xlinkHref=new t("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){v[a]=new t(a,1,!1,a.toLowerCase(),null,!0,!0)}); -var ma={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0, -zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},na=["Webkit","ms","Moz","O"];Object.keys(ma).forEach(function(a){na.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);ma[b]=ma[a]})});var oa=/["'&<>]/; -function w(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=oa.exec(a);if(b){var c="",d,e=0;for(d=b.index;d<a.length;d++){switch(a.charCodeAt(d)){case 34:b=""";break;case 38:b="&";break;case 39:b="'";break;case 60:b="<";break;case 62:b=">";break;default:continue}e!==d&&(c+=a.substring(e,d));e=d+1;c+=b}a=e!==d?c+a.substring(e,d):c}return a}var pa=/([A-Z])/g,qa=/^ms-/,ra=Array.isArray,x=Object.assign,y=null,sa=[],va={preload:ta,preinit:ua}; -function ta(a,b){if(y){var c=y;if("string"===typeof a&&a&&"object"===typeof b&&null!==b){var d=b.as,e=c.preloadsMap.get(a);e||(e=z(c,a,d,{href:a,rel:"preload",as:d,crossOrigin:"font"===d?"":b.crossOrigin,integrity:b.integrity}));switch(d){case "font":c.fontPreloads.add(e);break;case "style":c.explicitStylePreloads.add(e);break;case "script":c.explicitScriptPreloads.add(e)}}}} -function ua(a,b){if(y){var c=y;if("string"===typeof a&&a&&"object"===typeof b&&null!==b)switch(b.as){case "style":var d=c.stylesMap.get(a);d||(d=b.precedence||"default",d=wa(c,a,d,{rel:"stylesheet",href:a,"data-precedence":d,crossOrigin:b.crossOrigin}));d.set.add(d);c.explicitStylePreloads.add(d.hint);break;case "script":d=c.scriptsMap.get(a),d||(d=xa(c,a,{src:a,async:!0,crossOrigin:b.crossOrigin,integrity:b.integrity}),c.scripts.add(d))}}} -function ya(a,b){return{rel:"preload",as:"style",href:a,crossOrigin:b.crossOrigin,integrity:b.integrity,media:b.media,hrefLang:b.hrefLang,referrerPolicy:b.referrerPolicy}}function za(a,b){return{rel:"preload",as:"script",href:a,crossOrigin:b.crossOrigin,integrity:b.integrity,referrerPolicy:b.referrerPolicy}}function z(a,b,c,d){c={type:"preload",as:c,href:b,flushed:!1,props:d};a.preloadsMap.set(b,c);return c} -function wa(a,b,c,d){var e=a.stylesMap,f=a.preloadsMap,g=a.precedences,h=g.get(c);h||(h=new Set,g.set(c,h));(f=f.get(b))?(a=f.props,null==d.crossOrigin&&(d.crossOrigin=a.crossOrigin),null==d.referrerPolicy&&(d.referrerPolicy=a.referrerPolicy),null==d.title&&(d.title=a.title)):(f=ya(b,d),f=z(a,b,"style",f),a.explicitStylePreloads.add(f));c={type:"style",href:b,precedence:c,flushed:!1,inShell:!1,props:d,hint:f,set:h};e.set(b,c);return c} -function xa(a,b,c){var d=a.scriptsMap,e=a.preloadsMap.get(b);e?(a=e.props,null==c.crossOrigin&&(c.crossOrigin=a.crossOrigin),null==c.referrerPolicy&&(c.referrerPolicy=a.referrerPolicy),null==c.integrity&&(c.integrity=a.integrity)):(e=za(b,c),e=z(a,b,"script",e),a.explicitScriptPreloads.add(e));c={type:"script",src:b,flushed:!1,props:c,hint:e};d.set(b,c);return c} -function Aa(a,b){if(!y)throw Error('"currentResources" was expected to exist. This is a bug in React.');var c=y;switch(a){case "title":var d=b.children;Array.isArray(d)&&1===d.length&&(d=d[0]);if("string"===typeof d||"number"===typeof d){var e="title::"+d;a=c.headsMap.get(e);a||(b=x({},b),b.children=d,a={type:"title",props:b,flushed:!1},c.headsMap.set(e,a),c.headResources.add(a))}return!0;case "meta":if("string"===typeof b.charSet)e="charSet";else if("string"===typeof b.content)if(a="::"+b.content, -"string"===typeof b.httpEquiv)e="httpEquiv::"+b.httpEquiv+a;else if("string"===typeof b.name)e="name::"+b.name+a;else if("string"===typeof b.itemProp)e="itemProp::"+b.itemProp+a;else if("string"===typeof b.property){var f=b.property;e="property::"+f+a;d=f;a=f.split(":").slice(0,-1).join(":");(a=c.structuredMetaKeys.get(a))&&(e=a.key+"::child::"+e)}e&&!c.headsMap.has(e)&&(b={type:"meta",key:e,props:x({},b),flushed:!1},c.headsMap.set(e,b),"charSet"===e?c.charset=b:(d&&c.structuredMetaKeys.set(d,b), -c.headResources.add(b)));return!0;case "base":return e=b.target,d=b.href,e="base"+("string"===typeof d?'[href="'+d+'"]':":not([href])")+("string"===typeof e?'[target="'+e+'"]':":not([target])"),c.headsMap.has(e)||(b={type:"base",props:x({},b),flushed:!1},c.headsMap.set(e,b),c.bases.add(b)),!0}return!1} -function Ba(a){if(!y)throw Error('"currentResources" was expected to exist. This is a bug in React.');var b=y,c=a.rel,d=a.href;if(!d||"string"!==typeof d||!c||"string"!==typeof c)return!1;switch(c){case "stylesheet":var e=a.onLoad,f=a.onError;c=a.precedence;var g=a.disabled;if("string"!==typeof c||e||f||null!=g)return c=b.preloadsMap.get(d),c||(c=z(b,d,"style",ya(d,a)),b.usedStylePreloads.add(c)),!1;e=b.stylesMap.get(d);e||(a=x({},a),a.href=d,a.rel="stylesheet",a["data-precedence"]=c,delete a.precedence, -e=wa(y,d,c,a),b.usedStylePreloads.add(e.hint));b.boundaryResources?b.boundaryResources.add(e):e.set.add(e);return!0;case "preload":switch(e=a.as,e){case "script":case "style":case "font":c=b.preloadsMap.get(d);if(!c)switch(a=x({},a),a.href=d,a.rel="preload",a.as=e,"font"===e&&(a.crossOrigin=""),c=z(b,d,e,a),e){case "script":b.explicitScriptPreloads.add(c);break;case "style":b.explicitStylePreloads.add(c);break;case "font":b.fontPreloads.add(c)}return!0}}if(a.onLoad||a.onError)return!0;d="rel:"+c+ -"::href:"+d+"::sizes:"+("string"===typeof a.sizes?a.sizes:"")+"::media:"+("string"===typeof a.media?a.media:"");e=b.headsMap.get(d);if(!e)switch(e={type:"link",props:x({},a),flushed:!1},b.headsMap.set(d,e),c){case "preconnect":case "dns-prefetch":b.preconnects.add(e);break;default:b.headResources.add(e)}return!0}function Ca(a,b){var c=a.boundaryResources;c&&(b.forEach(function(a){return c.add(a)}),b.clear())}function Da(a,b){b.forEach(function(a){return a.set.add(a)});b.clear()} -var Ea=ca.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Dispatcher,Fa=/(<\/|<)(s)(cript)/gi;function Ga(a,b,c,d){return""+b+("s"===c?"\\u0073":"\\u0053")+d} -function Ha(a,b,c,d,e){a=void 0===a?"":a;b=void 0===b?"<script>":'<script nonce="'+w(b)+'">';var f=[];void 0!==c&&f.push(b,(""+c).replace(Fa,Ga),"\x3c/script>");if(void 0!==d)for(c=0;c<d.length;c++){var g=d[c],h="string"===typeof g?void 0:g.integrity;f.push('<script src="',w("string"===typeof g?g:g.src));h&&f.push('" integrity="',w(h));f.push('" async="">\x3c/script>')}if(void 0!==e)for(d=0;d<e.length;d++)c=e[d],g="string"===typeof c?void 0:c.integrity,f.push('<script type="module" src="',w("string"=== -typeof c?c:c.src)),g&&f.push('" integrity="',w(g)),f.push('" async="">\x3c/script>');return{bootstrapChunks:f,startInlineScript:b,placeholderPrefix:a+"P:",segmentPrefix:a+"S:",boundaryPrefix:a+"B:",idPrefix:a,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1,sentStyleInsertionFunction:!1}}function A(a,b,c){return{insertionMode:a,selectedValue:b,noscriptTagInScope:c}} -function Ia(a){return A("http://www.w3.org/2000/svg"===a?2:"http://www.w3.org/1998/Math/MathML"===a?3:0,null,!1)} -function Ja(a,b,c){switch(b){case "noscript":return A(1,null,!0);case "select":return A(1,null!=c.value?c.value:c.defaultValue,a.noscriptTagInScope);case "svg":return A(2,null,a.noscriptTagInScope);case "math":return A(3,null,a.noscriptTagInScope);case "foreignObject":return A(1,null,a.noscriptTagInScope);case "table":return A(4,null,a.noscriptTagInScope);case "thead":case "tbody":case "tfoot":return A(5,null,a.noscriptTagInScope);case "colgroup":return A(7,null,a.noscriptTagInScope);case "tr":return A(6, -null,a.noscriptTagInScope)}return 4<=a.insertionMode||0===a.insertionMode?A(1,null,a.noscriptTagInScope):a}function Ka(a,b,c,d){if(""===b)return d;d&&a.push("\x3c!-- --\x3e");a.push(w(b));return!0}var La=new Map; -function Ma(a,b,c){if("object"!==typeof c)throw Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.");b=!0;for(var d in c)if(r.call(c,d)){var e=c[d];if(null!=e&&"boolean"!==typeof e&&""!==e){if(0===d.indexOf("--")){var f=w(d);e=w((""+e).trim())}else{f=d;var g=La.get(f);void 0!==g?f=g:(g=w(f.replace(pa,"-$1").toLowerCase().replace(qa,"-ms-")),La.set(f,g),f=g);e="number"===typeof e?0===e||r.call(ma, -d)?""+e:e+"px":w((""+e).trim())}b?(b=!1,a.push(' style="',f,":",e)):a.push(";",f,":",e)}}b||a.push('"')} -function C(a,b,c,d){switch(c){case "style":Ma(a,b,d);return;case "defaultValue":case "defaultChecked":case "innerHTML":case "suppressContentEditableWarning":case "suppressHydrationWarning":return}if(!(2<c.length)||"o"!==c[0]&&"O"!==c[0]||"n"!==c[1]&&"N"!==c[1])if(b=v.hasOwnProperty(c)?v[c]:null,null!==b){switch(typeof d){case "function":case "symbol":return;case "boolean":if(!b.acceptsBooleans)return}c=b.attributeName;switch(b.type){case 3:d&&a.push(" ",c,'=""');break;case 4:!0===d?a.push(" ",c,'=""'): -!1!==d&&a.push(" ",c,'="',w(d),'"');break;case 5:isNaN(d)||a.push(" ",c,'="',w(d),'"');break;case 6:!isNaN(d)&&1<=d&&a.push(" ",c,'="',w(d),'"');break;default:b.sanitizeURL&&(d=""+d),a.push(" ",c,'="',w(d),'"')}}else if(ia(c)){switch(typeof d){case "function":case "symbol":return;case "boolean":if(b=c.toLowerCase().slice(0,5),"data-"!==b&&"aria-"!==b)return}a.push(" ",c,'="',w(d),'"')}} -function D(a,b,c){if(null!=b){if(null!=c)throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");if("object"!==typeof b||!("__html"in b))throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");b=b.__html;null!==b&&void 0!==b&&a.push(""+b)}}function Na(a){var b="";ba.Children.forEach(a,function(a){null!=a&&(b+=a)});return b} -function F(a,b,c){var d="stylesheet"===b.rel;a.push(G("link"));for(var e in b)if(r.call(b,e)){var f=b[e];if(null!=f)switch(e){case "children":case "dangerouslySetInnerHTML":throw Error("link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");case "precedence":if(d)continue;default:C(a,c,e,f)}}a.push("/>");return null} -function I(a,b,c,d){a.push(G(c));for(var e in b)if(r.call(b,e)){var f=b[e];if(null!=f)switch(e){case "children":case "dangerouslySetInnerHTML":throw Error(c+" is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");default:C(a,d,e,f)}}a.push("/>");return null} -function Oa(a,b,c){a.push(G("title"));var d=null,e;for(e in b)if(r.call(b,e)){var f=b[e];if(null!=f)switch(e){case "children":d=f;break;case "dangerouslySetInnerHTML":throw Error("`dangerouslySetInnerHTML` does not make sense on <title>.");default:C(a,c,e,f)}}a.push(">");b=Array.isArray(d)&&2>d.length?d[0]||null:d;"string"!==typeof b&&"number"!==typeof b||a.push(w(b));a.push("</","title",">");return null} -function Pa(a,b,c){a.push(G("script"));var d=null,e=null,f;for(f in b)if(r.call(b,f)){var g=b[f];if(null!=g)switch(f){case "children":d=g;break;case "dangerouslySetInnerHTML":e=g;break;default:C(a,c,f,g)}}a.push(">");D(a,e,d);"string"===typeof d&&a.push(w(d));a.push("</","script",">");return null} -function J(a,b,c,d){a.push(G(c));var e=c=null,f;for(f in b)if(r.call(b,f)){var g=b[f];if(null!=g)switch(f){case "children":c=g;break;case "dangerouslySetInnerHTML":e=g;break;default:C(a,d,f,g)}}a.push(">");D(a,e,c);return"string"===typeof c?(a.push(w(c)),null):c}var Qa=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,Ra=new Map;function G(a){var b=Ra.get(a);if(void 0===b){if(!Qa.test(a))throw Error("Invalid tag: "+a);b="<"+a;Ra.set(a,b)}return b} -function Sa(a,b,c,d,e,f,g){switch(c){case "select":a.push(G("select"));var h=g=null,m;for(m in d)if(r.call(d,m)){var k=d[m];if(null!=k)switch(m){case "children":g=k;break;case "dangerouslySetInnerHTML":h=k;break;case "defaultValue":case "value":break;default:C(a,e,m,k)}}a.push(">");D(a,h,g);return g;case "option":g=f.selectedValue;a.push(G("option"));var p=m=k=null,n=null;for(h in d)if(r.call(d,h)){var q=d[h];if(null!=q)switch(h){case "children":k=q;break;case "selected":p=q;break;case "dangerouslySetInnerHTML":n= -q;break;case "value":m=q;default:C(a,e,h,q)}}if(null!=g)if(d=null!==m?""+m:Na(k),ra(g))for(e=0;e<g.length;e++){if(""+g[e]===d){a.push(' selected=""');break}}else""+g===d&&a.push(' selected=""');else p&&a.push(' selected=""');a.push(">");D(a,n,k);return k;case "textarea":a.push(G("textarea"));k=h=g=null;for(n in d)if(r.call(d,n)&&(m=d[n],null!=m))switch(n){case "children":k=m;break;case "value":g=m;break;case "defaultValue":h=m;break;case "dangerouslySetInnerHTML":throw Error("`dangerouslySetInnerHTML` does not make sense on <textarea>."); -default:C(a,e,n,m)}null===g&&null!==h&&(g=h);a.push(">");if(null!=k){if(null!=g)throw Error("If you supply `defaultValue` on a <textarea>, do not pass children.");if(ra(k)&&1<k.length)throw Error("<textarea> can only have at most one child.");g=""+k}"string"===typeof g&&"\n"===g[0]&&a.push("\n");null!==g&&a.push(w(""+g));return null;case "input":a.push(G("input"));m=n=h=g=null;for(k in d)if(r.call(d,k)&&(p=d[k],null!=p))switch(k){case "children":case "dangerouslySetInnerHTML":throw Error("input is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."); -case "defaultChecked":m=p;break;case "defaultValue":h=p;break;case "checked":n=p;break;case "value":g=p;break;default:C(a,e,k,p)}null!==n?C(a,e,"checked",n):null!==m&&C(a,e,"checked",m);null!==g?C(a,e,"value",g):null!==h&&C(a,e,"value",h);a.push("/>");return null;case "menuitem":a.push(G("menuitem"));for(var u in d)if(r.call(d,u)&&(g=d[u],null!=g))switch(u){case "children":case "dangerouslySetInnerHTML":throw Error("menuitems cannot have `children` nor `dangerouslySetInnerHTML`.");default:C(a,e,u, -g)}a.push(">");return null;case "title":return a=2!==f.insertionMode&&!f.noscriptTagInScope&&Aa("title",d)?null:Oa(a,d,e),a;case "link":return!f.noscriptTagInScope&&Ba(d)?(g&&a.push("\x3c!-- --\x3e"),a=null):a=F(a,d,e),a;case "script":if(h=!f.noscriptTagInScope){if(!y)throw Error('"currentResources" was expected to exist. This is a bug in React.');h=y;k=d.src;n=d.onLoad;m=d.onError;k&&"string"===typeof k?d.async?(n||m?(n=h.preloadsMap.get(k),n||(n=z(h,k,"script",za(k,d)),h.usedScriptPreloads.add(n))): -(n=h.scriptsMap.get(k),n||(n=x({},d),n.src=k,n=xa(h,k,n),h.scripts.add(n))),h=!0):h=!1:h=!1}h?(g&&a.push("\x3c!-- --\x3e"),a=null):a=Pa(a,d,e);return a;case "meta":return!f.noscriptTagInScope&&Aa("meta",d)?(g&&a.push("\x3c!-- --\x3e"),a=null):a=I(a,d,"meta",e),a;case "base":return!f.noscriptTagInScope&&Aa("base",d)?(g&&a.push("\x3c!-- --\x3e"),a=null):a=I(a,d,"base",e),a;case "listing":case "pre":a.push(G(c));h=g=null;for(p in d)if(r.call(d,p)&&(k=d[p],null!=k))switch(p){case "children":g=k;break; -case "dangerouslySetInnerHTML":h=k;break;default:C(a,e,p,k)}a.push(">");if(null!=h){if(null!=g)throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");if("object"!==typeof h||!("__html"in h))throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");d=h.__html;null!==d&&void 0!==d&&("string"===typeof d&&0<d.length&&"\n"===d[0]?a.push("\n",d):a.push(""+d))}"string"=== -typeof g&&"\n"===g[0]&&a.push("\n");return g;case "area":case "br":case "col":case "embed":case "hr":case "img":case "keygen":case "param":case "source":case "track":case "wbr":return I(a,d,c,e);case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return J(a,d,c,e);case "head":return J(b,d,c,e);case "html":return 0===f.insertionMode&&b.push("<!DOCTYPE html>"),J(b,d,c,e);default:if(-1=== -c.indexOf("-")&&"string"!==typeof d.is)return J(a,d,c,e);a.push(G(c));h=g=null;for(q in d)if(r.call(d,q)&&(k=d[q],null!=k&&"function"!==typeof k&&"object"!==typeof k&&!1!==k))switch(!0===k&&(k=""),"className"===q&&(q="class"),q){case "children":g=k;break;case "dangerouslySetInnerHTML":h=k;break;case "style":Ma(a,e,k);break;case "suppressContentEditableWarning":case "suppressHydrationWarning":break;default:ia(q)&&"function"!==typeof k&&"symbol"!==typeof k&&a.push(" ",q,'="',w(k),'"')}a.push(">");D(a, -h,g);return g}}function Ta(a,b,c){switch(c){case "title":case "script":case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "input":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":return;case "body":b.unshift("</",c,">");return;case "html":b.push("</",c,">");return}a.push("</",c,">")} -function Ua(a,b,c){l(a,'\x3c!--$?--\x3e<template id="');if(null===c)throw Error("An ID must have been assigned before we can complete the boundary.");l(a,c);return!!a.write('"></template>')} -function Va(a,b,c,d){switch(c.insertionMode){case 0:case 1:return l(a,'<div hidden id="'),l(a,b.segmentPrefix),l(a,d.toString(16)),!!a.write('">');case 2:return l(a,'<svg aria-hidden="true" style="display:none" id="'),l(a,b.segmentPrefix),l(a,d.toString(16)),!!a.write('">');case 3:return l(a,'<math aria-hidden="true" style="display:none" id="'),l(a,b.segmentPrefix),l(a,d.toString(16)),!!a.write('">');case 4:return l(a,'<table hidden id="'),l(a,b.segmentPrefix),l(a,d.toString(16)),!!a.write('">'); -case 5:return l(a,'<table hidden><tbody id="'),l(a,b.segmentPrefix),l(a,d.toString(16)),!!a.write('">');case 6:return l(a,'<table hidden><tr id="'),l(a,b.segmentPrefix),l(a,d.toString(16)),!!a.write('">');case 7:return l(a,'<table hidden><colgroup id="'),l(a,b.segmentPrefix),l(a,d.toString(16)),!!a.write('">');default:throw Error("Unknown insertion mode. This is a bug in React.");}} -function Wa(a,b){switch(b.insertionMode){case 0:case 1:return!!a.write("</div>");case 2:return!!a.write("</svg>");case 3:return!!a.write("</math>");case 4:return!!a.write("</table>");case 5:return!!a.write("</tbody></table>");case 6:return!!a.write("</tr></table>");case 7:return!!a.write("</colgroup></table>");default:throw Error("Unknown insertion mode. This is a bug in React.");}}var Xa=/[<\u2028\u2029]/g; -function Ya(a){return JSON.stringify(a).replace(Xa,function(a){switch(a){case "<":return"\\u003c";case "\u2028":return"\\u2028";case "\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React");}})}var Za=/[&><\u2028\u2029]/g; -function K(a){return JSON.stringify(a).replace(Za,function(a){switch(a){case "&":return"\\u0026";case ">":return"\\u003e";case "<":return"\\u003c";case "\u2028":return"\\u2028";case "\u2029":return"\\u2029";default:throw Error("escapeJSObjectForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React");}})} -function $a(a,b,c){function d(a){a.flushed||(F(e,a.props,c),a.flushed=!0)}var e=[],f=b.charset,g=b.bases,h=b.preconnects,m=b.fontPreloads,k=b.precedences,p=b.usedStylePreloads,n=b.scripts,q=b.usedScriptPreloads,u=b.explicitStylePreloads,H=b.explicitScriptPreloads,B=b.headResources;f&&(I(e,f.props,"meta",c),f.flushed=!0,b.charset=null);g.forEach(function(a){I(e,a.props,"base",c);a.flushed=!0});g.clear();h.forEach(function(a){F(e,a.props,c);a.flushed=!0});h.clear();m.forEach(function(a){F(e,a.props, -c);a.flushed=!0});m.clear();k.forEach(function(a,b){a.size?(a.forEach(function(a){F(e,a.props,c);a.flushed=!0;a.inShell=!0;a.hint.flushed=!0}),a.clear()):e.push('<style data-precedence="',w(b),'"></style>')});p.forEach(d);p.clear();n.forEach(function(a){Pa(e,a.props,c);a.flushed=!0;a.hint.flushed=!0});n.clear();q.forEach(d);q.clear();u.forEach(d);u.clear();H.forEach(d);H.clear();B.forEach(function(a){switch(a.type){case "title":Oa(e,a.props,c);break;case "meta":I(e,a.props,"meta",c);break;case "link":F(e, -a.props,c)}a.flushed=!0});B.clear();f=!0;for(b=0;b<e.length-1;b++)l(a,e[b]);b<e.length&&(f=!!a.write(e[b]));return f} -function ab(a,b,c){function d(a){a.flushed||(F(e,a.props,c),a.flushed=!0)}var e=[],f=b.charset,g=b.preconnects,h=b.fontPreloads,m=b.usedStylePreloads,k=b.scripts,p=b.usedScriptPreloads,n=b.explicitStylePreloads,q=b.explicitScriptPreloads,u=b.headResources;f&&(I(e,f.props,"meta",c),f.flushed=!0,b.charset=null);g.forEach(function(a){F(e,a.props,c);a.flushed=!0});g.clear();h.forEach(function(a){F(e,a.props,c);a.flushed=!0});h.clear();m.forEach(d);m.clear();k.forEach(function(a){J(e,a.props,"script", -c);Ta(e,e,"script",a.props);a.flushed=!0;a.hint.flushed=!0});k.clear();p.forEach(d);p.clear();n.forEach(d);n.clear();q.forEach(d);q.clear();u.forEach(function(a){switch(a.type){case "title":Oa(e,a.props,c);break;case "meta":I(e,a.props,"meta",c);break;case "link":F(e,a.props,c)}a.flushed=!0});u.clear();f=!0;for(b=0;b<e.length-1;b++)l(a,e[b]);b<e.length&&(f=!!a.write(e[b]));return f} -function bb(a,b){l(a,"[");var c="[";b.forEach(function(b){if(!b.inShell)if(b.flushed)l(a,c),l(a,K(""+b.href)),l(a,"]"),c=",[";else{l(a,c);var d=b.precedence,f=b.props;l(a,K(""+b.href));d=""+d;l(a,",");l(a,K(d));for(var g in f)if(r.call(f,g)){var h=f[g];if(null!=h)switch(g){case "href":case "rel":case "precedence":case "data-precedence":break;case "children":case "dangerouslySetInnerHTML":throw Error("link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."); -default:a:{d=a;var m=g,k=m.toLowerCase();switch(typeof h){case "function":case "symbol":break a}switch(m){case "innerHTML":case "dangerouslySetInnerHTML":case "suppressContentEditableWarning":case "suppressHydrationWarning":case "style":break a;case "className":k="class";break;case "hidden":if(!1===h)break a;break;case "src":case "href":break;default:if(!ia(m))break a}if(!(2<m.length)||"o"!==m[0]&&"O"!==m[0]||"n"!==m[1]&&"N"!==m[1])h=""+h,l(d,","),l(d,K(k)),l(d,","),l(d,K(h))}}}l(a,"]");c=",[";b.flushed= -!0;b.hint.flushed=!0}});l(a,"]")} -var cb=Symbol.for("react.element"),db=Symbol.for("react.portal"),eb=Symbol.for("react.fragment"),fb=Symbol.for("react.strict_mode"),gb=Symbol.for("react.profiler"),hb=Symbol.for("react.provider"),ib=Symbol.for("react.context"),jb=Symbol.for("react.server_context"),kb=Symbol.for("react.forward_ref"),lb=Symbol.for("react.suspense"),mb=Symbol.for("react.suspense_list"),nb=Symbol.for("react.memo"),ob=Symbol.for("react.lazy"),pb=Symbol.for("react.scope"),qb=Symbol.for("react.debug_trace_mode"),rb=Symbol.for("react.offscreen"), -sb=Symbol.for("react.legacy_hidden"),tb=Symbol.for("react.cache"),ub=Symbol.for("react.default_value"),vb=Symbol.for("react.memo_cache_sentinel"),wb=Symbol.iterator; -function xb(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case eb:return"Fragment";case db:return"Portal";case gb:return"Profiler";case fb:return"StrictMode";case lb:return"Suspense";case mb:return"SuspenseList";case tb:return"Cache"}if("object"===typeof a)switch(a.$$typeof){case ib:return(a.displayName||"Context")+".Consumer";case hb:return(a._context.displayName||"Context")+".Provider";case kb:var b=a.render;a=a.displayName; -a||(a=b.displayName||b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case nb:return b=a.displayName||null,null!==b?b:xb(a.type)||"Memo";case ob:b=a._payload;a=a._init;try{return xb(a(b))}catch(c){break}case jb:return(a.displayName||a._globalName)+".Provider"}return null}var yb=ba.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,zb={};function Ab(a,b){a=a.contextTypes;if(!a)return zb;var c={},d;for(d in a)c[d]=b[d];return c}var L=null; -function Bb(a,b){if(a!==b){a.context._currentValue=a.parentValue;a=a.parent;var c=b.parent;if(null===a){if(null!==c)throw Error("The stacks must reach the root at the same time. This is a bug in React.");}else{if(null===c)throw Error("The stacks must reach the root at the same time. This is a bug in React.");Bb(a,c)}b.context._currentValue=b.value}}function Cb(a){a.context._currentValue=a.parentValue;a=a.parent;null!==a&&Cb(a)} -function Db(a){var b=a.parent;null!==b&&Db(b);a.context._currentValue=a.value}function Eb(a,b){a.context._currentValue=a.parentValue;a=a.parent;if(null===a)throw Error("The depth must equal at least at zero before reaching the root. This is a bug in React.");a.depth===b.depth?Bb(a,b):Eb(a,b)} -function Fb(a,b){var c=b.parent;if(null===c)throw Error("The depth must equal at least at zero before reaching the root. This is a bug in React.");a.depth===c.depth?Bb(a,c):Fb(a,c);b.context._currentValue=b.value}function Gb(a){var b=L;b!==a&&(null===b?Db(a):null===a?Cb(b):b.depth===a.depth?Bb(b,a):b.depth>a.depth?Eb(b,a):Fb(b,a),L=a)} -var Hb={isMounted:function(){return!1},enqueueSetState:function(a,b){a=a._reactInternals;null!==a.queue&&a.queue.push(b)},enqueueReplaceState:function(a,b){a=a._reactInternals;a.replace=!0;a.queue=[b]},enqueueForceUpdate:function(){}}; -function Ib(a,b,c,d){var e=void 0!==a.state?a.state:null;a.updater=Hb;a.props=c;a.state=e;var f={queue:[],replace:!1};a._reactInternals=f;var g=b.contextType;a.context="object"===typeof g&&null!==g?g._currentValue:d;g=b.getDerivedStateFromProps;"function"===typeof g&&(g=g(c,e),e=null===g||void 0===g?e:x({},e,g),a.state=e);if("function"!==typeof b.getDerivedStateFromProps&&"function"!==typeof a.getSnapshotBeforeUpdate&&("function"===typeof a.UNSAFE_componentWillMount||"function"===typeof a.componentWillMount))if(b= -a.state,"function"===typeof a.componentWillMount&&a.componentWillMount(),"function"===typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount(),b!==a.state&&Hb.enqueueReplaceState(a,a.state,null),null!==f.queue&&0<f.queue.length)if(b=f.queue,g=f.replace,f.queue=null,f.replace=!1,g&&1===b.length)a.state=b[0];else{f=g?b[0]:a.state;e=!0;for(g=g?1:0;g<b.length;g++){var h=b[g];h="function"===typeof h?h.call(a,f,c,d):h;null!=h&&(e?(e=!1,f=x({},f,h)):x(f,h))}a.state=f}else f.queue=null} -var Jb={id:1,overflow:""};function Kb(a,b,c){var d=a.id;a=a.overflow;var e=32-Lb(d)-1;d&=~(1<<e);c+=1;var f=32-Lb(b)+e;if(30<f){var g=e-e%5;f=(d&(1<<g)-1).toString(32);d>>=g;e-=g;return{id:1<<32-Lb(b)+e|c<<e|d,overflow:f+a}}return{id:1<<f|c<<e|d,overflow:a}}var Lb=Math.clz32?Math.clz32:Mb,Nb=Math.log,Ob=Math.LN2;function Mb(a){a>>>=0;return 0===a?32:31-(Nb(a)/Ob|0)|0}var Pb=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"); -function Qb(){}function Rb(a,b,c){c=a[c];void 0===c?a.push(b):c!==b&&(b.then(Qb,Qb),b=c);switch(b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;default:if("string"!==typeof b.status)switch(a=b,a.status="pending",a.then(function(a){if("pending"===b.status){var c=b;c.status="fulfilled";c.value=a}},function(a){if("pending"===b.status){var c=b;c.status="rejected";c.reason=a}}),b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;}Sb=b;throw Pb;}}var Sb=null; -function Tb(){if(null===Sb)throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue.");var a=Sb;Sb=null;return a}function Ub(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var Vb="function"===typeof Object.is?Object.is:Ub,M=null,Wb=null,Xb=null,N=null,O=!1,Yb=!1,Q=0,R=0,S=null,T=null,Zb=0; -function U(){if(null===M)throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");return M} -function $b(){if(0<Zb)throw Error("Rendered more hooks than during the previous render");return{memoizedState:null,queue:null,next:null}}function ac(){null===N?null===Xb?(O=!1,Xb=N=$b()):(O=!0,N=Xb):null===N.next?(O=!1,N=N.next=$b()):(O=!0,N=N.next);return N}function bc(a,b,c,d){for(;Yb;)Yb=!1,R=Q=0,Zb+=1,N=null,c=a(b,d);cc();return c}function dc(){var a=S;S=null;return a}function cc(){Wb=M=null;Yb=!1;Xb=null;Zb=0;N=T=null}function ec(a,b){return"function"===typeof b?b(a):b} -function fc(a,b,c){M=U();N=ac();if(O){var d=N.queue;b=d.dispatch;if(null!==T&&(c=T.get(d),void 0!==c)){T.delete(d);d=N.memoizedState;do d=a(d,c.action),c=c.next;while(null!==c);N.memoizedState=d;return[d,b]}return[N.memoizedState,b]}a=a===ec?"function"===typeof b?b():b:void 0!==c?c(b):b;N.memoizedState=a;a=N.queue={last:null,dispatch:null};a=a.dispatch=gc.bind(null,M,a);return[N.memoizedState,a]} -function hc(a,b){M=U();N=ac();b=void 0===b?null:b;if(null!==N){var c=N.memoizedState;if(null!==c&&null!==b){var d=c[1];a:if(null===d)d=!1;else{for(var e=0;e<d.length&&e<b.length;e++)if(!Vb(b[e],d[e])){d=!1;break a}d=!0}if(d)return c[0]}}a=a();N.memoizedState=[a,b];return a} -function gc(a,b,c){if(25<=Zb)throw Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");if(a===M)if(Yb=!0,a={action:c,next:null},null===T&&(T=new Map),c=T.get(b),void 0===c)T.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}}function ic(){throw Error("A function wrapped in useEvent can't be called during rendering.");}function jc(){throw Error("startTransition cannot be called during server rendering.");} -function kc(){throw Error("Cache cannot be refreshed during server rendering.");}function lc(){} -var nc={readContext:function(a){return a._currentValue},useContext:function(a){U();return a._currentValue},useMemo:hc,useReducer:fc,useRef:function(a){M=U();N=ac();var b=N.memoizedState;return null===b?(a={current:a},N.memoizedState=a):b},useState:function(a){return fc(ec,a)},useInsertionEffect:lc,useLayoutEffect:function(){},useCallback:function(a,b){return hc(function(){return a},b)},useImperativeHandle:lc,useEffect:lc,useDebugValue:lc,useDeferredValue:function(a){U();return a},useTransition:function(){U(); -return[!1,jc]},useId:function(){var a=Wb.treeContext;var b=a.overflow;a=a.id;a=(a&~(1<<32-Lb(a)-1)).toString(32)+b;var c=mc;if(null===c)throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component.");b=Q++;a=":"+c.idPrefix+"R"+a;0<b&&(a+="H"+b.toString(32));return a+":"},useMutableSource:function(a,b){U();return b(a._source)},useSyncExternalStore:function(a,b,c){if(void 0===c)throw Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."); -return c()},useCacheRefresh:function(){return kc},useEvent:function(){return ic},useMemoCache:function(a){for(var b=Array(a),c=0;c<a;c++)b[c]=vb;return b},use:function(a){if(null!==a&&"object"===typeof a){if("function"===typeof a.then){var b=R;R+=1;null===S&&(S=[]);return Rb(S,a,b)}if(a.$$typeof===ib||a.$$typeof===jb)return a._currentValue}throw Error("An unsupported type was passed to use(): "+String(a));}},mc=null,oc={getCacheSignal:function(){throw Error("Not implemented.");},getCacheForType:function(){throw Error("Not implemented."); -}},pc=yb.ReactCurrentDispatcher,qc=yb.ReactCurrentCache;function rc(a){console.error(a);return null}function W(){} -function sc(a,b,c,d,e,f,g,h,m){var k=[],p=new Set,n={preloadsMap:new Map,stylesMap:new Map,scriptsMap:new Map,headsMap:new Map,charset:null,bases:new Set,preconnects:new Set,fontPreloads:new Set,precedences:new Map,usedStylePreloads:new Set,scripts:new Set,usedScriptPreloads:new Set,explicitStylePreloads:new Set,explicitScriptPreloads:new Set,headResources:new Set,structuredMetaKeys:new Map,boundaryResources:null};b={destination:null,responseState:b,progressiveChunkSize:void 0===d?12800:d,status:0, -fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,resources:n,completedRootSegment:null,abortableTasks:p,pingedTasks:k,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],preamble:[],postamble:[],onError:void 0===e?rc:e,onAllReady:void 0===f?W:f,onShellReady:void 0===g?W:g,onShellError:void 0===h?W:h,onFatalError:void 0===m?W:m};c=tc(b,0,null,c,!1,!1);c.parentFlushed=!0;a=uc(b,null,a,null,c,p,zb,null,Jb);k.push(a);return b} -function uc(a,b,c,d,e,f,g,h,m){a.allPendingTasks++;null===d?a.pendingRootTasks++:d.pendingTasks++;var k={node:c,ping:function(){var b=a.pingedTasks;b.push(k);1===b.length&&vc(a)},blockedBoundary:d,blockedSegment:e,abortSet:f,legacyContext:g,context:h,treeContext:m,thenableState:b};f.add(k);return k}function tc(a,b,c,d,e,f){return{status:0,id:-1,index:b,parentFlushed:!1,chunks:[],children:[],formatContext:d,boundary:c,lastPushedText:e,textEmbedded:f}} -function X(a,b){a=a.onError(b);if(null!=a&&"string"!==typeof a)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof a+'" instead');return a}function Y(a,b){var c=a.onShellError;c(b);c=a.onFatalError;c(b);null!==a.destination?(a.status=2,da(a.destination,b)):(a.status=1,a.fatalError=b)} -function wc(a,b,c,d){var e=c.render(),f=d.childContextTypes;if(null!==f&&void 0!==f){var g=b.legacyContext;if("function"!==typeof c.getChildContext)d=g;else{c=c.getChildContext();for(var h in c)if(!(h in f))throw Error((xb(d)||"Unknown")+'.getChildContext(): key "'+h+'" is not defined in childContextTypes.');d=x({},g,c)}b.legacyContext=d;Z(a,b,null,e);b.legacyContext=g}else Z(a,b,null,e)} -function xc(a,b){if(a&&a.defaultProps){b=x({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b} -function yc(a,b,c,d,e,f){if("function"===typeof d)if(d.prototype&&d.prototype.isReactComponent)c=Ab(d,b.legacyContext),f=d.contextType,f=new d(e,"object"===typeof f&&null!==f?f._currentValue:c),Ib(f,d,e,c),wc(a,b,f,d);else{f=Ab(d,b.legacyContext);M={};Wb=b;R=Q=0;S=c;c=d(e,f);c=bc(d,e,c,f);var g=0!==Q;if("object"===typeof c&&null!==c&&"function"===typeof c.render&&void 0===c.$$typeof)Ib(c,d,e,f),wc(a,b,c,d);else if(g){e=b.treeContext;b.treeContext=Kb(e,1,0);try{Z(a,b,null,c)}finally{b.treeContext= -e}}else Z(a,b,null,c)}else if("string"===typeof d)c=b.blockedSegment,f=Sa(c.chunks,a.preamble,d,e,a.responseState,c.formatContext,c.lastPushedText),c.lastPushedText=!1,g=c.formatContext,c.formatContext=Ja(g,d,e),zc(a,b,f),c.formatContext=g,Ta(c.chunks,a.postamble,d),c.lastPushedText=!1;else{switch(d){case sb:case qb:case fb:case gb:case eb:Z(a,b,null,e.children);return;case rb:"hidden"!==e.mode&&Z(a,b,null,e.children);return;case mb:Z(a,b,null,e.children);return;case pb:throw Error("ReactDOMServer does not yet support scope components."); -case lb:a:{d=b.blockedBoundary;c=b.blockedSegment;f=e.fallback;e=e.children;g=new Set;var h={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:g,errorDigest:null,resources:new Set},m=tc(a,c.chunks.length,h,c.formatContext,!1,!1);c.children.push(m);c.lastPushedText=!1;var k=tc(a,0,null,c.formatContext,!1,!1);k.parentFlushed=!0;b.blockedBoundary=h;b.blockedSegment=k;a.resources.boundaryResources=h.resources;try{if(zc(a, -b,e),k.lastPushedText&&k.textEmbedded&&k.chunks.push("\x3c!-- --\x3e"),k.status=1,0===h.pendingTasks&&(null!==a.completedRootSegment||0<a.pendingRootTasks)&&Da(a.resources,h.resources),Ac(h,k),0===h.pendingTasks)break a}catch(p){k.status=4,h.forceClientRender=!0,h.errorDigest=X(a,p)}finally{a.resources.boundaryResources=d?d.resources:null,b.blockedBoundary=d,b.blockedSegment=c}b=uc(a,null,f,d,m,g,b.legacyContext,b.context,b.treeContext);a.pingedTasks.push(b)}return}if("object"===typeof d&&null!== -d)switch(d.$$typeof){case kb:d=d.render;M={};Wb=b;R=Q=0;S=c;c=d(e,f);e=bc(d,e,c,f);if(0!==Q){d=b.treeContext;b.treeContext=Kb(d,1,0);try{Z(a,b,null,e)}finally{b.treeContext=d}}else Z(a,b,null,e);return;case nb:d=d.type;e=xc(d,e);yc(a,b,c,d,e,f);return;case hb:c=e.children;d=d._context;e=e.value;f=d._currentValue;d._currentValue=e;g=L;L=e={parent:g,depth:null===g?0:g.depth+1,context:d,parentValue:f,value:e};b.context=e;Z(a,b,null,c);a=L;if(null===a)throw Error("Tried to pop a Context at the root of the app. This is a bug in React."); -e=a.parentValue;a.context._currentValue=e===ub?a.context._defaultValue:e;a=L=a.parent;b.context=a;return;case ib:e=e.children;e=e(d._currentValue);Z(a,b,null,e);return;case ob:f=d._init;d=f(d._payload);e=xc(d,e);yc(a,b,c,d,e,void 0);return}throw Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: "+((null==d?d:typeof d)+"."));}} -function Z(a,b,c,d){b.node=d;if("object"===typeof d&&null!==d){switch(d.$$typeof){case cb:yc(a,b,c,d.type,d.props,d.ref);return;case db:throw Error("Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render.");case ob:c=d._init;d=c(d._payload);Z(a,b,null,d);return}if(ra(d)){Bc(a,b,d);return}null===d||"object"!==typeof d?c=null:(c=wb&&d[wb]||d["@@iterator"],c="function"===typeof c?c:null);if(c&&(c=c.call(d))){d=c.next();if(!d.done){var e= -[];do e.push(d.value),d=c.next();while(!d.done);Bc(a,b,e)}return}a=Object.prototype.toString.call(d);throw Error("Objects are not valid as a React child (found: "+("[object Object]"===a?"object with keys {"+Object.keys(d).join(", ")+"}":a)+"). If you meant to render a collection of children, use an array instead.");}"string"===typeof d?(c=b.blockedSegment,c.lastPushedText=Ka(b.blockedSegment.chunks,d,a.responseState,c.lastPushedText)):"number"===typeof d&&(c=b.blockedSegment,c.lastPushedText=Ka(b.blockedSegment.chunks, -""+d,a.responseState,c.lastPushedText))}function Bc(a,b,c){for(var d=c.length,e=0;e<d;e++){var f=b.treeContext;b.treeContext=Kb(f,d,e);try{zc(a,b,c[e])}finally{b.treeContext=f}}} -function zc(a,b,c){var d=b.blockedSegment.formatContext,e=b.legacyContext,f=b.context;try{return Z(a,b,null,c)}catch(k){if(cc(),c=k===Pb?Tb():k,"object"===typeof c&&null!==c&&"function"===typeof c.then){var g=dc(),h=b.blockedSegment,m=tc(a,h.chunks.length,null,h.formatContext,h.lastPushedText,!0);h.children.push(m);h.lastPushedText=!1;a=uc(a,g,b.node,b.blockedBoundary,m,b.abortSet,b.legacyContext,b.context,b.treeContext).ping;c.then(a,a);b.blockedSegment.formatContext=d;b.legacyContext=e;b.context= -f;Gb(f)}else throw b.blockedSegment.formatContext=d,b.legacyContext=e,b.context=f,Gb(f),c;}}function Cc(a){var b=a.blockedBoundary;a=a.blockedSegment;a.status=3;Dc(this,b,a)} -function Ec(a,b,c){var d=a.blockedBoundary;a.blockedSegment.status=3;null===d?(b.allPendingTasks--,1!==b.status&&2!==b.status&&(X(b,c),Y(b,c))):(d.pendingTasks--,d.forceClientRender||(d.forceClientRender=!0,d.errorDigest=b.onError(c),d.parentFlushed&&b.clientRenderedBoundaries.push(d)),d.fallbackAbortableTasks.forEach(function(a){return Ec(a,b,c)}),d.fallbackAbortableTasks.clear(),b.allPendingTasks--,0===b.allPendingTasks&&(a=b.onAllReady,a()))} -function Ac(a,b){if(0===b.chunks.length&&1===b.children.length&&null===b.children[0].boundary){var c=b.children[0];c.id=b.id;c.parentFlushed=!0;1===c.status&&Ac(a,c)}else a.completedSegments.push(b)} -function Dc(a,b,c){if(null===b){if(c.parentFlushed){if(null!==a.completedRootSegment)throw Error("There can only be one root segment. This is a bug in React.");a.completedRootSegment=c}a.pendingRootTasks--;0===a.pendingRootTasks&&(a.onShellError=W,b=a.onShellReady,b())}else b.pendingTasks--,b.forceClientRender||(0===b.pendingTasks?(c.parentFlushed&&1===c.status&&Ac(b,c),(null!==a.completedRootSegment||0<a.pendingRootTasks)&&Da(a.resources,b.resources),b.parentFlushed&&a.completedBoundaries.push(b), -b.fallbackAbortableTasks.forEach(Cc,a),b.fallbackAbortableTasks.clear()):c.parentFlushed&&1===c.status&&(Ac(b,c),1===b.completedSegments.length&&b.parentFlushed&&a.partialBoundaries.push(b)));a.allPendingTasks--;0===a.allPendingTasks&&(a=a.onAllReady,a())} -function vc(a){if(2!==a.status){var b=L,c=pc.current;pc.current=nc;var d=qc.current;qc.current=oc;var e=a.resources;sa.push(y);y=e;e=Ea.current;Ea.current=va;var f=mc;mc=a.responseState;try{var g=a.pingedTasks,h;for(h=0;h<g.length;h++){var m=g[h];var k=a,p=m.blockedBoundary;k.resources.boundaryResources=p?p.resources:null;var n=m.blockedSegment;if(0===n.status){Gb(m.context);try{var q=m.thenableState;m.thenableState=null;Z(k,m,q,m.node);n.lastPushedText&&n.textEmbedded&&n.chunks.push("\x3c!-- --\x3e"); -m.abortSet.delete(m);n.status=1;Dc(k,m.blockedBoundary,n)}catch(aa){cc();var u=aa===Pb?Tb():aa;if("object"===typeof u&&null!==u&&"function"===typeof u.then){var H=m.ping;u.then(H,H);m.thenableState=dc()}else{m.abortSet.delete(m);n.status=4;var B=k,E=m.blockedBoundary,V=u,P=X(B,V);null===E?Y(B,V):(E.pendingTasks--,E.forceClientRender||(E.forceClientRender=!0,E.errorDigest=P,E.parentFlushed&&B.clientRenderedBoundaries.push(E)));B.allPendingTasks--;if(0===B.allPendingTasks){var Mc=B.onAllReady;Mc()}}}finally{k.resources.boundaryResources= -null}}}g.splice(0,h);null!==a.destination&&Fc(a,a.destination)}catch(aa){X(a,aa),Y(a,aa)}finally{mc=f,pc.current=c,qc.current=d,y=sa.pop(),Ea.current=e,c===nc&&Gb(b)}}} -function Gc(a,b,c){c.parentFlushed=!0;switch(c.status){case 0:var d=c.id=a.nextSegmentId++;c.lastPushedText=!1;c.textEmbedded=!1;a=a.responseState;l(b,'<template id="');l(b,a.placeholderPrefix);a=d.toString(16);l(b,a);return!!b.write('"></template>');case 1:c.status=2;var e=!0;d=c.chunks;var f=0;c=c.children;for(var g=0;g<c.length;g++){for(e=c[g];f<e.index;f++)l(b,d[f]);e=Hc(a,b,e)}for(;f<d.length-1;f++)l(b,d[f]);f<d.length&&(e=!!b.write(d[f]));return e;default:throw Error("Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React."); -}} -function Hc(a,b,c){var d=c.boundary;if(null===d)return Gc(a,b,c);d.parentFlushed=!0;if(d.forceClientRender)d=d.errorDigest,b.write("\x3c!--$!--\x3e"),l(b,"<template"),d&&(l(b,' data-dgst="'),l(b,w(d)),l(b,'"')),b.write("></template>"),Gc(a,b,c);else if(0<d.pendingTasks){d.rootSegmentID=a.nextSegmentId++;0<d.completedSegments.length&&a.partialBoundaries.push(d);var e=a.responseState;var f=e.nextSuspenseID++;e=e.boundaryPrefix+f.toString(16);d=d.id=e;Ua(b,a.responseState,d);Gc(a,b,c)}else if(d.byteSize>a.progressiveChunkSize)d.rootSegmentID= -a.nextSegmentId++,a.completedBoundaries.push(d),Ua(b,a.responseState,d.id),Gc(a,b,c);else{Ca(a.resources,d.resources);b.write("\x3c!--$--\x3e");c=d.completedSegments;if(1!==c.length)throw Error("A previously unvisited boundary must have exactly one root segment. This is a bug in React.");Hc(a,b,c[0])}return!!b.write("\x3c!--/$--\x3e")}function Ic(a,b,c){Va(b,a.responseState,c.formatContext,c.id);Hc(a,b,c);return Wa(b,c.formatContext)} -function Jc(a,b,c){a.resources.boundaryResources=c.resources;for(var d=c.completedSegments,e=0;e<d.length;e++)Kc(a,b,c,d[e]);d.length=0;a=a.responseState;d=c.id;e=c.rootSegmentID;c=c.resources;var f;a:{for(f=c.values();;){var g=f.next().value;if(!g)break;if(!g.inShell){f=!0;break a}}f=!1}l(b,a.startInlineScript);f?a.sentCompleteBoundaryFunction?a.sentStyleInsertionFunction?l(b,'$RR("'):(a.sentStyleInsertionFunction=!0,l(b,'$RM=new Map;\n$RR=function(p,q,v){function r(l){this.s=l}for(var t=$RC,u=$RM,m=new Map,n=document,g,e,f=n.querySelectorAll("link[data-precedence],style[data-precedence]"),d=0;e=f[d++];)m.set(e.dataset.precedence,g=e);e=0;f=[];for(var c,h,b,a;c=v[e++];){var k=0;h=c[k++];if(b=u.get(h))"l"!==b.s&&f.push(b);else{a=n.createElement("link");a.href=h;a.rel="stylesheet";for(a.dataset.precedence=d=c[k++];b=c[k++];)a.setAttribute(b,c[k++]);b=a._p=new Promise(function(l,w){a.onload=l;a.onerror=w});b.then(r.bind(b,\n"l"),r.bind(b,"e"));u.set(h,b);f.push(b);c=m.get(d)||g;c===g&&(g=a);m.set(d,a);c?c.parentNode.insertBefore(a,c.nextSibling):(d=n.head,d.insertBefore(a,d.firstChild))}}Promise.all(f).then(t.bind(null,p,q,""),t.bind(null,p,q,"Resource failed to load"))};;$RR("')): -(a.sentCompleteBoundaryFunction=!0,a.sentStyleInsertionFunction=!0,l(b,'$RC=function(b,c,e){c=document.getElementById(c);c.parentNode.removeChild(c);var a=document.getElementById(b);if(a){b=a.previousSibling;if(e)b.data="$!",a.setAttribute("data-dgst",e);else{e=b.parentNode;a=b.nextSibling;var f=0;do{if(a&&8===a.nodeType){var d=a.data;if("/$"===d)if(0===f)break;else f--;else"$"!==d&&"$?"!==d&&"$!"!==d||f++}d=a.nextSibling;e.removeChild(a);a=d}while(a);for(;c.firstChild;)e.insertBefore(c.firstChild,a);b.data="$"}b._reactRetry&&b._reactRetry()}};;$RM=new Map;\n$RR=function(p,q,v){function r(l){this.s=l}for(var t=$RC,u=$RM,m=new Map,n=document,g,e,f=n.querySelectorAll("link[data-precedence],style[data-precedence]"),d=0;e=f[d++];)m.set(e.dataset.precedence,g=e);e=0;f=[];for(var c,h,b,a;c=v[e++];){var k=0;h=c[k++];if(b=u.get(h))"l"!==b.s&&f.push(b);else{a=n.createElement("link");a.href=h;a.rel="stylesheet";for(a.dataset.precedence=d=c[k++];b=c[k++];)a.setAttribute(b,c[k++]);b=a._p=new Promise(function(l,w){a.onload=l;a.onerror=w});b.then(r.bind(b,\n"l"),r.bind(b,"e"));u.set(h,b);f.push(b);c=m.get(d)||g;c===g&&(g=a);m.set(d,a);c?c.parentNode.insertBefore(a,c.nextSibling):(d=n.head,d.insertBefore(a,d.firstChild))}}Promise.all(f).then(t.bind(null,p,q,""),t.bind(null,p,q,"Resource failed to load"))};;$RR("')): -a.sentCompleteBoundaryFunction?l(b,'$RC("'):(a.sentCompleteBoundaryFunction=!0,l(b,'$RC=function(b,c,e){c=document.getElementById(c);c.parentNode.removeChild(c);var a=document.getElementById(b);if(a){b=a.previousSibling;if(e)b.data="$!",a.setAttribute("data-dgst",e);else{e=b.parentNode;a=b.nextSibling;var f=0;do{if(a&&8===a.nodeType){var d=a.data;if("/$"===d)if(0===f)break;else f--;else"$"!==d&&"$?"!==d&&"$!"!==d||f++}d=a.nextSibling;e.removeChild(a);a=d}while(a);for(;c.firstChild;)e.insertBefore(c.firstChild,a);b.data="$"}b._reactRetry&&b._reactRetry()}};;$RC("')); -if(null===d)throw Error("An ID must have been assigned before we can complete the boundary.");e=e.toString(16);l(b,d);l(b,'","');l(b,a.segmentPrefix);l(b,e);f?(l(b,'",'),bb(b,c)):l(b,'"');return!!b.write(")\x3c/script>")} -function Kc(a,b,c,d){if(2===d.status)return!0;var e=d.id;if(-1===e){if(-1===(d.id=c.rootSegmentID))throw Error("A root segment ID must have been assigned by now. This is a bug in React.");return Ic(a,b,d)}Ic(a,b,d);a=a.responseState;l(b,a.startInlineScript);a.sentCompleteSegmentFunction?l(b,'$RS("'):(a.sentCompleteSegmentFunction=!0,l(b,'$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};;$RS("')); -l(b,a.segmentPrefix);e=e.toString(16);l(b,e);l(b,'","');l(b,a.placeholderPrefix);l(b,e);return!!b.write('")\x3c/script>')} -function Fc(a,b){try{var c,d=a.completedRootSegment;if(null!==d)if(0===a.pendingRootTasks){var e=a.preamble;for(c=0;c<e.length;c++)l(b,e[c]);$a(b,a.resources,a.responseState);Hc(a,b,d);a.completedRootSegment=null;var f=a.responseState.bootstrapChunks;for(d=0;d<f.length-1;d++)l(b,f[d]);d<f.length&&b.write(f[d])}else return;else ab(b,a.resources,a.responseState);var g=a.clientRenderedBoundaries;for(c=0;c<g.length;c++){var h=g[c];f=b;var m=a.responseState,k=h.id,p=h.errorDigest,n=h.errorMessage,q=h.errorComponentStack; -l(f,m.startInlineScript);m.sentClientRenderFunction?l(f,'$RX("'):(m.sentClientRenderFunction=!0,l(f,'$RX=function(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};;$RX("'));if(null===k)throw Error("An ID must have been assigned before we can complete the boundary.");l(f,k);l(f,'"');if(p||n||q)l(f,","),l(f,Ya(p||""));if(n||q)l(f,","),l(f,Ya(n||""));q&&(l(f,","),l(f,Ya(q)));if(!f.write(")\x3c/script>")){a.destination= -null;c++;g.splice(0,c);return}}g.splice(0,c);var u=a.completedBoundaries;for(c=0;c<u.length;c++)if(!Jc(a,b,u[c])){a.destination=null;c++;u.splice(0,c);return}u.splice(0,c);var H=a.partialBoundaries;for(c=0;c<H.length;c++){var B=H[c];a:{g=a;h=b;g.resources.boundaryResources=B.resources;var E=B.completedSegments;for(m=0;m<E.length;m++)if(!Kc(g,h,B,E[m])){m++;E.splice(0,m);var V=!1;break a}E.splice(0,m);V=!0}if(!V){a.destination=null;c++;H.splice(0,c);return}}H.splice(0,c);var P=a.completedBoundaries; -for(c=0;c<P.length;c++)if(!Jc(a,b,P[c])){a.destination=null;c++;P.splice(0,c);return}P.splice(0,c)}finally{if(0===a.allPendingTasks&&0===a.pingedTasks.length&&0===a.clientRenderedBoundaries.length&&0===a.completedBoundaries.length){a=a.postamble;for(c=0;c<a.length;c++)l(b,a[c]);b.end()}}} -function Lc(a,b){try{var c=a.abortableTasks;if(0<c.size){var d=void 0===b?Error("The render was aborted by the server without a reason."):b;c.forEach(function(b){return Ec(b,a,d)});c.clear()}null!==a.destination&&Fc(a,a.destination)}catch(e){X(a,e),Y(a,e)}}exports.renderToNodeStream=function(){throw Error("ReactDOMServer.renderToNodeStream(): The Node Stream API is not available in Bun. Use ReactDOMServer.renderToReadableStream() instead.");}; -exports.renderToReadableStream=function(a,b){return new Promise(function(c,d){var e,f,g=new Promise(function(a,b){f=a;e=b}),h=sc(a,Ha(b?b.identifierPrefix:void 0,b?b.nonce:void 0,b?b.bootstrapScriptContent:void 0,b?b.bootstrapScripts:void 0,b?b.bootstrapModules:void 0,b?b.unstable_externalRuntimeSrc:void 0),Ia(b?b.namespaceURI:void 0),b?b.progressiveChunkSize:void 0,b?b.onError:void 0,f,function(){var a=new ReadableStream({type:"direct",pull:function(a){if(1===h.status)h.status=2,da(a,h.fatalError); -else if(2!==h.status&&null===h.destination){h.destination=a;try{Fc(h,a)}catch(q){X(h,q),Y(h,q)}}},cancel:function(){Lc(h)}},{highWaterMark:2048});a.allReady=g;c(a)},function(a){g.catch(function(){});d(a)},e);if(b&&b.signal){var m=b.signal;if(m.aborted)Lc(h,m.reason);else{var k=function(){Lc(h,m.reason);m.removeEventListener("abort",k)};m.addEventListener("abort",k)}}vc(h)})}; -exports.renderToStaticNodeStream=function(){throw Error("ReactDOMServer.renderToStaticNodeStream(): The Node Stream API is not available in Bun. Use ReactDOMServer.renderToReadableStream() instead.");};exports.version="18.2.0"; +"use strict"; +var ba = require("react"), + ca = require("react-dom"); +function l(a, b) { + 0 !== b.length && a.write(b); +} +function da(a, b) { + "function" === typeof a.error ? a.error(b) : a.close(); +} +var r = Object.prototype.hasOwnProperty, + ea = + /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, + fa = {}, + ha = {}; +function ia(a) { + if (r.call(ha, a)) return !0; + if (r.call(fa, a)) return !1; + if (ea.test(a)) return (ha[a] = !0); + fa[a] = !0; + return !1; +} +function t(a, b, c, d, e, f, g) { + this.acceptsBooleans = 2 === b || 3 === b || 4 === b; + this.attributeName = d; + this.attributeNamespace = e; + this.mustUseProperty = c; + this.propertyName = a; + this.type = b; + this.sanitizeURL = f; + this.removeEmptyString = g; +} +var v = {}, + ja = + "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split( + " " + ); +ja.push("innerText", "textContent"); +ja.forEach(function (a) { + v[a] = new t(a, 0, !1, a, null, !1, !1); +}); +[ + ["acceptCharset", "accept-charset"], + ["className", "class"], + ["htmlFor", "for"], + ["httpEquiv", "http-equiv"], +].forEach(function (a) { + var b = a[0]; + v[b] = new t(b, 1, !1, a[1], null, !1, !1); +}); +["contentEditable", "draggable", "spellCheck", "value"].forEach(function (a) { + v[a] = new t(a, 2, !1, a.toLowerCase(), null, !1, !1); +}); +[ + "autoReverse", + "externalResourcesRequired", + "focusable", + "preserveAlpha", +].forEach(function (a) { + v[a] = new t(a, 2, !1, a, null, !1, !1); +}); +"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope" + .split(" ") + .forEach(function (a) { + v[a] = new t(a, 3, !1, a.toLowerCase(), null, !1, !1); + }); +["checked", "multiple", "muted", "selected"].forEach(function (a) { + v[a] = new t(a, 3, !0, a, null, !1, !1); +}); +["capture", "download"].forEach(function (a) { + v[a] = new t(a, 4, !1, a, null, !1, !1); +}); +["cols", "rows", "size", "span"].forEach(function (a) { + v[a] = new t(a, 6, !1, a, null, !1, !1); +}); +["rowSpan", "start"].forEach(function (a) { + v[a] = new t(a, 5, !1, a.toLowerCase(), null, !1, !1); +}); +var ka = /[\-:]([a-z])/g; +function la(a) { + return a[1].toUpperCase(); +} +"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height" + .split(" ") + .forEach(function (a) { + var b = a.replace(ka, la); + v[b] = new t(b, 1, !1, a, null, !1, !1); + }); +"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type" + .split(" ") + .forEach(function (a) { + var b = a.replace(ka, la); + v[b] = new t(b, 1, !1, a, "http://www.w3.org/1999/xlink", !1, !1); + }); +["xml:base", "xml:lang", "xml:space"].forEach(function (a) { + var b = a.replace(ka, la); + v[b] = new t(b, 1, !1, a, "http://www.w3.org/XML/1998/namespace", !1, !1); +}); +["tabIndex", "crossOrigin"].forEach(function (a) { + v[a] = new t(a, 1, !1, a.toLowerCase(), null, !1, !1); +}); +v.xlinkHref = new t( + "xlinkHref", + 1, + !1, + "xlink:href", + "http://www.w3.org/1999/xlink", + !0, + !1 +); +["src", "href", "action", "formAction"].forEach(function (a) { + v[a] = new t(a, 1, !1, a.toLowerCase(), null, !0, !0); +}); +var ma = { + animationIterationCount: !0, + aspectRatio: !0, + borderImageOutset: !0, + borderImageSlice: !0, + borderImageWidth: !0, + boxFlex: !0, + boxFlexGroup: !0, + boxOrdinalGroup: !0, + columnCount: !0, + columns: !0, + flex: !0, + flexGrow: !0, + flexPositive: !0, + flexShrink: !0, + flexNegative: !0, + flexOrder: !0, + gridArea: !0, + gridRow: !0, + gridRowEnd: !0, + gridRowSpan: !0, + gridRowStart: !0, + gridColumn: !0, + gridColumnEnd: !0, + gridColumnSpan: !0, + gridColumnStart: !0, + fontWeight: !0, + lineClamp: !0, + lineHeight: !0, + opacity: !0, + order: !0, + orphans: !0, + tabSize: !0, + widows: !0, + zIndex: !0, + zoom: !0, + fillOpacity: !0, + floodOpacity: !0, + stopOpacity: !0, + strokeDasharray: !0, + strokeDashoffset: !0, + strokeMiterlimit: !0, + strokeOpacity: !0, + strokeWidth: !0, + }, + na = ["Webkit", "ms", "Moz", "O"]; +Object.keys(ma).forEach(function (a) { + na.forEach(function (b) { + b = b + a.charAt(0).toUpperCase() + a.substring(1); + ma[b] = ma[a]; + }); +}); +var oa = /["'&<>]/; +function w(a) { + if ("boolean" === typeof a || "number" === typeof a) return "" + a; + a = "" + a; + var b = oa.exec(a); + if (b) { + var c = "", + d, + e = 0; + for (d = b.index; d < a.length; d++) { + switch (a.charCodeAt(d)) { + case 34: + b = """; + break; + case 38: + b = "&"; + break; + case 39: + b = "'"; + break; + case 60: + b = "<"; + break; + case 62: + b = ">"; + break; + default: + continue; + } + e !== d && (c += a.substring(e, d)); + e = d + 1; + c += b; + } + a = e !== d ? c + a.substring(e, d) : c; + } + return a; +} +var pa = /([A-Z])/g, + qa = /^ms-/, + ra = Array.isArray, + x = Object.assign, + y = null, + sa = [], + va = { preload: ta, preinit: ua }; +function ta(a, b) { + if (y) { + var c = y; + if ("string" === typeof a && a && "object" === typeof b && null !== b) { + var d = b.as, + e = c.preloadsMap.get(a); + e || + (e = z(c, a, d, { + href: a, + rel: "preload", + as: d, + crossOrigin: "font" === d ? "" : b.crossOrigin, + integrity: b.integrity, + })); + switch (d) { + case "font": + c.fontPreloads.add(e); + break; + case "style": + c.explicitStylePreloads.add(e); + break; + case "script": + c.explicitScriptPreloads.add(e); + } + } + } +} +function ua(a, b) { + if (y) { + var c = y; + if ("string" === typeof a && a && "object" === typeof b && null !== b) + switch (b.as) { + case "style": + var d = c.stylesMap.get(a); + d || + ((d = b.precedence || "default"), + (d = wa(c, a, d, { + rel: "stylesheet", + href: a, + "data-precedence": d, + crossOrigin: b.crossOrigin, + }))); + d.set.add(d); + c.explicitStylePreloads.add(d.hint); + break; + case "script": + (d = c.scriptsMap.get(a)), + d || + ((d = xa(c, a, { + src: a, + async: !0, + crossOrigin: b.crossOrigin, + integrity: b.integrity, + })), + c.scripts.add(d)); + } + } +} +function ya(a, b) { + return { + rel: "preload", + as: "style", + href: a, + crossOrigin: b.crossOrigin, + integrity: b.integrity, + media: b.media, + hrefLang: b.hrefLang, + referrerPolicy: b.referrerPolicy, + }; +} +function za(a, b) { + return { + rel: "preload", + as: "script", + href: a, + crossOrigin: b.crossOrigin, + integrity: b.integrity, + referrerPolicy: b.referrerPolicy, + }; +} +function z(a, b, c, d) { + c = { type: "preload", as: c, href: b, flushed: !1, props: d }; + a.preloadsMap.set(b, c); + return c; +} +function wa(a, b, c, d) { + var e = a.stylesMap, + f = a.preloadsMap, + g = a.precedences, + h = g.get(c); + h || ((h = new Set()), g.set(c, h)); + (f = f.get(b)) + ? ((a = f.props), + null == d.crossOrigin && (d.crossOrigin = a.crossOrigin), + null == d.referrerPolicy && (d.referrerPolicy = a.referrerPolicy), + null == d.title && (d.title = a.title)) + : ((f = ya(b, d)), + (f = z(a, b, "style", f)), + a.explicitStylePreloads.add(f)); + c = { + type: "style", + href: b, + precedence: c, + flushed: !1, + inShell: !1, + props: d, + hint: f, + set: h, + }; + e.set(b, c); + return c; +} +function xa(a, b, c) { + var d = a.scriptsMap, + e = a.preloadsMap.get(b); + e + ? ((a = e.props), + null == c.crossOrigin && (c.crossOrigin = a.crossOrigin), + null == c.referrerPolicy && (c.referrerPolicy = a.referrerPolicy), + null == c.integrity && (c.integrity = a.integrity)) + : ((e = za(b, c)), + (e = z(a, b, "script", e)), + a.explicitScriptPreloads.add(e)); + c = { type: "script", src: b, flushed: !1, props: c, hint: e }; + d.set(b, c); + return c; +} +function Aa(a, b) { + if (!y) + throw Error( + '"currentResources" was expected to exist. This is a bug in React.' + ); + var c = y; + switch (a) { + case "title": + var d = b.children; + Array.isArray(d) && 1 === d.length && (d = d[0]); + if ("string" === typeof d || "number" === typeof d) { + var e = "title::" + d; + a = c.headsMap.get(e); + a || + ((b = x({}, b)), + (b.children = d), + (a = { type: "title", props: b, flushed: !1 }), + c.headsMap.set(e, a), + c.headResources.add(a)); + } + return !0; + case "meta": + if ("string" === typeof b.charSet) e = "charSet"; + else if ("string" === typeof b.content) + if (((a = "::" + b.content), "string" === typeof b.httpEquiv)) + e = "httpEquiv::" + b.httpEquiv + a; + else if ("string" === typeof b.name) e = "name::" + b.name + a; + else if ("string" === typeof b.itemProp) + e = "itemProp::" + b.itemProp + a; + else if ("string" === typeof b.property) { + var f = b.property; + e = "property::" + f + a; + d = f; + a = f.split(":").slice(0, -1).join(":"); + (a = c.structuredMetaKeys.get(a)) && (e = a.key + "::child::" + e); + } + e && + !c.headsMap.has(e) && + ((b = { type: "meta", key: e, props: x({}, b), flushed: !1 }), + c.headsMap.set(e, b), + "charSet" === e + ? (c.charset = b) + : (d && c.structuredMetaKeys.set(d, b), c.headResources.add(b))); + return !0; + case "base": + return ( + (e = b.target), + (d = b.href), + (e = + "base" + + ("string" === typeof d ? '[href="' + d + '"]' : ":not([href])") + + ("string" === typeof e ? '[target="' + e + '"]' : ":not([target])")), + c.headsMap.has(e) || + ((b = { type: "base", props: x({}, b), flushed: !1 }), + c.headsMap.set(e, b), + c.bases.add(b)), + !0 + ); + } + return !1; +} +function Ba(a) { + if (!y) + throw Error( + '"currentResources" was expected to exist. This is a bug in React.' + ); + var b = y, + c = a.rel, + d = a.href; + if (!d || "string" !== typeof d || !c || "string" !== typeof c) return !1; + switch (c) { + case "stylesheet": + var e = a.onLoad, + f = a.onError; + c = a.precedence; + var g = a.disabled; + if ("string" !== typeof c || e || f || null != g) + return ( + (c = b.preloadsMap.get(d)), + c || ((c = z(b, d, "style", ya(d, a))), b.usedStylePreloads.add(c)), + !1 + ); + e = b.stylesMap.get(d); + e || + ((a = x({}, a)), + (a.href = d), + (a.rel = "stylesheet"), + (a["data-precedence"] = c), + delete a.precedence, + (e = wa(y, d, c, a)), + b.usedStylePreloads.add(e.hint)); + b.boundaryResources ? b.boundaryResources.add(e) : e.set.add(e); + return !0; + case "preload": + switch (((e = a.as), e)) { + case "script": + case "style": + case "font": + c = b.preloadsMap.get(d); + if (!c) + switch ( + ((a = x({}, a)), + (a.href = d), + (a.rel = "preload"), + (a.as = e), + "font" === e && (a.crossOrigin = ""), + (c = z(b, d, e, a)), + e) + ) { + case "script": + b.explicitScriptPreloads.add(c); + break; + case "style": + b.explicitStylePreloads.add(c); + break; + case "font": + b.fontPreloads.add(c); + } + return !0; + } + } + if (a.onLoad || a.onError) return !0; + d = + "rel:" + + c + + "::href:" + + d + + "::sizes:" + + ("string" === typeof a.sizes ? a.sizes : "") + + "::media:" + + ("string" === typeof a.media ? a.media : ""); + e = b.headsMap.get(d); + if (!e) + switch ( + ((e = { type: "link", props: x({}, a), flushed: !1 }), + b.headsMap.set(d, e), + c) + ) { + case "preconnect": + case "dns-prefetch": + b.preconnects.add(e); + break; + default: + b.headResources.add(e); + } + return !0; +} +function Ca(a, b) { + var c = a.boundaryResources; + c && + (b.forEach(function (a) { + return c.add(a); + }), + b.clear()); +} +function Da(a, b) { + b.forEach(function (a) { + return a.set.add(a); + }); + b.clear(); +} +var Ea = ca.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Dispatcher, + Fa = /(<\/|<)(s)(cript)/gi; +function Ga(a, b, c, d) { + return "" + b + ("s" === c ? "\\u0073" : "\\u0053") + d; +} +function Ha(a, b, c, d, e) { + a = void 0 === a ? "" : a; + b = void 0 === b ? "<script>" : '<script nonce="' + w(b) + '">'; + var f = []; + void 0 !== c && f.push(b, ("" + c).replace(Fa, Ga), "\x3c/script>"); + if (void 0 !== d) + for (c = 0; c < d.length; c++) { + var g = d[c], + h = "string" === typeof g ? void 0 : g.integrity; + f.push('<script src="', w("string" === typeof g ? g : g.src)); + h && f.push('" integrity="', w(h)); + f.push('" async="">\x3c/script>'); + } + if (void 0 !== e) + for (d = 0; d < e.length; d++) + (c = e[d]), + (g = "string" === typeof c ? void 0 : c.integrity), + f.push( + '<script type="module" src="', + w("string" === typeof c ? c : c.src) + ), + g && f.push('" integrity="', w(g)), + f.push('" async="">\x3c/script>'); + return { + bootstrapChunks: f, + startInlineScript: b, + placeholderPrefix: a + "P:", + segmentPrefix: a + "S:", + boundaryPrefix: a + "B:", + idPrefix: a, + nextSuspenseID: 0, + sentCompleteSegmentFunction: !1, + sentCompleteBoundaryFunction: !1, + sentClientRenderFunction: !1, + sentStyleInsertionFunction: !1, + }; +} +function A(a, b, c) { + return { insertionMode: a, selectedValue: b, noscriptTagInScope: c }; +} +function Ia(a) { + return A( + "http://www.w3.org/2000/svg" === a + ? 2 + : "http://www.w3.org/1998/Math/MathML" === a + ? 3 + : 0, + null, + !1 + ); +} +function Ja(a, b, c) { + switch (b) { + case "noscript": + return A(1, null, !0); + case "select": + return A( + 1, + null != c.value ? c.value : c.defaultValue, + a.noscriptTagInScope + ); + case "svg": + return A(2, null, a.noscriptTagInScope); + case "math": + return A(3, null, a.noscriptTagInScope); + case "foreignObject": + return A(1, null, a.noscriptTagInScope); + case "table": + return A(4, null, a.noscriptTagInScope); + case "thead": + case "tbody": + case "tfoot": + return A(5, null, a.noscriptTagInScope); + case "colgroup": + return A(7, null, a.noscriptTagInScope); + case "tr": + return A(6, null, a.noscriptTagInScope); + } + return 4 <= a.insertionMode || 0 === a.insertionMode + ? A(1, null, a.noscriptTagInScope) + : a; +} +function Ka(a, b, c, d) { + if ("" === b) return d; + d && a.push("\x3c!-- --\x3e"); + a.push(w(b)); + return !0; +} +var La = new Map(); +function Ma(a, b, c) { + if ("object" !== typeof c) + throw Error( + "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX." + ); + b = !0; + for (var d in c) + if (r.call(c, d)) { + var e = c[d]; + if (null != e && "boolean" !== typeof e && "" !== e) { + if (0 === d.indexOf("--")) { + var f = w(d); + e = w(("" + e).trim()); + } else { + f = d; + var g = La.get(f); + void 0 !== g + ? (f = g) + : ((g = w(f.replace(pa, "-$1").toLowerCase().replace(qa, "-ms-"))), + La.set(f, g), + (f = g)); + e = + "number" === typeof e + ? 0 === e || r.call(ma, d) + ? "" + e + : e + "px" + : w(("" + e).trim()); + } + b ? ((b = !1), a.push(' style="', f, ":", e)) : a.push(";", f, ":", e); + } + } + b || a.push('"'); +} +function C(a, b, c, d) { + switch (c) { + case "style": + Ma(a, b, d); + return; + case "defaultValue": + case "defaultChecked": + case "innerHTML": + case "suppressContentEditableWarning": + case "suppressHydrationWarning": + return; + } + if ( + !(2 < c.length) || + ("o" !== c[0] && "O" !== c[0]) || + ("n" !== c[1] && "N" !== c[1]) + ) + if (((b = v.hasOwnProperty(c) ? v[c] : null), null !== b)) { + switch (typeof d) { + case "function": + case "symbol": + return; + case "boolean": + if (!b.acceptsBooleans) return; + } + c = b.attributeName; + switch (b.type) { + case 3: + d && a.push(" ", c, '=""'); + break; + case 4: + !0 === d + ? a.push(" ", c, '=""') + : !1 !== d && a.push(" ", c, '="', w(d), '"'); + break; + case 5: + isNaN(d) || a.push(" ", c, '="', w(d), '"'); + break; + case 6: + !isNaN(d) && 1 <= d && a.push(" ", c, '="', w(d), '"'); + break; + default: + b.sanitizeURL && (d = "" + d), a.push(" ", c, '="', w(d), '"'); + } + } else if (ia(c)) { + switch (typeof d) { + case "function": + case "symbol": + return; + case "boolean": + if ( + ((b = c.toLowerCase().slice(0, 5)), "data-" !== b && "aria-" !== b) + ) + return; + } + a.push(" ", c, '="', w(d), '"'); + } +} +function D(a, b, c) { + if (null != b) { + if (null != c) + throw Error( + "Can only set one of `children` or `props.dangerouslySetInnerHTML`." + ); + if ("object" !== typeof b || !("__html" in b)) + throw Error( + "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information." + ); + b = b.__html; + null !== b && void 0 !== b && a.push("" + b); + } +} +function Na(a) { + var b = ""; + ba.Children.forEach(a, function (a) { + null != a && (b += a); + }); + return b; +} +function F(a, b, c) { + var d = "stylesheet" === b.rel; + a.push(G("link")); + for (var e in b) + if (r.call(b, e)) { + var f = b[e]; + if (null != f) + switch (e) { + case "children": + case "dangerouslySetInnerHTML": + throw Error( + "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + ); + case "precedence": + if (d) continue; + default: + C(a, c, e, f); + } + } + a.push("/>"); + return null; +} +function I(a, b, c, d) { + a.push(G(c)); + for (var e in b) + if (r.call(b, e)) { + var f = b[e]; + if (null != f) + switch (e) { + case "children": + case "dangerouslySetInnerHTML": + throw Error( + c + + " is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + ); + default: + C(a, d, e, f); + } + } + a.push("/>"); + return null; +} +function Oa(a, b, c) { + a.push(G("title")); + var d = null, + e; + for (e in b) + if (r.call(b, e)) { + var f = b[e]; + if (null != f) + switch (e) { + case "children": + d = f; + break; + case "dangerouslySetInnerHTML": + throw Error( + "`dangerouslySetInnerHTML` does not make sense on <title>." + ); + default: + C(a, c, e, f); + } + } + a.push(">"); + b = Array.isArray(d) && 2 > d.length ? d[0] || null : d; + ("string" !== typeof b && "number" !== typeof b) || a.push(w(b)); + a.push("</", "title", ">"); + return null; +} +function Pa(a, b, c) { + a.push(G("script")); + var d = null, + e = null, + f; + for (f in b) + if (r.call(b, f)) { + var g = b[f]; + if (null != g) + switch (f) { + case "children": + d = g; + break; + case "dangerouslySetInnerHTML": + e = g; + break; + default: + C(a, c, f, g); + } + } + a.push(">"); + D(a, e, d); + "string" === typeof d && a.push(w(d)); + a.push("</", "script", ">"); + return null; +} +function J(a, b, c, d) { + a.push(G(c)); + var e = (c = null), + f; + for (f in b) + if (r.call(b, f)) { + var g = b[f]; + if (null != g) + switch (f) { + case "children": + c = g; + break; + case "dangerouslySetInnerHTML": + e = g; + break; + default: + C(a, d, f, g); + } + } + a.push(">"); + D(a, e, c); + return "string" === typeof c ? (a.push(w(c)), null) : c; +} +var Qa = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/, + Ra = new Map(); +function G(a) { + var b = Ra.get(a); + if (void 0 === b) { + if (!Qa.test(a)) throw Error("Invalid tag: " + a); + b = "<" + a; + Ra.set(a, b); + } + return b; +} +function Sa(a, b, c, d, e, f, g) { + switch (c) { + case "select": + a.push(G("select")); + var h = (g = null), + m; + for (m in d) + if (r.call(d, m)) { + var k = d[m]; + if (null != k) + switch (m) { + case "children": + g = k; + break; + case "dangerouslySetInnerHTML": + h = k; + break; + case "defaultValue": + case "value": + break; + default: + C(a, e, m, k); + } + } + a.push(">"); + D(a, h, g); + return g; + case "option": + g = f.selectedValue; + a.push(G("option")); + var p = (m = k = null), + n = null; + for (h in d) + if (r.call(d, h)) { + var q = d[h]; + if (null != q) + switch (h) { + case "children": + k = q; + break; + case "selected": + p = q; + break; + case "dangerouslySetInnerHTML": + n = q; + break; + case "value": + m = q; + default: + C(a, e, h, q); + } + } + if (null != g) + if (((d = null !== m ? "" + m : Na(k)), ra(g))) + for (e = 0; e < g.length; e++) { + if ("" + g[e] === d) { + a.push(' selected=""'); + break; + } + } + else "" + g === d && a.push(' selected=""'); + else p && a.push(' selected=""'); + a.push(">"); + D(a, n, k); + return k; + case "textarea": + a.push(G("textarea")); + k = h = g = null; + for (n in d) + if (r.call(d, n) && ((m = d[n]), null != m)) + switch (n) { + case "children": + k = m; + break; + case "value": + g = m; + break; + case "defaultValue": + h = m; + break; + case "dangerouslySetInnerHTML": + throw Error( + "`dangerouslySetInnerHTML` does not make sense on <textarea>." + ); + default: + C(a, e, n, m); + } + null === g && null !== h && (g = h); + a.push(">"); + if (null != k) { + if (null != g) + throw Error( + "If you supply `defaultValue` on a <textarea>, do not pass children." + ); + if (ra(k) && 1 < k.length) + throw Error("<textarea> can only have at most one child."); + g = "" + k; + } + "string" === typeof g && "\n" === g[0] && a.push("\n"); + null !== g && a.push(w("" + g)); + return null; + case "input": + a.push(G("input")); + m = n = h = g = null; + for (k in d) + if (r.call(d, k) && ((p = d[k]), null != p)) + switch (k) { + case "children": + case "dangerouslySetInnerHTML": + throw Error( + "input is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + ); + case "defaultChecked": + m = p; + break; + case "defaultValue": + h = p; + break; + case "checked": + n = p; + break; + case "value": + g = p; + break; + default: + C(a, e, k, p); + } + null !== n ? C(a, e, "checked", n) : null !== m && C(a, e, "checked", m); + null !== g ? C(a, e, "value", g) : null !== h && C(a, e, "value", h); + a.push("/>"); + return null; + case "menuitem": + a.push(G("menuitem")); + for (var u in d) + if (r.call(d, u) && ((g = d[u]), null != g)) + switch (u) { + case "children": + case "dangerouslySetInnerHTML": + throw Error( + "menuitems cannot have `children` nor `dangerouslySetInnerHTML`." + ); + default: + C(a, e, u, g); + } + a.push(">"); + return null; + case "title": + return ( + (a = + 2 !== f.insertionMode && !f.noscriptTagInScope && Aa("title", d) + ? null + : Oa(a, d, e)), + a + ); + case "link": + return ( + !f.noscriptTagInScope && Ba(d) + ? (g && a.push("\x3c!-- --\x3e"), (a = null)) + : (a = F(a, d, e)), + a + ); + case "script": + if ((h = !f.noscriptTagInScope)) { + if (!y) + throw Error( + '"currentResources" was expected to exist. This is a bug in React.' + ); + h = y; + k = d.src; + n = d.onLoad; + m = d.onError; + k && "string" === typeof k + ? d.async + ? (n || m + ? ((n = h.preloadsMap.get(k)), + n || + ((n = z(h, k, "script", za(k, d))), + h.usedScriptPreloads.add(n))) + : ((n = h.scriptsMap.get(k)), + n || + ((n = x({}, d)), + (n.src = k), + (n = xa(h, k, n)), + h.scripts.add(n))), + (h = !0)) + : (h = !1) + : (h = !1); + } + h ? (g && a.push("\x3c!-- --\x3e"), (a = null)) : (a = Pa(a, d, e)); + return a; + case "meta": + return ( + !f.noscriptTagInScope && Aa("meta", d) + ? (g && a.push("\x3c!-- --\x3e"), (a = null)) + : (a = I(a, d, "meta", e)), + a + ); + case "base": + return ( + !f.noscriptTagInScope && Aa("base", d) + ? (g && a.push("\x3c!-- --\x3e"), (a = null)) + : (a = I(a, d, "base", e)), + a + ); + case "listing": + case "pre": + a.push(G(c)); + h = g = null; + for (p in d) + if (r.call(d, p) && ((k = d[p]), null != k)) + switch (p) { + case "children": + g = k; + break; + case "dangerouslySetInnerHTML": + h = k; + break; + default: + C(a, e, p, k); + } + a.push(">"); + if (null != h) { + if (null != g) + throw Error( + "Can only set one of `children` or `props.dangerouslySetInnerHTML`." + ); + if ("object" !== typeof h || !("__html" in h)) + throw Error( + "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information." + ); + d = h.__html; + null !== d && + void 0 !== d && + ("string" === typeof d && 0 < d.length && "\n" === d[0] + ? a.push("\n", d) + : a.push("" + d)); + } + "string" === typeof g && "\n" === g[0] && a.push("\n"); + return g; + case "area": + case "br": + case "col": + case "embed": + case "hr": + case "img": + case "keygen": + case "param": + case "source": + case "track": + case "wbr": + return I(a, d, c, e); + case "annotation-xml": + case "color-profile": + case "font-face": + case "font-face-src": + case "font-face-uri": + case "font-face-format": + case "font-face-name": + case "missing-glyph": + return J(a, d, c, e); + case "head": + return J(b, d, c, e); + case "html": + return 0 === f.insertionMode && b.push("<!DOCTYPE html>"), J(b, d, c, e); + default: + if (-1 === c.indexOf("-") && "string" !== typeof d.is) + return J(a, d, c, e); + a.push(G(c)); + h = g = null; + for (q in d) + if ( + r.call(d, q) && + ((k = d[q]), + null != k && + "function" !== typeof k && + "object" !== typeof k && + !1 !== k) + ) + switch ( + (!0 === k && (k = ""), "className" === q && (q = "class"), q) + ) { + case "children": + g = k; + break; + case "dangerouslySetInnerHTML": + h = k; + break; + case "style": + Ma(a, e, k); + break; + case "suppressContentEditableWarning": + case "suppressHydrationWarning": + break; + default: + ia(q) && + "function" !== typeof k && + "symbol" !== typeof k && + a.push(" ", q, '="', w(k), '"'); + } + a.push(">"); + D(a, h, g); + return g; + } +} +function Ta(a, b, c) { + switch (c) { + case "title": + case "script": + case "area": + case "base": + case "br": + case "col": + case "embed": + case "hr": + case "img": + case "input": + case "keygen": + case "link": + case "meta": + case "param": + case "source": + case "track": + case "wbr": + return; + case "body": + b.unshift("</", c, ">"); + return; + case "html": + b.push("</", c, ">"); + return; + } + a.push("</", c, ">"); +} +function Ua(a, b, c) { + l(a, '\x3c!--$?--\x3e<template id="'); + if (null === c) + throw Error( + "An ID must have been assigned before we can complete the boundary." + ); + l(a, c); + return !!a.write('"></template>'); +} +function Va(a, b, c, d) { + switch (c.insertionMode) { + case 0: + case 1: + return ( + l(a, '<div hidden id="'), + l(a, b.segmentPrefix), + l(a, d.toString(16)), + !!a.write('">') + ); + case 2: + return ( + l(a, '<svg aria-hidden="true" style="display:none" id="'), + l(a, b.segmentPrefix), + l(a, d.toString(16)), + !!a.write('">') + ); + case 3: + return ( + l(a, '<math aria-hidden="true" style="display:none" id="'), + l(a, b.segmentPrefix), + l(a, d.toString(16)), + !!a.write('">') + ); + case 4: + return ( + l(a, '<table hidden id="'), + l(a, b.segmentPrefix), + l(a, d.toString(16)), + !!a.write('">') + ); + case 5: + return ( + l(a, '<table hidden><tbody id="'), + l(a, b.segmentPrefix), + l(a, d.toString(16)), + !!a.write('">') + ); + case 6: + return ( + l(a, '<table hidden><tr id="'), + l(a, b.segmentPrefix), + l(a, d.toString(16)), + !!a.write('">') + ); + case 7: + return ( + l(a, '<table hidden><colgroup id="'), + l(a, b.segmentPrefix), + l(a, d.toString(16)), + !!a.write('">') + ); + default: + throw Error("Unknown insertion mode. This is a bug in React."); + } +} +function Wa(a, b) { + switch (b.insertionMode) { + case 0: + case 1: + return !!a.write("</div>"); + case 2: + return !!a.write("</svg>"); + case 3: + return !!a.write("</math>"); + case 4: + return !!a.write("</table>"); + case 5: + return !!a.write("</tbody></table>"); + case 6: + return !!a.write("</tr></table>"); + case 7: + return !!a.write("</colgroup></table>"); + default: + throw Error("Unknown insertion mode. This is a bug in React."); + } +} +var Xa = /[<\u2028\u2029]/g; +function Ya(a) { + return JSON.stringify(a).replace(Xa, function (a) { + switch (a) { + case "<": + return "\\u003c"; + case "\u2028": + return "\\u2028"; + case "\u2029": + return "\\u2029"; + default: + throw Error( + "escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React" + ); + } + }); +} +var Za = /[&><\u2028\u2029]/g; +function K(a) { + return JSON.stringify(a).replace(Za, function (a) { + switch (a) { + case "&": + return "\\u0026"; + case ">": + return "\\u003e"; + case "<": + return "\\u003c"; + case "\u2028": + return "\\u2028"; + case "\u2029": + return "\\u2029"; + default: + throw Error( + "escapeJSObjectForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React" + ); + } + }); +} +function $a(a, b, c) { + function d(a) { + a.flushed || (F(e, a.props, c), (a.flushed = !0)); + } + var e = [], + f = b.charset, + g = b.bases, + h = b.preconnects, + m = b.fontPreloads, + k = b.precedences, + p = b.usedStylePreloads, + n = b.scripts, + q = b.usedScriptPreloads, + u = b.explicitStylePreloads, + H = b.explicitScriptPreloads, + B = b.headResources; + f && (I(e, f.props, "meta", c), (f.flushed = !0), (b.charset = null)); + g.forEach(function (a) { + I(e, a.props, "base", c); + a.flushed = !0; + }); + g.clear(); + h.forEach(function (a) { + F(e, a.props, c); + a.flushed = !0; + }); + h.clear(); + m.forEach(function (a) { + F(e, a.props, c); + a.flushed = !0; + }); + m.clear(); + k.forEach(function (a, b) { + a.size + ? (a.forEach(function (a) { + F(e, a.props, c); + a.flushed = !0; + a.inShell = !0; + a.hint.flushed = !0; + }), + a.clear()) + : e.push('<style data-precedence="', w(b), '"></style>'); + }); + p.forEach(d); + p.clear(); + n.forEach(function (a) { + Pa(e, a.props, c); + a.flushed = !0; + a.hint.flushed = !0; + }); + n.clear(); + q.forEach(d); + q.clear(); + u.forEach(d); + u.clear(); + H.forEach(d); + H.clear(); + B.forEach(function (a) { + switch (a.type) { + case "title": + Oa(e, a.props, c); + break; + case "meta": + I(e, a.props, "meta", c); + break; + case "link": + F(e, a.props, c); + } + a.flushed = !0; + }); + B.clear(); + f = !0; + for (b = 0; b < e.length - 1; b++) l(a, e[b]); + b < e.length && (f = !!a.write(e[b])); + return f; +} +function ab(a, b, c) { + function d(a) { + a.flushed || (F(e, a.props, c), (a.flushed = !0)); + } + var e = [], + f = b.charset, + g = b.preconnects, + h = b.fontPreloads, + m = b.usedStylePreloads, + k = b.scripts, + p = b.usedScriptPreloads, + n = b.explicitStylePreloads, + q = b.explicitScriptPreloads, + u = b.headResources; + f && (I(e, f.props, "meta", c), (f.flushed = !0), (b.charset = null)); + g.forEach(function (a) { + F(e, a.props, c); + a.flushed = !0; + }); + g.clear(); + h.forEach(function (a) { + F(e, a.props, c); + a.flushed = !0; + }); + h.clear(); + m.forEach(d); + m.clear(); + k.forEach(function (a) { + J(e, a.props, "script", c); + Ta(e, e, "script", a.props); + a.flushed = !0; + a.hint.flushed = !0; + }); + k.clear(); + p.forEach(d); + p.clear(); + n.forEach(d); + n.clear(); + q.forEach(d); + q.clear(); + u.forEach(function (a) { + switch (a.type) { + case "title": + Oa(e, a.props, c); + break; + case "meta": + I(e, a.props, "meta", c); + break; + case "link": + F(e, a.props, c); + } + a.flushed = !0; + }); + u.clear(); + f = !0; + for (b = 0; b < e.length - 1; b++) l(a, e[b]); + b < e.length && (f = !!a.write(e[b])); + return f; +} +function bb(a, b) { + l(a, "["); + var c = "["; + b.forEach(function (b) { + if (!b.inShell) + if (b.flushed) l(a, c), l(a, K("" + b.href)), l(a, "]"), (c = ",["); + else { + l(a, c); + var d = b.precedence, + f = b.props; + l(a, K("" + b.href)); + d = "" + d; + l(a, ","); + l(a, K(d)); + for (var g in f) + if (r.call(f, g)) { + var h = f[g]; + if (null != h) + switch (g) { + case "href": + case "rel": + case "precedence": + case "data-precedence": + break; + case "children": + case "dangerouslySetInnerHTML": + throw Error( + "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + ); + default: + a: { + d = a; + var m = g, + k = m.toLowerCase(); + switch (typeof h) { + case "function": + case "symbol": + break a; + } + switch (m) { + case "innerHTML": + case "dangerouslySetInnerHTML": + case "suppressContentEditableWarning": + case "suppressHydrationWarning": + case "style": + break a; + case "className": + k = "class"; + break; + case "hidden": + if (!1 === h) break a; + break; + case "src": + case "href": + break; + default: + if (!ia(m)) break a; + } + if ( + !(2 < m.length) || + ("o" !== m[0] && "O" !== m[0]) || + ("n" !== m[1] && "N" !== m[1]) + ) + (h = "" + h), + l(d, ","), + l(d, K(k)), + l(d, ","), + l(d, K(h)); + } + } + } + l(a, "]"); + c = ",["; + b.flushed = !0; + b.hint.flushed = !0; + } + }); + l(a, "]"); +} +var cb = Symbol.for("react.element"), + db = Symbol.for("react.portal"), + eb = Symbol.for("react.fragment"), + fb = Symbol.for("react.strict_mode"), + gb = Symbol.for("react.profiler"), + hb = Symbol.for("react.provider"), + ib = Symbol.for("react.context"), + jb = Symbol.for("react.server_context"), + kb = Symbol.for("react.forward_ref"), + lb = Symbol.for("react.suspense"), + mb = Symbol.for("react.suspense_list"), + nb = Symbol.for("react.memo"), + ob = Symbol.for("react.lazy"), + pb = Symbol.for("react.scope"), + qb = Symbol.for("react.debug_trace_mode"), + rb = Symbol.for("react.offscreen"), + sb = Symbol.for("react.legacy_hidden"), + tb = Symbol.for("react.cache"), + ub = Symbol.for("react.default_value"), + vb = Symbol.for("react.memo_cache_sentinel"), + wb = Symbol.iterator; +function xb(a) { + if (null == a) return null; + if ("function" === typeof a) return a.displayName || a.name || null; + if ("string" === typeof a) return a; + switch (a) { + case eb: + return "Fragment"; + case db: + return "Portal"; + case gb: + return "Profiler"; + case fb: + return "StrictMode"; + case lb: + return "Suspense"; + case mb: + return "SuspenseList"; + case tb: + return "Cache"; + } + if ("object" === typeof a) + switch (a.$$typeof) { + case ib: + return (a.displayName || "Context") + ".Consumer"; + case hb: + return (a._context.displayName || "Context") + ".Provider"; + case kb: + var b = a.render; + a = a.displayName; + a || + ((a = b.displayName || b.name || ""), + (a = "" !== a ? "ForwardRef(" + a + ")" : "ForwardRef")); + return a; + case nb: + return ( + (b = a.displayName || null), null !== b ? b : xb(a.type) || "Memo" + ); + case ob: + b = a._payload; + a = a._init; + try { + return xb(a(b)); + } catch (c) { + break; + } + case jb: + return (a.displayName || a._globalName) + ".Provider"; + } + return null; +} +var yb = ba.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, + zb = {}; +function Ab(a, b) { + a = a.contextTypes; + if (!a) return zb; + var c = {}, + d; + for (d in a) c[d] = b[d]; + return c; +} +var L = null; +function Bb(a, b) { + if (a !== b) { + a.context._currentValue = a.parentValue; + a = a.parent; + var c = b.parent; + if (null === a) { + if (null !== c) + throw Error( + "The stacks must reach the root at the same time. This is a bug in React." + ); + } else { + if (null === c) + throw Error( + "The stacks must reach the root at the same time. This is a bug in React." + ); + Bb(a, c); + } + b.context._currentValue = b.value; + } +} +function Cb(a) { + a.context._currentValue = a.parentValue; + a = a.parent; + null !== a && Cb(a); +} +function Db(a) { + var b = a.parent; + null !== b && Db(b); + a.context._currentValue = a.value; +} +function Eb(a, b) { + a.context._currentValue = a.parentValue; + a = a.parent; + if (null === a) + throw Error( + "The depth must equal at least at zero before reaching the root. This is a bug in React." + ); + a.depth === b.depth ? Bb(a, b) : Eb(a, b); +} +function Fb(a, b) { + var c = b.parent; + if (null === c) + throw Error( + "The depth must equal at least at zero before reaching the root. This is a bug in React." + ); + a.depth === c.depth ? Bb(a, c) : Fb(a, c); + b.context._currentValue = b.value; +} +function Gb(a) { + var b = L; + b !== a && + (null === b + ? Db(a) + : null === a + ? Cb(b) + : b.depth === a.depth + ? Bb(b, a) + : b.depth > a.depth + ? Eb(b, a) + : Fb(b, a), + (L = a)); +} +var Hb = { + isMounted: function () { + return !1; + }, + enqueueSetState: function (a, b) { + a = a._reactInternals; + null !== a.queue && a.queue.push(b); + }, + enqueueReplaceState: function (a, b) { + a = a._reactInternals; + a.replace = !0; + a.queue = [b]; + }, + enqueueForceUpdate: function () {}, +}; +function Ib(a, b, c, d) { + var e = void 0 !== a.state ? a.state : null; + a.updater = Hb; + a.props = c; + a.state = e; + var f = { queue: [], replace: !1 }; + a._reactInternals = f; + var g = b.contextType; + a.context = "object" === typeof g && null !== g ? g._currentValue : d; + g = b.getDerivedStateFromProps; + "function" === typeof g && + ((g = g(c, e)), + (e = null === g || void 0 === g ? e : x({}, e, g)), + (a.state = e)); + if ( + "function" !== typeof b.getDerivedStateFromProps && + "function" !== typeof a.getSnapshotBeforeUpdate && + ("function" === typeof a.UNSAFE_componentWillMount || + "function" === typeof a.componentWillMount) + ) + if ( + ((b = a.state), + "function" === typeof a.componentWillMount && a.componentWillMount(), + "function" === typeof a.UNSAFE_componentWillMount && + a.UNSAFE_componentWillMount(), + b !== a.state && Hb.enqueueReplaceState(a, a.state, null), + null !== f.queue && 0 < f.queue.length) + ) + if ( + ((b = f.queue), + (g = f.replace), + (f.queue = null), + (f.replace = !1), + g && 1 === b.length) + ) + a.state = b[0]; + else { + f = g ? b[0] : a.state; + e = !0; + for (g = g ? 1 : 0; g < b.length; g++) { + var h = b[g]; + h = "function" === typeof h ? h.call(a, f, c, d) : h; + null != h && (e ? ((e = !1), (f = x({}, f, h))) : x(f, h)); + } + a.state = f; + } + else f.queue = null; +} +var Jb = { id: 1, overflow: "" }; +function Kb(a, b, c) { + var d = a.id; + a = a.overflow; + var e = 32 - Lb(d) - 1; + d &= ~(1 << e); + c += 1; + var f = 32 - Lb(b) + e; + if (30 < f) { + var g = e - (e % 5); + f = (d & ((1 << g) - 1)).toString(32); + d >>= g; + e -= g; + return { id: (1 << (32 - Lb(b) + e)) | (c << e) | d, overflow: f + a }; + } + return { id: (1 << f) | (c << e) | d, overflow: a }; +} +var Lb = Math.clz32 ? Math.clz32 : Mb, + Nb = Math.log, + Ob = Math.LN2; +function Mb(a) { + a >>>= 0; + return 0 === a ? 32 : (31 - ((Nb(a) / Ob) | 0)) | 0; +} +var Pb = Error( + "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`" +); +function Qb() {} +function Rb(a, b, c) { + c = a[c]; + void 0 === c ? a.push(b) : c !== b && (b.then(Qb, Qb), (b = c)); + switch (b.status) { + case "fulfilled": + return b.value; + case "rejected": + throw b.reason; + default: + if ("string" !== typeof b.status) + switch ( + ((a = b), + (a.status = "pending"), + a.then( + function (a) { + if ("pending" === b.status) { + var c = b; + c.status = "fulfilled"; + c.value = a; + } + }, + function (a) { + if ("pending" === b.status) { + var c = b; + c.status = "rejected"; + c.reason = a; + } + } + ), + b.status) + ) { + case "fulfilled": + return b.value; + case "rejected": + throw b.reason; + } + Sb = b; + throw Pb; + } +} +var Sb = null; +function Tb() { + if (null === Sb) + throw Error( + "Expected a suspended thenable. This is a bug in React. Please file an issue." + ); + var a = Sb; + Sb = null; + return a; +} +function Ub(a, b) { + return (a === b && (0 !== a || 1 / a === 1 / b)) || (a !== a && b !== b); +} +var Vb = "function" === typeof Object.is ? Object.is : Ub, + M = null, + Wb = null, + Xb = null, + N = null, + O = !1, + Yb = !1, + Q = 0, + R = 0, + S = null, + T = null, + Zb = 0; +function U() { + if (null === M) + throw Error( + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." + ); + return M; +} +function $b() { + if (0 < Zb) + throw Error("Rendered more hooks than during the previous render"); + return { memoizedState: null, queue: null, next: null }; +} +function ac() { + null === N + ? null === Xb + ? ((O = !1), (Xb = N = $b())) + : ((O = !0), (N = Xb)) + : null === N.next + ? ((O = !1), (N = N.next = $b())) + : ((O = !0), (N = N.next)); + return N; +} +function bc(a, b, c, d) { + for (; Yb; ) (Yb = !1), (R = Q = 0), (Zb += 1), (N = null), (c = a(b, d)); + cc(); + return c; +} +function dc() { + var a = S; + S = null; + return a; +} +function cc() { + Wb = M = null; + Yb = !1; + Xb = null; + Zb = 0; + N = T = null; +} +function ec(a, b) { + return "function" === typeof b ? b(a) : b; +} +function fc(a, b, c) { + M = U(); + N = ac(); + if (O) { + var d = N.queue; + b = d.dispatch; + if (null !== T && ((c = T.get(d)), void 0 !== c)) { + T.delete(d); + d = N.memoizedState; + do (d = a(d, c.action)), (c = c.next); + while (null !== c); + N.memoizedState = d; + return [d, b]; + } + return [N.memoizedState, b]; + } + a = a === ec ? ("function" === typeof b ? b() : b) : void 0 !== c ? c(b) : b; + N.memoizedState = a; + a = N.queue = { last: null, dispatch: null }; + a = a.dispatch = gc.bind(null, M, a); + return [N.memoizedState, a]; +} +function hc(a, b) { + M = U(); + N = ac(); + b = void 0 === b ? null : b; + if (null !== N) { + var c = N.memoizedState; + if (null !== c && null !== b) { + var d = c[1]; + a: if (null === d) d = !1; + else { + for (var e = 0; e < d.length && e < b.length; e++) + if (!Vb(b[e], d[e])) { + d = !1; + break a; + } + d = !0; + } + if (d) return c[0]; + } + } + a = a(); + N.memoizedState = [a, b]; + return a; +} +function gc(a, b, c) { + if (25 <= Zb) + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); + if (a === M) + if ( + ((Yb = !0), + (a = { action: c, next: null }), + null === T && (T = new Map()), + (c = T.get(b)), + void 0 === c) + ) + T.set(b, a); + else { + for (b = c; null !== b.next; ) b = b.next; + b.next = a; + } +} +function ic() { + throw Error( + "A function wrapped in useEvent can't be called during rendering." + ); +} +function jc() { + throw Error("startTransition cannot be called during server rendering."); +} +function kc() { + throw Error("Cache cannot be refreshed during server rendering."); +} +function lc() {} +var nc = { + readContext: function (a) { + return a._currentValue; + }, + useContext: function (a) { + U(); + return a._currentValue; + }, + useMemo: hc, + useReducer: fc, + useRef: function (a) { + M = U(); + N = ac(); + var b = N.memoizedState; + return null === b ? ((a = { current: a }), (N.memoizedState = a)) : b; + }, + useState: function (a) { + return fc(ec, a); + }, + useInsertionEffect: lc, + useLayoutEffect: function () {}, + useCallback: function (a, b) { + return hc(function () { + return a; + }, b); + }, + useImperativeHandle: lc, + useEffect: lc, + useDebugValue: lc, + useDeferredValue: function (a) { + U(); + return a; + }, + useTransition: function () { + U(); + return [!1, jc]; + }, + useId: function () { + var a = Wb.treeContext; + var b = a.overflow; + a = a.id; + a = (a & ~(1 << (32 - Lb(a) - 1))).toString(32) + b; + var c = mc; + if (null === c) + throw Error( + "Invalid hook call. Hooks can only be called inside of the body of a function component." + ); + b = Q++; + a = ":" + c.idPrefix + "R" + a; + 0 < b && (a += "H" + b.toString(32)); + return a + ":"; + }, + useMutableSource: function (a, b) { + U(); + return b(a._source); + }, + useSyncExternalStore: function (a, b, c) { + if (void 0 === c) + throw Error( + "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering." + ); + return c(); + }, + useCacheRefresh: function () { + return kc; + }, + useEvent: function () { + return ic; + }, + useMemoCache: function (a) { + for (var b = Array(a), c = 0; c < a; c++) b[c] = vb; + return b; + }, + use: function (a) { + if (null !== a && "object" === typeof a) { + if ("function" === typeof a.then) { + var b = R; + R += 1; + null === S && (S = []); + return Rb(S, a, b); + } + if (a.$$typeof === ib || a.$$typeof === jb) return a._currentValue; + } + throw Error("An unsupported type was passed to use(): " + String(a)); + }, + }, + mc = null, + oc = { + getCacheSignal: function () { + throw Error("Not implemented."); + }, + getCacheForType: function () { + throw Error("Not implemented."); + }, + }, + pc = yb.ReactCurrentDispatcher, + qc = yb.ReactCurrentCache; +function rc(a) { + console.error(a); + return null; +} +function W() {} +function sc(a, b, c, d, e, f, g, h, m) { + var k = [], + p = new Set(), + n = { + preloadsMap: new Map(), + stylesMap: new Map(), + scriptsMap: new Map(), + headsMap: new Map(), + charset: null, + bases: new Set(), + preconnects: new Set(), + fontPreloads: new Set(), + precedences: new Map(), + usedStylePreloads: new Set(), + scripts: new Set(), + usedScriptPreloads: new Set(), + explicitStylePreloads: new Set(), + explicitScriptPreloads: new Set(), + headResources: new Set(), + structuredMetaKeys: new Map(), + boundaryResources: null, + }; + b = { + destination: null, + responseState: b, + progressiveChunkSize: void 0 === d ? 12800 : d, + status: 0, + fatalError: null, + nextSegmentId: 0, + allPendingTasks: 0, + pendingRootTasks: 0, + resources: n, + completedRootSegment: null, + abortableTasks: p, + pingedTasks: k, + clientRenderedBoundaries: [], + completedBoundaries: [], + partialBoundaries: [], + preamble: [], + postamble: [], + onError: void 0 === e ? rc : e, + onAllReady: void 0 === f ? W : f, + onShellReady: void 0 === g ? W : g, + onShellError: void 0 === h ? W : h, + onFatalError: void 0 === m ? W : m, + }; + c = tc(b, 0, null, c, !1, !1); + c.parentFlushed = !0; + a = uc(b, null, a, null, c, p, zb, null, Jb); + k.push(a); + return b; +} +function uc(a, b, c, d, e, f, g, h, m) { + a.allPendingTasks++; + null === d ? a.pendingRootTasks++ : d.pendingTasks++; + var k = { + node: c, + ping: function () { + var b = a.pingedTasks; + b.push(k); + 1 === b.length && vc(a); + }, + blockedBoundary: d, + blockedSegment: e, + abortSet: f, + legacyContext: g, + context: h, + treeContext: m, + thenableState: b, + }; + f.add(k); + return k; +} +function tc(a, b, c, d, e, f) { + return { + status: 0, + id: -1, + index: b, + parentFlushed: !1, + chunks: [], + children: [], + formatContext: d, + boundary: c, + lastPushedText: e, + textEmbedded: f, + }; +} +function X(a, b) { + a = a.onError(b); + if (null != a && "string" !== typeof a) + throw Error( + 'onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "' + + typeof a + + '" instead' + ); + return a; +} +function Y(a, b) { + var c = a.onShellError; + c(b); + c = a.onFatalError; + c(b); + null !== a.destination + ? ((a.status = 2), da(a.destination, b)) + : ((a.status = 1), (a.fatalError = b)); +} +function wc(a, b, c, d) { + var e = c.render(), + f = d.childContextTypes; + if (null !== f && void 0 !== f) { + var g = b.legacyContext; + if ("function" !== typeof c.getChildContext) d = g; + else { + c = c.getChildContext(); + for (var h in c) + if (!(h in f)) + throw Error( + (xb(d) || "Unknown") + + '.getChildContext(): key "' + + h + + '" is not defined in childContextTypes.' + ); + d = x({}, g, c); + } + b.legacyContext = d; + Z(a, b, null, e); + b.legacyContext = g; + } else Z(a, b, null, e); +} +function xc(a, b) { + if (a && a.defaultProps) { + b = x({}, b); + a = a.defaultProps; + for (var c in a) void 0 === b[c] && (b[c] = a[c]); + return b; + } + return b; +} +function yc(a, b, c, d, e, f) { + if ("function" === typeof d) + if (d.prototype && d.prototype.isReactComponent) + (c = Ab(d, b.legacyContext)), + (f = d.contextType), + (f = new d( + e, + "object" === typeof f && null !== f ? f._currentValue : c + )), + Ib(f, d, e, c), + wc(a, b, f, d); + else { + f = Ab(d, b.legacyContext); + M = {}; + Wb = b; + R = Q = 0; + S = c; + c = d(e, f); + c = bc(d, e, c, f); + var g = 0 !== Q; + if ( + "object" === typeof c && + null !== c && + "function" === typeof c.render && + void 0 === c.$$typeof + ) + Ib(c, d, e, f), wc(a, b, c, d); + else if (g) { + e = b.treeContext; + b.treeContext = Kb(e, 1, 0); + try { + Z(a, b, null, c); + } finally { + b.treeContext = e; + } + } else Z(a, b, null, c); + } + else if ("string" === typeof d) + (c = b.blockedSegment), + (f = Sa( + c.chunks, + a.preamble, + d, + e, + a.responseState, + c.formatContext, + c.lastPushedText + )), + (c.lastPushedText = !1), + (g = c.formatContext), + (c.formatContext = Ja(g, d, e)), + zc(a, b, f), + (c.formatContext = g), + Ta(c.chunks, a.postamble, d), + (c.lastPushedText = !1); + else { + switch (d) { + case sb: + case qb: + case fb: + case gb: + case eb: + Z(a, b, null, e.children); + return; + case rb: + "hidden" !== e.mode && Z(a, b, null, e.children); + return; + case mb: + Z(a, b, null, e.children); + return; + case pb: + throw Error("ReactDOMServer does not yet support scope components."); + case lb: + a: { + d = b.blockedBoundary; + c = b.blockedSegment; + f = e.fallback; + e = e.children; + g = new Set(); + var h = { + id: null, + rootSegmentID: -1, + parentFlushed: !1, + pendingTasks: 0, + forceClientRender: !1, + completedSegments: [], + byteSize: 0, + fallbackAbortableTasks: g, + errorDigest: null, + resources: new Set(), + }, + m = tc(a, c.chunks.length, h, c.formatContext, !1, !1); + c.children.push(m); + c.lastPushedText = !1; + var k = tc(a, 0, null, c.formatContext, !1, !1); + k.parentFlushed = !0; + b.blockedBoundary = h; + b.blockedSegment = k; + a.resources.boundaryResources = h.resources; + try { + if ( + (zc(a, b, e), + k.lastPushedText && + k.textEmbedded && + k.chunks.push("\x3c!-- --\x3e"), + (k.status = 1), + 0 === h.pendingTasks && + (null !== a.completedRootSegment || 0 < a.pendingRootTasks) && + Da(a.resources, h.resources), + Ac(h, k), + 0 === h.pendingTasks) + ) + break a; + } catch (p) { + (k.status = 4), + (h.forceClientRender = !0), + (h.errorDigest = X(a, p)); + } finally { + (a.resources.boundaryResources = d ? d.resources : null), + (b.blockedBoundary = d), + (b.blockedSegment = c); + } + b = uc( + a, + null, + f, + d, + m, + g, + b.legacyContext, + b.context, + b.treeContext + ); + a.pingedTasks.push(b); + } + return; + } + if ("object" === typeof d && null !== d) + switch (d.$$typeof) { + case kb: + d = d.render; + M = {}; + Wb = b; + R = Q = 0; + S = c; + c = d(e, f); + e = bc(d, e, c, f); + if (0 !== Q) { + d = b.treeContext; + b.treeContext = Kb(d, 1, 0); + try { + Z(a, b, null, e); + } finally { + b.treeContext = d; + } + } else Z(a, b, null, e); + return; + case nb: + d = d.type; + e = xc(d, e); + yc(a, b, c, d, e, f); + return; + case hb: + c = e.children; + d = d._context; + e = e.value; + f = d._currentValue; + d._currentValue = e; + g = L; + L = e = { + parent: g, + depth: null === g ? 0 : g.depth + 1, + context: d, + parentValue: f, + value: e, + }; + b.context = e; + Z(a, b, null, c); + a = L; + if (null === a) + throw Error( + "Tried to pop a Context at the root of the app. This is a bug in React." + ); + e = a.parentValue; + a.context._currentValue = e === ub ? a.context._defaultValue : e; + a = L = a.parent; + b.context = a; + return; + case ib: + e = e.children; + e = e(d._currentValue); + Z(a, b, null, e); + return; + case ob: + f = d._init; + d = f(d._payload); + e = xc(d, e); + yc(a, b, c, d, e, void 0); + return; + } + throw Error( + "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + + ((null == d ? d : typeof d) + ".") + ); + } +} +function Z(a, b, c, d) { + b.node = d; + if ("object" === typeof d && null !== d) { + switch (d.$$typeof) { + case cb: + yc(a, b, c, d.type, d.props, d.ref); + return; + case db: + throw Error( + "Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render." + ); + case ob: + c = d._init; + d = c(d._payload); + Z(a, b, null, d); + return; + } + if (ra(d)) { + Bc(a, b, d); + return; + } + null === d || "object" !== typeof d + ? (c = null) + : ((c = (wb && d[wb]) || d["@@iterator"]), + (c = "function" === typeof c ? c : null)); + if (c && (c = c.call(d))) { + d = c.next(); + if (!d.done) { + var e = []; + do e.push(d.value), (d = c.next()); + while (!d.done); + Bc(a, b, e); + } + return; + } + a = Object.prototype.toString.call(d); + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === a + ? "object with keys {" + Object.keys(d).join(", ") + "}" + : a) + + "). If you meant to render a collection of children, use an array instead." + ); + } + "string" === typeof d + ? ((c = b.blockedSegment), + (c.lastPushedText = Ka( + b.blockedSegment.chunks, + d, + a.responseState, + c.lastPushedText + ))) + : "number" === typeof d && + ((c = b.blockedSegment), + (c.lastPushedText = Ka( + b.blockedSegment.chunks, + "" + d, + a.responseState, + c.lastPushedText + ))); +} +function Bc(a, b, c) { + for (var d = c.length, e = 0; e < d; e++) { + var f = b.treeContext; + b.treeContext = Kb(f, d, e); + try { + zc(a, b, c[e]); + } finally { + b.treeContext = f; + } + } +} +function zc(a, b, c) { + var d = b.blockedSegment.formatContext, + e = b.legacyContext, + f = b.context; + try { + return Z(a, b, null, c); + } catch (k) { + if ( + (cc(), + (c = k === Pb ? Tb() : k), + "object" === typeof c && null !== c && "function" === typeof c.then) + ) { + var g = dc(), + h = b.blockedSegment, + m = tc(a, h.chunks.length, null, h.formatContext, h.lastPushedText, !0); + h.children.push(m); + h.lastPushedText = !1; + a = uc( + a, + g, + b.node, + b.blockedBoundary, + m, + b.abortSet, + b.legacyContext, + b.context, + b.treeContext + ).ping; + c.then(a, a); + b.blockedSegment.formatContext = d; + b.legacyContext = e; + b.context = f; + Gb(f); + } else + throw ( + ((b.blockedSegment.formatContext = d), + (b.legacyContext = e), + (b.context = f), + Gb(f), + c) + ); + } +} +function Cc(a) { + var b = a.blockedBoundary; + a = a.blockedSegment; + a.status = 3; + Dc(this, b, a); +} +function Ec(a, b, c) { + var d = a.blockedBoundary; + a.blockedSegment.status = 3; + null === d + ? (b.allPendingTasks--, + 1 !== b.status && 2 !== b.status && (X(b, c), Y(b, c))) + : (d.pendingTasks--, + d.forceClientRender || + ((d.forceClientRender = !0), + (d.errorDigest = b.onError(c)), + d.parentFlushed && b.clientRenderedBoundaries.push(d)), + d.fallbackAbortableTasks.forEach(function (a) { + return Ec(a, b, c); + }), + d.fallbackAbortableTasks.clear(), + b.allPendingTasks--, + 0 === b.allPendingTasks && ((a = b.onAllReady), a())); +} +function Ac(a, b) { + if ( + 0 === b.chunks.length && + 1 === b.children.length && + null === b.children[0].boundary + ) { + var c = b.children[0]; + c.id = b.id; + c.parentFlushed = !0; + 1 === c.status && Ac(a, c); + } else a.completedSegments.push(b); +} +function Dc(a, b, c) { + if (null === b) { + if (c.parentFlushed) { + if (null !== a.completedRootSegment) + throw Error( + "There can only be one root segment. This is a bug in React." + ); + a.completedRootSegment = c; + } + a.pendingRootTasks--; + 0 === a.pendingRootTasks && + ((a.onShellError = W), (b = a.onShellReady), b()); + } else + b.pendingTasks--, + b.forceClientRender || + (0 === b.pendingTasks + ? (c.parentFlushed && 1 === c.status && Ac(b, c), + (null !== a.completedRootSegment || 0 < a.pendingRootTasks) && + Da(a.resources, b.resources), + b.parentFlushed && a.completedBoundaries.push(b), + b.fallbackAbortableTasks.forEach(Cc, a), + b.fallbackAbortableTasks.clear()) + : c.parentFlushed && + 1 === c.status && + (Ac(b, c), + 1 === b.completedSegments.length && + b.parentFlushed && + a.partialBoundaries.push(b))); + a.allPendingTasks--; + 0 === a.allPendingTasks && ((a = a.onAllReady), a()); +} +function vc(a) { + if (2 !== a.status) { + var b = L, + c = pc.current; + pc.current = nc; + var d = qc.current; + qc.current = oc; + var e = a.resources; + sa.push(y); + y = e; + e = Ea.current; + Ea.current = va; + var f = mc; + mc = a.responseState; + try { + var g = a.pingedTasks, + h; + for (h = 0; h < g.length; h++) { + var m = g[h]; + var k = a, + p = m.blockedBoundary; + k.resources.boundaryResources = p ? p.resources : null; + var n = m.blockedSegment; + if (0 === n.status) { + Gb(m.context); + try { + var q = m.thenableState; + m.thenableState = null; + Z(k, m, q, m.node); + n.lastPushedText && + n.textEmbedded && + n.chunks.push("\x3c!-- --\x3e"); + m.abortSet.delete(m); + n.status = 1; + Dc(k, m.blockedBoundary, n); + } catch (aa) { + cc(); + var u = aa === Pb ? Tb() : aa; + if ( + "object" === typeof u && + null !== u && + "function" === typeof u.then + ) { + var H = m.ping; + u.then(H, H); + m.thenableState = dc(); + } else { + m.abortSet.delete(m); + n.status = 4; + var B = k, + E = m.blockedBoundary, + V = u, + P = X(B, V); + null === E + ? Y(B, V) + : (E.pendingTasks--, + E.forceClientRender || + ((E.forceClientRender = !0), + (E.errorDigest = P), + E.parentFlushed && B.clientRenderedBoundaries.push(E))); + B.allPendingTasks--; + if (0 === B.allPendingTasks) { + var Mc = B.onAllReady; + Mc(); + } + } + } finally { + k.resources.boundaryResources = null; + } + } + } + g.splice(0, h); + null !== a.destination && Fc(a, a.destination); + } catch (aa) { + X(a, aa), Y(a, aa); + } finally { + (mc = f), + (pc.current = c), + (qc.current = d), + (y = sa.pop()), + (Ea.current = e), + c === nc && Gb(b); + } + } +} +function Gc(a, b, c) { + c.parentFlushed = !0; + switch (c.status) { + case 0: + var d = (c.id = a.nextSegmentId++); + c.lastPushedText = !1; + c.textEmbedded = !1; + a = a.responseState; + l(b, '<template id="'); + l(b, a.placeholderPrefix); + a = d.toString(16); + l(b, a); + return !!b.write('"></template>'); + case 1: + c.status = 2; + var e = !0; + d = c.chunks; + var f = 0; + c = c.children; + for (var g = 0; g < c.length; g++) { + for (e = c[g]; f < e.index; f++) l(b, d[f]); + e = Hc(a, b, e); + } + for (; f < d.length - 1; f++) l(b, d[f]); + f < d.length && (e = !!b.write(d[f])); + return e; + default: + throw Error( + "Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React." + ); + } +} +function Hc(a, b, c) { + var d = c.boundary; + if (null === d) return Gc(a, b, c); + d.parentFlushed = !0; + if (d.forceClientRender) + (d = d.errorDigest), + b.write("\x3c!--$!--\x3e"), + l(b, "<template"), + d && (l(b, ' data-dgst="'), l(b, w(d)), l(b, '"')), + b.write("></template>"), + Gc(a, b, c); + else if (0 < d.pendingTasks) { + d.rootSegmentID = a.nextSegmentId++; + 0 < d.completedSegments.length && a.partialBoundaries.push(d); + var e = a.responseState; + var f = e.nextSuspenseID++; + e = e.boundaryPrefix + f.toString(16); + d = d.id = e; + Ua(b, a.responseState, d); + Gc(a, b, c); + } else if (d.byteSize > a.progressiveChunkSize) + (d.rootSegmentID = a.nextSegmentId++), + a.completedBoundaries.push(d), + Ua(b, a.responseState, d.id), + Gc(a, b, c); + else { + Ca(a.resources, d.resources); + b.write("\x3c!--$--\x3e"); + c = d.completedSegments; + if (1 !== c.length) + throw Error( + "A previously unvisited boundary must have exactly one root segment. This is a bug in React." + ); + Hc(a, b, c[0]); + } + return !!b.write("\x3c!--/$--\x3e"); +} +function Ic(a, b, c) { + Va(b, a.responseState, c.formatContext, c.id); + Hc(a, b, c); + return Wa(b, c.formatContext); +} +function Jc(a, b, c) { + a.resources.boundaryResources = c.resources; + for (var d = c.completedSegments, e = 0; e < d.length; e++) Kc(a, b, c, d[e]); + d.length = 0; + a = a.responseState; + d = c.id; + e = c.rootSegmentID; + c = c.resources; + var f; + a: { + for (f = c.values(); ; ) { + var g = f.next().value; + if (!g) break; + if (!g.inShell) { + f = !0; + break a; + } + } + f = !1; + } + l(b, a.startInlineScript); + f + ? a.sentCompleteBoundaryFunction + ? a.sentStyleInsertionFunction + ? l(b, '$RR("') + : ((a.sentStyleInsertionFunction = !0), + l( + b, + '$RM=new Map;\n$RR=function(p,q,v){function r(l){this.s=l}for(var t=$RC,u=$RM,m=new Map,n=document,g,e,f=n.querySelectorAll("link[data-precedence],style[data-precedence]"),d=0;e=f[d++];)m.set(e.dataset.precedence,g=e);e=0;f=[];for(var c,h,b,a;c=v[e++];){var k=0;h=c[k++];if(b=u.get(h))"l"!==b.s&&f.push(b);else{a=n.createElement("link");a.href=h;a.rel="stylesheet";for(a.dataset.precedence=d=c[k++];b=c[k++];)a.setAttribute(b,c[k++]);b=a._p=new Promise(function(l,w){a.onload=l;a.onerror=w});b.then(r.bind(b,\n"l"),r.bind(b,"e"));u.set(h,b);f.push(b);c=m.get(d)||g;c===g&&(g=a);m.set(d,a);c?c.parentNode.insertBefore(a,c.nextSibling):(d=n.head,d.insertBefore(a,d.firstChild))}}Promise.all(f).then(t.bind(null,p,q,""),t.bind(null,p,q,"Resource failed to load"))};;$RR("' + )) + : ((a.sentCompleteBoundaryFunction = !0), + (a.sentStyleInsertionFunction = !0), + l( + b, + '$RC=function(b,c,e){c=document.getElementById(c);c.parentNode.removeChild(c);var a=document.getElementById(b);if(a){b=a.previousSibling;if(e)b.data="$!",a.setAttribute("data-dgst",e);else{e=b.parentNode;a=b.nextSibling;var f=0;do{if(a&&8===a.nodeType){var d=a.data;if("/$"===d)if(0===f)break;else f--;else"$"!==d&&"$?"!==d&&"$!"!==d||f++}d=a.nextSibling;e.removeChild(a);a=d}while(a);for(;c.firstChild;)e.insertBefore(c.firstChild,a);b.data="$"}b._reactRetry&&b._reactRetry()}};;$RM=new Map;\n$RR=function(p,q,v){function r(l){this.s=l}for(var t=$RC,u=$RM,m=new Map,n=document,g,e,f=n.querySelectorAll("link[data-precedence],style[data-precedence]"),d=0;e=f[d++];)m.set(e.dataset.precedence,g=e);e=0;f=[];for(var c,h,b,a;c=v[e++];){var k=0;h=c[k++];if(b=u.get(h))"l"!==b.s&&f.push(b);else{a=n.createElement("link");a.href=h;a.rel="stylesheet";for(a.dataset.precedence=d=c[k++];b=c[k++];)a.setAttribute(b,c[k++]);b=a._p=new Promise(function(l,w){a.onload=l;a.onerror=w});b.then(r.bind(b,\n"l"),r.bind(b,"e"));u.set(h,b);f.push(b);c=m.get(d)||g;c===g&&(g=a);m.set(d,a);c?c.parentNode.insertBefore(a,c.nextSibling):(d=n.head,d.insertBefore(a,d.firstChild))}}Promise.all(f).then(t.bind(null,p,q,""),t.bind(null,p,q,"Resource failed to load"))};;$RR("' + )) + : a.sentCompleteBoundaryFunction + ? l(b, '$RC("') + : ((a.sentCompleteBoundaryFunction = !0), + l( + b, + '$RC=function(b,c,e){c=document.getElementById(c);c.parentNode.removeChild(c);var a=document.getElementById(b);if(a){b=a.previousSibling;if(e)b.data="$!",a.setAttribute("data-dgst",e);else{e=b.parentNode;a=b.nextSibling;var f=0;do{if(a&&8===a.nodeType){var d=a.data;if("/$"===d)if(0===f)break;else f--;else"$"!==d&&"$?"!==d&&"$!"!==d||f++}d=a.nextSibling;e.removeChild(a);a=d}while(a);for(;c.firstChild;)e.insertBefore(c.firstChild,a);b.data="$"}b._reactRetry&&b._reactRetry()}};;$RC("' + )); + if (null === d) + throw Error( + "An ID must have been assigned before we can complete the boundary." + ); + e = e.toString(16); + l(b, d); + l(b, '","'); + l(b, a.segmentPrefix); + l(b, e); + f ? (l(b, '",'), bb(b, c)) : l(b, '"'); + return !!b.write(")\x3c/script>"); +} +function Kc(a, b, c, d) { + if (2 === d.status) return !0; + var e = d.id; + if (-1 === e) { + if (-1 === (d.id = c.rootSegmentID)) + throw Error( + "A root segment ID must have been assigned by now. This is a bug in React." + ); + return Ic(a, b, d); + } + Ic(a, b, d); + a = a.responseState; + l(b, a.startInlineScript); + a.sentCompleteSegmentFunction + ? l(b, '$RS("') + : ((a.sentCompleteSegmentFunction = !0), + l( + b, + '$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};;$RS("' + )); + l(b, a.segmentPrefix); + e = e.toString(16); + l(b, e); + l(b, '","'); + l(b, a.placeholderPrefix); + l(b, e); + return !!b.write('")\x3c/script>'); +} +function Fc(a, b) { + try { + var c, + d = a.completedRootSegment; + if (null !== d) + if (0 === a.pendingRootTasks) { + var e = a.preamble; + for (c = 0; c < e.length; c++) l(b, e[c]); + $a(b, a.resources, a.responseState); + Hc(a, b, d); + a.completedRootSegment = null; + var f = a.responseState.bootstrapChunks; + for (d = 0; d < f.length - 1; d++) l(b, f[d]); + d < f.length && b.write(f[d]); + } else return; + else ab(b, a.resources, a.responseState); + var g = a.clientRenderedBoundaries; + for (c = 0; c < g.length; c++) { + var h = g[c]; + f = b; + var m = a.responseState, + k = h.id, + p = h.errorDigest, + n = h.errorMessage, + q = h.errorComponentStack; + l(f, m.startInlineScript); + m.sentClientRenderFunction + ? l(f, '$RX("') + : ((m.sentClientRenderFunction = !0), + l( + f, + '$RX=function(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};;$RX("' + )); + if (null === k) + throw Error( + "An ID must have been assigned before we can complete the boundary." + ); + l(f, k); + l(f, '"'); + if (p || n || q) l(f, ","), l(f, Ya(p || "")); + if (n || q) l(f, ","), l(f, Ya(n || "")); + q && (l(f, ","), l(f, Ya(q))); + if (!f.write(")\x3c/script>")) { + a.destination = null; + c++; + g.splice(0, c); + return; + } + } + g.splice(0, c); + var u = a.completedBoundaries; + for (c = 0; c < u.length; c++) + if (!Jc(a, b, u[c])) { + a.destination = null; + c++; + u.splice(0, c); + return; + } + u.splice(0, c); + var H = a.partialBoundaries; + for (c = 0; c < H.length; c++) { + var B = H[c]; + a: { + g = a; + h = b; + g.resources.boundaryResources = B.resources; + var E = B.completedSegments; + for (m = 0; m < E.length; m++) + if (!Kc(g, h, B, E[m])) { + m++; + E.splice(0, m); + var V = !1; + break a; + } + E.splice(0, m); + V = !0; + } + if (!V) { + a.destination = null; + c++; + H.splice(0, c); + return; + } + } + H.splice(0, c); + var P = a.completedBoundaries; + for (c = 0; c < P.length; c++) + if (!Jc(a, b, P[c])) { + a.destination = null; + c++; + P.splice(0, c); + return; + } + P.splice(0, c); + } finally { + if ( + 0 === a.allPendingTasks && + 0 === a.pingedTasks.length && + 0 === a.clientRenderedBoundaries.length && + 0 === a.completedBoundaries.length + ) { + a = a.postamble; + for (c = 0; c < a.length; c++) l(b, a[c]); + b.end(); + } + } +} +function Lc(a, b) { + try { + var c = a.abortableTasks; + if (0 < c.size) { + var d = + void 0 === b + ? Error("The render was aborted by the server without a reason.") + : b; + c.forEach(function (b) { + return Ec(b, a, d); + }); + c.clear(); + } + null !== a.destination && Fc(a, a.destination); + } catch (e) { + X(a, e), Y(a, e); + } +} +exports.renderToNodeStream = function () { + throw Error( + "ReactDOMServer.renderToNodeStream(): The Node Stream API is not available in Bun. Use ReactDOMServer.renderToReadableStream() instead." + ); +}; +exports.renderToReadableStream = function (a, b) { + return new Promise(function (c, d) { + var e, + f, + g = new Promise(function (a, b) { + f = a; + e = b; + }), + h = sc( + a, + Ha( + b ? b.identifierPrefix : void 0, + b ? b.nonce : void 0, + b ? b.bootstrapScriptContent : void 0, + b ? b.bootstrapScripts : void 0, + b ? b.bootstrapModules : void 0, + b ? b.unstable_externalRuntimeSrc : void 0 + ), + Ia(b ? b.namespaceURI : void 0), + b ? b.progressiveChunkSize : void 0, + b ? b.onError : void 0, + f, + function () { + var a = new ReadableStream( + { + type: "direct", + pull: function (a) { + if (1 === h.status) (h.status = 2), da(a, h.fatalError); + else if (2 !== h.status && null === h.destination) { + h.destination = a; + try { + Fc(h, a); + } catch (q) { + X(h, q), Y(h, q); + } + } + }, + cancel: function () { + Lc(h); + }, + }, + { highWaterMark: 2048 } + ); + a.allReady = g; + c(a); + }, + function (a) { + g.catch(function () {}); + d(a); + }, + e + ); + if (b && b.signal) { + var m = b.signal; + if (m.aborted) Lc(h, m.reason); + else { + var k = function () { + Lc(h, m.reason); + m.removeEventListener("abort", k); + }; + m.addEventListener("abort", k); + } + } + vc(h); + }); +}; +exports.renderToStaticNodeStream = function () { + throw Error( + "ReactDOMServer.renderToStaticNodeStream(): The Node Stream API is not available in Bun. Use ReactDOMServer.renderToReadableStream() instead." + ); +}; +exports.version = "18.2.0"; diff --git a/test/bun.js/react-dom.test.tsx b/test/bun.js/react-dom.test.tsx index 678f1ee9a..a05ed16a1 100644 --- a/test/bun.js/react-dom.test.tsx +++ b/test/bun.js/react-dom.test.tsx @@ -10,7 +10,7 @@ import { heapStats } from "bun:jsc"; import { describe, expect, it } from "bun:test"; import { renderToReadableStream as renderToReadableStreamBrowser } from "react-dom/server.browser"; import { gc } from "./gc"; -import { renderToReadableStream as renderToReadableStreamBun } from "./react-dom-server.bun"; +import { renderToReadableStream as renderToReadableStreamBun } from "./react-dom-server.bun.cjs"; import React from "react"; Object.defineProperty(renderToReadableStreamBrowser, "name", { @@ -93,9 +93,11 @@ describe("React", () => { it("React.createContext works", () => { expect(typeof React.createContext).toBe("function"); const pleaseDontThrow = React.createContext({ foo: true }); - expect(pleaseDontThrow.$$typeof.description).toBe("react.context"); + expect((pleaseDontThrow as any).$$typeof.description).toBe("react.context"); - const pleaseDontThrow2 = React.default.createContext({ foo: true }); + const pleaseDontThrow2 = (React as any).default.createContext({ + foo: true, + }); expect(pleaseDontThrow2.$$typeof.description).toBe("react.context"); }); }); @@ -117,7 +119,7 @@ describe("ReactDOM", () => { gc(); expect(text.replaceAll("<!-- -->", "")).toBe(inputString); gc(); - } catch (e) { + } catch (e: any) { console.log(e.stack); throw e; } @@ -159,7 +161,7 @@ describe("ReactDOM", () => { gc(); expect(text.replaceAll("<!-- -->", "")).toBe(inputString); gc(); - } catch (e) { + } catch (e: any) { console.error(e.message); console.error(e.stack); throw e; @@ -172,7 +174,7 @@ describe("ReactDOM", () => { const text = renderToReadableStream === renderToReadableStreamBun ? array.join("") - : new TextDecoder().decode(concatArrayBuffers(array)); + : new TextDecoder().decode(concatArrayBuffers(array as any[])); gc(); expect(text.replaceAll("<!-- -->", "")).toBe(inputString); gc(); @@ -189,7 +191,7 @@ describe("ReactDOM", () => { it("for await (chunk of stream)", async () => { const stream = await renderToReadableStream(reactElement); gc(); - const chunks = []; + const chunks: any = []; for await (let chunk of stream) { chunks.push(chunk); } @@ -202,12 +204,12 @@ describe("ReactDOM", () => { it("for await (chunk of stream) (arrayBuffer)", async () => { const stream = await renderToReadableStream(reactElement); gc(); - const chunks = []; + const chunks: any[] = []; for await (let chunk of stream) { chunks.push(chunk); } const text = new TextDecoder().decode( - await new Response(chunks).arrayBuffer() + await new Response(chunks as any).arrayBuffer(), ); gc(); expect(text.replaceAll("<!-- -->", "")).toBe(inputString); diff --git a/test/bun.js/resolve-error.test.ts b/test/bun.js/resolve-error.test.ts index 4db6319cc..cddd2c051 100644 --- a/test/bun.js/resolve-error.test.ts +++ b/test/bun.js/resolve-error.test.ts @@ -4,7 +4,7 @@ describe("ResolveError", () => { it("position object does not segfault", async () => { try { await import("./file-importing-nonexistent-file.js"); - } catch (e) { + } catch (e: any) { expect(Bun.inspect(e.position).length > 0).toBe(true); } }); diff --git a/test/bun.js/resolve.test.js b/test/bun.js/resolve.test.js index 6d8daedc5..1ae00306e 100644 --- a/test/bun.js/resolve.test.js +++ b/test/bun.js/resolve.test.js @@ -7,19 +7,19 @@ it("#imports", async () => { const baz = await import.meta.resolve( "#foo", - join(await import.meta.resolve("package-json-imports/baz"), "../") + join(await import.meta.resolve("package-json-imports/baz"), "../"), ); expect(baz.endsWith("foo/private-foo.js")).toBe(true); const subpath = await import.meta.resolve( "#foo/bar", - join(await import.meta.resolve("package-json-imports/baz"), "../") + join(await import.meta.resolve("package-json-imports/baz"), "../"), ); expect(subpath.endsWith("foo/private-foo.js")).toBe(true); const react = await import.meta.resolve( "#internal-react", - join(await import.meta.resolve("package-json-imports/baz"), "../") + join(await import.meta.resolve("package-json-imports/baz"), "../"), ); expect(react.endsWith("/react/index.js")).toBe(true); @@ -52,7 +52,7 @@ it("#imports with wildcard", async () => { expect( ( await import.meta.resolve("package-json-imports/#foo/wildcard.js") - ).endsWith("/wildcard.js") + ).endsWith("/wildcard.js"), ).toBe(true); }); @@ -60,20 +60,20 @@ it("import.meta.resolve", async () => { expect(await import.meta.resolve("./resolve.test.js")).toBe(import.meta.path); expect(await import.meta.resolve("./resolve.test.js", import.meta.path)).toBe( - import.meta.path + import.meta.path, ); expect( // optional second param can be any path, including a dir await import.meta.resolve( "./bun.js/resolve.test.js", - join(import.meta.path, "../") - ) + join(import.meta.path, "../"), + ), ).toBe(import.meta.path); // can be a package path expect( - (await import.meta.resolve("react", import.meta.path)).length > 0 + (await import.meta.resolve("react", import.meta.path)).length > 0, ).toBe(true); // file extensions are optional @@ -81,22 +81,22 @@ it("import.meta.resolve", async () => { // works with tsconfig.json "paths" expect(await import.meta.resolve("foo/bar")).toBe( - join(import.meta.path, "../baz.js") + join(import.meta.path, "../baz.js"), ); // works with package.json "exports" writePackageJSONExportsFixture(); expect(await import.meta.resolve("package-json-exports/baz")).toBe( - join(import.meta.path, "../node_modules/package-json-exports/foo/bar.js") + join(import.meta.path, "../node_modules/package-json-exports/foo/bar.js"), ); // works with TypeScript compiler edgecases like: // - If the file ends with .js and it doesn't exist, try again with .ts and .tsx expect(await import.meta.resolve("./resolve-typescript-file.js")).toBe( - join(import.meta.path, "../resolve-typescript-file.tsx") + join(import.meta.path, "../resolve-typescript-file.tsx"), ); expect(await import.meta.resolve("./resolve-typescript-file.tsx")).toBe( - join(import.meta.path, "../resolve-typescript-file.tsx") + join(import.meta.path, "../resolve-typescript-file.tsx"), ); // throws a ResolveError on failure @@ -114,14 +114,14 @@ it("import.meta.resolve", async () => { // and expects a directory instead of a filepath it("Bun.resolve", async () => { expect(await Bun.resolve("./resolve.test.js", import.meta.dir)).toBe( - import.meta.path + import.meta.path, ); }); // synchronous it("Bun.resolveSync", () => { expect(Bun.resolveSync("./resolve.test.js", import.meta.dir)).toBe( - import.meta.path + import.meta.path, ); }); @@ -130,7 +130,7 @@ it("self-referencing imports works", async () => { const baz = await import.meta.resolve("package-json-exports/baz"); const namespace = await import.meta.resolve( - "package-json-exports/references-baz" + "package-json-exports/references-baz", ); Loader.registry.delete(baz); Loader.registry.delete(namespace); @@ -175,19 +175,19 @@ function writePackageJSONExportsFixture() { join(import.meta.dir, "./node_modules/package-json-exports/foo"), { recursive: true, - } + }, ); } catch (exception) {} writeFileSync( join(import.meta.dir, "./node_modules/package-json-exports/foo/bar.js"), - "export const bar = 1;" + "export const bar = 1;", ); writeFileSync( join( import.meta.dir, - "./node_modules/package-json-exports/foo/references-baz.js" + "./node_modules/package-json-exports/foo/references-baz.js", ), - "export {bar} from 'package-json-exports/baz';" + "export {bar} from 'package-json-exports/baz';", ); writeFileSync( join(import.meta.dir, "./node_modules/package-json-exports/package.json"), @@ -200,8 +200,8 @@ function writePackageJSONExportsFixture() { }, }, null, - 2 - ) + 2, + ), ); } @@ -211,26 +211,26 @@ function writePackageJSONImportsFixture() { join(import.meta.dir, "./node_modules/package-json-imports/foo"), { recursive: true, - } + }, ); } catch (exception) {} writeFileSync( join(import.meta.dir, "./node_modules/package-json-imports/foo/bar.js"), - "export const bar = 1;" + "export const bar = 1;", ); writeFileSync( join( import.meta.dir, - "./node_modules/package-json-imports/foo/wildcard.js" + "./node_modules/package-json-imports/foo/wildcard.js", ), - "export const wildcard = 1;" + "export const wildcard = 1;", ); writeFileSync( join( import.meta.dir, - "./node_modules/package-json-imports/foo/private-foo.js" + "./node_modules/package-json-imports/foo/private-foo.js", ), - "export {bar} from 'package-json-imports/#foo';" + "export {bar} from 'package-json-imports/#foo';", ); writeFileSync( join(import.meta.dir, "./node_modules/package-json-imports/package.json"), @@ -248,7 +248,7 @@ function writePackageJSONImportsFixture() { }, }, null, - 2 - ) + 2, + ), ); } diff --git a/test/bun.js/serve.test.ts b/test/bun.js/serve.test.ts index c033aaeb3..ea175dca5 100644 --- a/test/bun.js/serve.test.ts +++ b/test/bun.js/serve.test.ts @@ -90,13 +90,13 @@ describe("streaming", () => { pull(controller) { throw new Error("error"); }, - }) + }), ); }, }); const response = await fetch( - `http://${server.hostname}:${server.port}` + `http://${server.hostname}:${server.port}`, ); if (response.status > 0) { expect(response.status).toBe(500); @@ -132,13 +132,13 @@ describe("streaming", () => { controller.enqueue("such fail"); throw new Error("error"); }, - }) + }), ); }, }); const response = await fetch( - `http://${server.hostname}:${server.port}` + `http://${server.hostname}:${server.port}`, ); // connection terminated if (response.status > 0) { @@ -167,7 +167,7 @@ describe("streaming", () => { controller.enqueue(textToExpect); controller.close(); }, - }) + }), ); }, }); @@ -192,7 +192,7 @@ describe("streaming", () => { controller.enqueue(textToExpect.substring(100)); controller.close(); }, - }) + }), ); }, }); @@ -214,7 +214,7 @@ describe("streaming", () => { start(controller) { throw new TestPass("Test Passed"); }, - }) + }), ); }, }); @@ -222,7 +222,7 @@ describe("streaming", () => { var response; try { response = await fetch(`http://${server.hostname}:${server.port}`); - } catch (e) { + } catch (e: any) { if (e.name !== "ConnectionClosed") { throw e; } @@ -260,7 +260,7 @@ describe("streaming", () => { start(controller) { throw new TypeError("error"); }, - }) + }), ); }, }); @@ -294,7 +294,7 @@ describe("streaming", () => { controller.close(); }); }, - }) + }), ); }, }); @@ -316,7 +316,7 @@ describe("streaming", () => { controller.enqueue(textToExpect); controller.close(); }, - }) + }), ); }, }); @@ -342,7 +342,7 @@ describe("streaming", () => { controller.close(); }); }, - }) + }), ); }, }); @@ -367,7 +367,7 @@ describe("streaming", () => { await Promise.resolve(); controller.close(); }, - }) + }), ); }, }); @@ -396,7 +396,7 @@ describe("streaming", () => { controller.enqueue(remain); controller.close(); }, - }) + }), ); }, }); diff --git a/test/bun.js/snapshots.debug.js b/test/bun.js/snapshots.debug.js index d4c345677..e130188c0 100644 --- a/test/bun.js/snapshots.debug.js +++ b/test/bun.js/snapshots.debug.js @@ -1,9 +1,8 @@ - // test/bun.js/module-require.snapshot.js -import { -__require as require -} from "bun:wrap"; -console.log(import.meta.require("/Users/jarred/Code/bun/node_modules/react/index.js")); +import { __require as require } from "bun:wrap"; +console.log( + import.meta.require("/Users/jarred/Code/bun/node_modules/react/index.js"), +); // test/bun.js/require-referenceerror.snapshot.js diff --git a/test/bun.js/snapshots.js b/test/bun.js/snapshots.js index d4c345677..e130188c0 100644 --- a/test/bun.js/snapshots.js +++ b/test/bun.js/snapshots.js @@ -1,9 +1,8 @@ - // test/bun.js/module-require.snapshot.js -import { -__require as require -} from "bun:wrap"; -console.log(import.meta.require("/Users/jarred/Code/bun/node_modules/react/index.js")); +import { __require as require } from "bun:wrap"; +console.log( + import.meta.require("/Users/jarred/Code/bun/node_modules/react/index.js"), +); // test/bun.js/require-referenceerror.snapshot.js diff --git a/test/bun.js/solid-dom-fixtures/SVG/code.js b/test/bun.js/solid-dom-fixtures/SVG/code.js index 0ffded054..9f8b508f7 100644 --- a/test/bun.js/solid-dom-fixtures/SVG/code.js +++ b/test/bun.js/solid-dom-fixtures/SVG/code.js @@ -11,7 +11,7 @@ const template = ( style="fill:red;stroke:black;stroke-width:5;opacity:0.5" /> <linearGradient gradientTransform="rotate(25)"> - <stop offset="0%"></stop> + <stop offset="0%" /> </linearGradient> </svg> ); diff --git a/test/bun.js/solid-dom-fixtures/attributeExpressions/code.js b/test/bun.js/solid-dom-fixtures/attributeExpressions/code.js index b64949434..e6822ec0c 100644 --- a/test/bun.js/solid-dom-fixtures/attributeExpressions/code.js +++ b/test/bun.js/solid-dom-fixtures/attributeExpressions/code.js @@ -46,7 +46,7 @@ const template4 = ( <div class="hi" className={state.class} classList={{ "ccc:ddd": true }} /> ); -const template5 = <div class="a" className="b"></div>; +const template5 = <div class="a" className="b" />; const template6 = <div style={someStyle()} textContent="Hi" />; diff --git a/test/bun.js/solid-dom-fixtures/customElements/code.js b/test/bun.js/solid-dom-fixtures/customElements/code.js index f2e2bd02d..bc844b7d8 100644 --- a/test/bun.js/solid-dom-fixtures/customElements/code.js +++ b/test/bun.js/solid-dom-fixtures/customElements/code.js @@ -24,6 +24,6 @@ const template3 = ( const template4 = ( <> - <slot name="head"></slot> + <slot name="head" /> </> ); diff --git a/test/bun.js/some-fs.js b/test/bun.js/some-fs.js index e6b31f162..b22423dc7 100644 --- a/test/bun.js/some-fs.js +++ b/test/bun.js/some-fs.js @@ -16,7 +16,7 @@ for (let i = 0; i < count; i++) { if (existsSync(tempdir)) { throw new Error( - `existsSync reports ${tempdir} exists, but it probably does not` + `existsSync reports ${tempdir} exists, but it probably does not`, ); } @@ -40,12 +40,12 @@ console.log("MKDIR " + total + " depth took:", performance.now() - start, "ms"); if (!existsSync(tempdir)) { throw new Error( - "Expected directory to exist after mkdirSync, but it doesn't" + "Expected directory to exist after mkdirSync, but it doesn't", ); } if (mkdirSync(tempdir, { recursive: true })) { throw new Error( - "mkdirSync shouldn't return directory name on existing directories" + "mkdirSync shouldn't return directory name on existing directories", ); } diff --git a/test/bun.js/spawn.test.ts b/test/bun.js/spawn.test.ts index b3ac6ae5f..f8694bfcc 100644 --- a/test/bun.js/spawn.test.ts +++ b/test/bun.js/spawn.test.ts @@ -1,12 +1,12 @@ import { readableStreamToText, spawn, spawnSync, write } from "bun"; import { describe, expect, it } from "bun:test"; -import { gcTick as _gcTick } from "gc"; +import { gcTick as _gcTick } from "./gc"; import { rmdirSync, unlinkSync, rmSync, writeFileSync } from "node:fs"; for (let [gcTick, label] of [ [_gcTick, "gcTick"], [() => {}, "no gc tick"], -]) { +] as const) { describe(label, () => { describe("spawnSync", () => { const hugeString = "hello".repeat(10000).slice(); @@ -15,7 +15,7 @@ for (let [gcTick, label] of [ const { stdout } = spawnSync(["echo", "hi"]); // stdout is a Buffer - const text = stdout.toString(); + const text = stdout!.toString(); expect(text).toBe("hi\n"); }); @@ -25,8 +25,8 @@ for (let [gcTick, label] of [ stdin: new TextEncoder().encode(hugeString), }); - expect(stdout.toString()).toBe(hugeString); - expect(stderr.byteLength).toBe(0); + expect(stdout!.toString()).toBe(hugeString); + expect(stderr!.byteLength).toBe(0); }); it("check exit code", async () => { @@ -94,7 +94,7 @@ for (let [gcTick, label] of [ it("check exit code from onExit", async () => { var exitCode1, exitCode2; - await new Promise((resolve) => { + await new Promise<void>((resolve) => { var counter = 0; spawn({ cmd: ["ls"], @@ -156,7 +156,7 @@ for (let [gcTick, label] of [ stdin: Bun.file("/tmp/out.456.txt"), }); gcTick(); - expect(await readableStreamToText(stdout)).toBe("hello there!"); + expect(await readableStreamToText(stdout!)).toBe("hello there!"); }); it("Bun.file() works as stdin and stdout", async () => { @@ -184,9 +184,10 @@ for (let [gcTick, label] of [ cmd: ["cat", "/tmp/out.txt"], stdout: "pipe", }); + gcTick(); - const text = await readableStreamToText(stdout); + const text = await readableStreamToText(stdout!); gcTick(); expect(text).toBe(hugeString); }); @@ -220,17 +221,18 @@ for (let [gcTick, label] of [ stdin: "pipe", stderr: "inherit", }); - proc.stdin.write(hugeString); - await proc.stdin.end(true); + + proc.stdin!.write(hugeString); + await proc.stdin!.end(); var text = ""; - var reader = proc.stdout.getReader(); + var reader = proc.stdout!.getReader(); var done = false; while (!done) { var { value, done } = await reader.read(); if (value) text += new TextDecoder().decode(value); if (done && text.length === 0) { reader.releaseLock(); - reader = proc.stdout.getReader(); + reader = proc.stdout!.getReader(); done = false; } } @@ -262,14 +264,14 @@ for (let [gcTick, label] of [ const fixtures = [ [helloWorld, "hello"], [huge, hugeString], - ]; + ] as const; for (const [callback, fixture] of fixtures) { describe(fixture.slice(0, 12), () => { describe("should should allow reading stdout", () => { it("before exit", async () => { const process = callback(); - const output = await readableStreamToText(process.stdout); + const output = await readableStreamToText(process.stdout!); const expected = fixture + "\n"; expect(output.length).toBe(expected.length); expect(output).toBe(expected); @@ -280,7 +282,7 @@ for (let [gcTick, label] of [ it("before exit (chunked)", async () => { const process = callback(); var output = ""; - var reader = process.stdout.getReader(); + var reader = process.stdout!.getReader(); var done = false; while (!done) { var { value, done } = await reader.read(); @@ -296,9 +298,9 @@ for (let [gcTick, label] of [ it("after exit", async () => { const process = callback(); - await process.stdin.end(); + await process.stdin!.end(); - const output = await readableStreamToText(process.stdout); + const output = await readableStreamToText(process.stdout!); const expected = fixture + "\n"; expect(output.length).toBe(expected.length); diff --git a/test/bun.js/sql-raw.test.js b/test/bun.js/sql-raw.test.js index e4dd1db82..6cf052e0e 100644 --- a/test/bun.js/sql-raw.test.js +++ b/test/bun.js/sql-raw.test.js @@ -8,10 +8,10 @@ it("works", () => { const stmt = SQL.prepare( handle, - 'SELECT * FROM "Orders" WHERE OrderDate > date($date)' + 'SELECT * FROM "Orders" WHERE OrderDate > date($date)', ); expect(stmt.toString()).toBe( - `SELECT * FROM "Orders" WHERE OrderDate > date(NULL)` + `SELECT * FROM "Orders" WHERE OrderDate > date(NULL)`, ); expect( @@ -19,37 +19,37 @@ it("works", () => { stmt.all({ // do the conversion this way so that this test runs in multiple timezones $date: new Date( - new Date(1996, 8, 1, 0, 0, 0, 0).toUTCString() + new Date(1996, 8, 1, 0, 0, 0, 0).toUTCString(), ).toISOString(), - }) - ) + }), + ), ).toBe(true); expect(stmt.toString()).toBe( - `SELECT * FROM "Orders" WHERE OrderDate > date('1996-09-01T07:00:00.000Z')` + `SELECT * FROM "Orders" WHERE OrderDate > date('1996-09-01T07:00:00.000Z')`, ); var ran = stmt.run({ $date: new Date( - new Date(1997, 8, 1, 0, 0, 0, 0).toUTCString() + new Date(1997, 8, 1, 0, 0, 0, 0).toUTCString(), ).toISOString(), }); expect(Array.isArray(ran)).toBe(false); expect(ran === undefined).toBe(true); expect(stmt.toString()).toBe( - `SELECT * FROM "Orders" WHERE OrderDate > date('1997-09-01T07:00:00.000Z')` + `SELECT * FROM "Orders" WHERE OrderDate > date('1997-09-01T07:00:00.000Z')`, ); expect( Array.isArray( stmt.get({ $date: new Date( - new Date(1998, 8, 1, 0, 0, 0, 0).toUTCString() + new Date(1998, 8, 1, 0, 0, 0, 0).toUTCString(), ).toISOString(), - }) - ) + }), + ), ).toBe(false); expect(stmt.toString()).toBe( - `SELECT * FROM "Orders" WHERE OrderDate > date('1998-09-01T07:00:00.000Z')` + `SELECT * FROM "Orders" WHERE OrderDate > date('1998-09-01T07:00:00.000Z')`, ); expect(stmt.paramsCount).toBe(1); expect(stmt.columnsCount).toBe(14); @@ -65,7 +65,7 @@ it("SQL.run works", () => { expect( SQL.run(handle, 'SELECT * FROM "Orders" WHERE OrderDate > date($date)', { $date: new Date(1996, 8, 1).toISOString(), - }) + }), ).toBe(undefined); SQL.close(handle); diff --git a/test/bun.js/sqlite.test.js b/test/bun.js/sqlite.test.js index 96d106b65..4ca236819 100644 --- a/test/bun.js/sqlite.test.js +++ b/test/bun.js/sqlite.test.js @@ -1,14 +1,14 @@ import { expect, it, describe } from "bun:test"; import { Database, constants } from "bun:sqlite"; import { existsSync, fstat, writeFileSync } from "fs"; -var encode = (text) => new TextEncoder().encode(text) +var encode = (text) => new TextEncoder().encode(text); it("Database.open", () => { // in a folder which doesn't exist try { Database.open( "/this/database/does/not/exist.sqlite", - constants.SQLITE_OPEN_READWRITE + constants.SQLITE_OPEN_READWRITE, ); throw new Error("Expected an error to be thrown"); } catch (error) { @@ -19,7 +19,7 @@ it("Database.open", () => { try { Database.open( `/tmp/database-${Math.random()}.sqlite`, - constants.SQLITE_OPEN_READWRITE + constants.SQLITE_OPEN_READWRITE, ); throw new Error("Expected an error to be thrown"); } catch (error) { @@ -58,10 +58,10 @@ it("Database.open", () => { it("creates", () => { const db = Database.open(":memory:"); db.exec( - "CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, created TEXT, deci FLOAT, blobby BLOB)" + "CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, created TEXT, deci FLOAT, blobby BLOB)", ); const stmt = db.prepare( - "INSERT INTO test (name, value, deci, created, blobby) VALUES (?, ?, ?, ?, ?)" + "INSERT INTO test (name, value, deci, created, blobby) VALUES (?, ?, ?, ?, ?)", ); stmt.run([ @@ -97,7 +97,7 @@ it("creates", () => { created: new Date(1995, 12, 19).toISOString(), deci: Math.fround(1.111), blobby: encode("Hello World"), - }) + }), ); expect(JSON.stringify(stmt2.all())).toBe( @@ -126,7 +126,7 @@ it("creates", () => { deci: Math.fround(3.333), blobby: encode("Hello World"), }, - ]) + ]), ); expect(stmt2.run()).toBe(undefined); @@ -193,7 +193,7 @@ it("db.query supports TypedArray", () => { JSON.stringify({ id: 1, blobby: encode("Hello World"), - }) + }), ); const stmt3 = db.prepare("SELECT * FROM test WHERE (blobby = ?)"); @@ -202,20 +202,20 @@ it("db.query supports TypedArray", () => { JSON.stringify({ id: 1, blobby: encode("Hello World"), - }) + }), ); expect( JSON.stringify( db .query("SELECT * FROM test WHERE (blobby = ?)") - .get([encode("Hello World")]) - ) + .get([encode("Hello World")]), + ), ).toBe( JSON.stringify({ id: 1, blobby: encode("Hello World"), - }) + }), ); expect(stmt3.get([encode("Hello World NOT")])).toBe(null); @@ -235,7 +235,7 @@ it("supports serialize/deserialize", () => { JSON.stringify({ id: 1, name: "Hello", - }) + }), ); expect(JSON.stringify(stmt.all())).toBe( @@ -248,7 +248,7 @@ it("supports serialize/deserialize", () => { id: 2, name: "World", }, - ]) + ]), ); db2.exec("insert into test (name) values ('foo')"); expect(JSON.stringify(stmt.all())).toBe( @@ -265,7 +265,7 @@ it("supports serialize/deserialize", () => { id: 3, name: "foo", }, - ]) + ]), ); const db3 = new Database(input, { readonly: true }); @@ -334,15 +334,15 @@ it("db.query()", () => { JSON.stringify( db .query("SELECT * FROM test where (name = ? OR name = ?)") - .all(["Hello", "Fooooo"]) - ) + .all(["Hello", "Fooooo"]), + ), ).toBe(JSON.stringify([{ id: 1, name: "Hello" }])); expect( JSON.stringify( db .query("SELECT * FROM test where (name = ? OR name = ?)") - .all("Hello", "Fooooo") - ) + .all("Hello", "Fooooo"), + ), ).toBe(JSON.stringify([{ id: 1, name: "Hello" }])); // throws if insufficeint arguments @@ -360,8 +360,8 @@ it("db.query()", () => { .all({ $hello: "Hello", $goodbye: "Fooooo", - }) - ) + }), + ), ).toBe(JSON.stringify([{ id: 1, name: "Hello" }])); db.close(); @@ -386,11 +386,11 @@ it("db.transaction()", () => { const db = Database.open(":memory:"); db.exec( - "CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)" + "CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)", ); const insert = db.prepare( - "INSERT INTO cats (name, age) VALUES (@name, @age)" + "INSERT INTO cats (name, age) VALUES (@name, @age)", ); expect(db.inTransaction).toBe(false); diff --git a/test/bun.js/streams.test.js b/test/bun.js/streams.test.js index d18aae84a..c6d69ab08 100644 --- a/test/bun.js/streams.test.js +++ b/test/bun.js/streams.test.js @@ -455,7 +455,7 @@ it("ReadableStream for Blob", async () => { chunks.push(new TextDecoder().decode(chunk.value)); } expect(chunks.join("")).toBe( - new TextDecoder().decode(Buffer.from("abdefghijklmnop")) + new TextDecoder().decode(Buffer.from("abdefghijklmnop")), ); }); diff --git a/test/bun.js/string-decoder.test.js b/test/bun.js/string-decoder.test.js index 8f3ad7695..4664cc388 100644 --- a/test/bun.js/string-decoder.test.js +++ b/test/bun.js/string-decoder.test.js @@ -2,10 +2,10 @@ import { expect, it } from "bun:test"; import { StringDecoder } from "string_decoder"; it("StringDecoder-utf8", () => { - test('utf-8', Buffer.from('$', 'utf-8'), '$'); - test('utf-8', Buffer.from('¢', 'utf-8'), '¢'); - test('utf-8', Buffer.from('€', 'utf-8'), '€'); - test('utf-8', Buffer.from('𤭢', 'utf-8'), '𤭢'); + test("utf-8", Buffer.from("$", "utf-8"), "$"); + test("utf-8", Buffer.from("¢", "utf-8"), "¢"); + test("utf-8", Buffer.from("€", "utf-8"), "€"); + test("utf-8", Buffer.from("𤭢", "utf-8"), "𤭢"); // A mixed ascii and non-ascii string // Test stolen from deps/v8/test/cctest/test-strings.cc // U+02E4 -> CB A4 @@ -14,67 +14,69 @@ it("StringDecoder-utf8", () => { // U+0030 -> 30 // U+3045 -> E3 81 85 test( - 'utf-8', - Buffer.from([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85]), - '\u02e4\u0064\u12e4\u0030\u3045' + "utf-8", + Buffer.from([0xcb, 0xa4, 0x64, 0xe1, 0x8b, 0xa4, 0x30, 0xe3, 0x81, 0x85]), + "\u02e4\u0064\u12e4\u0030\u3045", ); }); it("StringDecoder-ucs-2", () => { - test('ucs2', Buffer.from('ababc', 'ucs2'), 'ababc'); + test("ucs2", Buffer.from("ababc", "ucs2"), "ababc"); }); it("StringDecoder-utf16le", () => { - test('utf16le', Buffer.from('3DD84DDC', 'hex'), '\ud83d\udc4d'); + test("utf16le", Buffer.from("3DD84DDC", "hex"), "\ud83d\udc4d"); }); it("StringDecoder-utf8-additional", () => { - let decoder = new StringDecoder('utf8'); - expect(decoder.write(Buffer.from('E18B', 'hex'))).toBe(''); - expect(decoder.end()).toBe('\ufffd'); + let decoder = new StringDecoder("utf8"); + expect(decoder.write(Buffer.from("E18B", "hex"))).toBe(""); + expect(decoder.end()).toBe("\ufffd"); - decoder = new StringDecoder('utf8'); - expect(decoder.write(Buffer.from('\ufffd'))).toBe('\ufffd'); - expect(decoder.end()).toBe(''); + decoder = new StringDecoder("utf8"); + expect(decoder.write(Buffer.from("\ufffd"))).toBe("\ufffd"); + expect(decoder.end()).toBe(""); - decoder = new StringDecoder('utf8'); - expect(decoder.write(Buffer.from('\ufffd\ufffd\ufffd'))).toBe('\ufffd\ufffd\ufffd'); - expect(decoder.end()).toBe(''); + decoder = new StringDecoder("utf8"); + expect(decoder.write(Buffer.from("\ufffd\ufffd\ufffd"))).toBe( + "\ufffd\ufffd\ufffd", + ); + expect(decoder.end()).toBe(""); - decoder = new StringDecoder('utf8'); - expect(decoder.write(Buffer.from('EFBFBDE2', 'hex'))).toBe('\ufffd'); - expect(decoder.end()).toBe('\ufffd'); + decoder = new StringDecoder("utf8"); + expect(decoder.write(Buffer.from("EFBFBDE2", "hex"))).toBe("\ufffd"); + expect(decoder.end()).toBe("\ufffd"); - decoder = new StringDecoder('utf8'); - expect(decoder.write(Buffer.from('F1', 'hex'))).toBe(''); - expect(decoder.write(Buffer.from('41F2', 'hex'))).toBe('\ufffdA'); - expect(decoder.end()).toBe('\ufffd'); + decoder = new StringDecoder("utf8"); + expect(decoder.write(Buffer.from("F1", "hex"))).toBe(""); + expect(decoder.write(Buffer.from("41F2", "hex"))).toBe("\ufffdA"); + expect(decoder.end()).toBe("\ufffd"); // Additional utf8Text test - decoder = new StringDecoder('utf8'); - expect(decoder.text(Buffer.from([0x41]), 2)).toBe(''); + decoder = new StringDecoder("utf8"); + expect(decoder.text(Buffer.from([0x41]), 2)).toBe(""); }); it("StringDecoder-utf16le-additional", () => { // Additional UTF-16LE surrogate pair tests - let decoder = new StringDecoder('utf16le'); - expect(decoder.write(Buffer.from('3DD8', 'hex'))).toBe(''); - expect(decoder.write(Buffer.from('4D', 'hex'))).toBe(''); - expect(decoder.write(Buffer.from('DC', 'hex'))).toBe('\ud83d\udc4d'); - expect(decoder.end()).toBe(''); + let decoder = new StringDecoder("utf16le"); + expect(decoder.write(Buffer.from("3DD8", "hex"))).toBe(""); + expect(decoder.write(Buffer.from("4D", "hex"))).toBe(""); + expect(decoder.write(Buffer.from("DC", "hex"))).toBe("\ud83d\udc4d"); + expect(decoder.end()).toBe(""); - decoder = new StringDecoder('utf16le'); - expect(decoder.write(Buffer.from('3DD8', 'hex'))).toBe(''); - expect(decoder.end()).toBe('\ud83d'); + decoder = new StringDecoder("utf16le"); + expect(decoder.write(Buffer.from("3DD8", "hex"))).toBe(""); + expect(decoder.end()).toBe("\ud83d"); - decoder = new StringDecoder('utf16le'); - expect(decoder.write(Buffer.from('3DD8', 'hex'))).toBe(''); - expect(decoder.write(Buffer.from('4D', 'hex'))).toBe(''); - expect(decoder.end()).toBe('\ud83d'); + decoder = new StringDecoder("utf16le"); + expect(decoder.write(Buffer.from("3DD8", "hex"))).toBe(""); + expect(decoder.write(Buffer.from("4D", "hex"))).toBe(""); + expect(decoder.end()).toBe("\ud83d"); - decoder = new StringDecoder('utf16le'); - expect(decoder.write(Buffer.from('3DD84D', 'hex'))).toBe('\ud83d'); - expect(decoder.end()).toBe(''); + decoder = new StringDecoder("utf16le"); + expect(decoder.write(Buffer.from("3DD84D", "hex"))).toBe("\ud83d"); + expect(decoder.end()).toBe(""); }); // Test verifies that StringDecoder will correctly decode the given input @@ -91,7 +93,7 @@ function test(encoding, input, expected, singleSequence) { } sequences.forEach((sequence) => { const decoder = new StringDecoder(encoding); - let output = ''; + let output = ""; sequence.forEach((write) => { output += decoder.write(input.slice(write[0], write[1])); }); diff --git a/test/bun.js/tcp-server.test.ts b/test/bun.js/tcp-server.test.ts index 8b3b21820..65dd069a6 100644 --- a/test/bun.js/tcp-server.test.ts +++ b/test/bun.js/tcp-server.test.ts @@ -1,5 +1,5 @@ -import { listen, connect, finalizationCounter } from "bun"; -import { expect, describe, it } from "bun:test"; +import { listen, connect, TCPSocketListener } from "bun"; +import { expect, it } from "bun:test"; import * as JSC from "bun:jsc"; var decoder = new TextDecoder(); @@ -76,7 +76,7 @@ it("echo server 1 on 1", async () => { }, }; - var server = listen({ + var server: TCPSocketListener<any> | undefined = listen({ socket: handlers, hostname: "localhost", port: 8084, @@ -103,7 +103,7 @@ it("echo server 1 on 1", async () => { await new Promise((resolve, reject) => { setTimeout(() => { Bun.gc(true); - resolve(); + resolve(undefined); }, 1); }); diff --git a/test/bun.js/test_scope_debug.ts b/test/bun.js/test_scope_debug.ts index 9af649552..fbc79acd8 100644 --- a/test/bun.js/test_scope_debug.ts +++ b/test/bun.js/test_scope_debug.ts @@ -1,3 +1,4 @@ +type AnyFunction = (...args: any[]) => any; export function wrap({ test: test_, it: it_, @@ -6,12 +7,12 @@ export function wrap({ beforeAll: beforeAll_ = undefined, afterEach: afterEach_ = undefined, afterAll: afterAll_ = undefined, -}) { +}: any) { if (it_ === undefined) { it_ = test_; } - var describe = (label, cb) => { + var describe = (label, cb: AnyFunction) => { return describe_( label, cb instanceof async function () {}.constructor @@ -34,11 +35,11 @@ export function wrap({ } finally { console.log(`DESCRIBE [Exit] ${label}`); } - } + }, ); }; - var it = (label, cb) => { + var it = (label, cb: AnyFunction) => { console.log("Before", label); return it_( label, @@ -62,11 +63,11 @@ export function wrap({ } finally { console.log(`TEST [Exit] ${label}`); } - } + }, ); }; - var beforeEach = (cb) => { + var beforeEach = (cb: AnyFunction) => { return beforeEach_( cb instanceof async function () {}.constructor ? async () => { @@ -88,10 +89,10 @@ export function wrap({ } finally { console.log(`BEFORE EACH [Exit]`); } - } + }, ); }; - var beforeAll = (cb) => { + var beforeAll = (cb: AnyFunction) => { return beforeAll_( cb instanceof async function () {}.constructor ? async () => { @@ -113,10 +114,10 @@ export function wrap({ } finally { console.log(`BEFORE ALL [Exit]`); } - } + }, ); }; - var afterEach = (cb) => { + var afterEach = (cb: AnyFunction) => { return afterEach_( cb instanceof async function () {}.constructor ? async () => { @@ -138,10 +139,10 @@ export function wrap({ } finally { console.log(`AFTER EACH [Exit]`); } - } + }, ); }; - var afterAll = (cb) => { + var afterAll = (cb: AnyFunction) => { return afterAll_( cb instanceof async function () {}.constructor ? async () => { @@ -163,7 +164,7 @@ export function wrap({ } finally { console.log(`AFTER ALL [Exit]`); } - } + }, ); }; diff --git a/test/bun.js/text-decoder.test.js b/test/bun.js/text-decoder.test.js index 417a4c23a..2a88a8bc8 100644 --- a/test/bun.js/text-decoder.test.js +++ b/test/bun.js/text-decoder.test.js @@ -24,7 +24,7 @@ describe("TextDecoder", () => { const result = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]; gcTrace(true); expect(decoder.decode(Uint8Array.from(result))).toBe( - String.fromCharCode(...result) + String.fromCharCode(...result), ); gcTrace(true); }); diff --git a/test/bun.js/text-encoder.test.js b/test/bun.js/text-encoder.test.js index 2c8f9acf4..90255323f 100644 --- a/test/bun.js/text-encoder.test.js +++ b/test/bun.js/text-encoder.test.js @@ -175,12 +175,12 @@ describe("TextEncoder", () => { it(t.encoding + " - " + t.name, () => { gcTrace(true); expect( - new TextDecoder(t.encoding).decode(new Uint8Array(t.input)) + new TextDecoder(t.encoding).decode(new Uint8Array(t.input)), ).toBe(t.expected); expect( new TextDecoder(t.encoding).decode( - new Uint16Array(new Uint8Array(t.input).buffer) - ) + new Uint16Array(new Uint8Array(t.input).buffer), + ), ).toBe(t.expected); gcTrace(true); }); diff --git a/test/bun.js/toml.test.js b/test/bun.js/toml.test.js index 44141b2d4..900d30bf0 100644 --- a/test/bun.js/toml.test.js +++ b/test/bun.js/toml.test.js @@ -20,10 +20,10 @@ it("syntax", async () => { expect(toml.inline.array[1]).toBe(4); expect(toml.dev["foo.bar"]).toBe("baz"); expect(toml.install.scopes["@mybigcompany"].url).toBe( - "https://registry.mybigcompany.com" + "https://registry.mybigcompany.com", ); expect(toml.install.scopes["@mybigcompany2"].url).toBe( - "https://registry.mybigcompany.com" + "https://registry.mybigcompany.com", ); expect(toml.install.scopes["@mybigcompany3"].three).toBe(4); gc(); diff --git a/test/bun.js/transpiler.test.js b/test/bun.js/transpiler.test.js index 91803ef9b..c81b00ec5 100644 --- a/test/bun.js/transpiler.test.js +++ b/test/bun.js/transpiler.test.js @@ -68,7 +68,7 @@ describe("Bun.Transpiler", () => { it("normalizes \\r\\n", () => { ts.expectPrinted_( "console.log(`\r\n\r\n\r\n`)", - "console.log(`\n\n\n`);\n" + "console.log(`\n\n\n`);\n", ); }); @@ -76,14 +76,14 @@ describe("Bun.Transpiler", () => { it("import Foo = Baz.Bar", () => { ts.expectPrinted_( "import Foo = Baz.Bar;\nexport default Foo;", - "const Foo = Baz.Bar;\nexport default Foo" + "const Foo = Baz.Bar;\nexport default Foo", ); }); it("import Foo = require('bar')", () => { ts.expectPrinted_( "import React = require('react')", - 'const React = require("react")' + 'const React = require("react")', ); }); @@ -98,7 +98,7 @@ describe("Bun.Transpiler", () => { it("export import Foo = Baz.Bar", () => { ts.expectPrinted_( "export import Foo = Baz.Bar;", - "export const Foo = Baz.Bar" + "export const Foo = Baz.Bar", ); }); @@ -472,75 +472,75 @@ export default <>hi</> `export var foo = jsx("div", { foo: true }, undefined, false, undefined, this); -` +`, ); expect(bun.transformSync("export var foo = <div foo={foo} />")).toBe( `export var foo = jsx("div", { foo }, undefined, false, undefined, this); -` +`, ); expect(bun.transformSync("export var foo = <div {...foo} />")).toBe( `export var foo = jsx("div", { ...foo }, undefined, false, undefined, this); -` +`, ); expect(bun.transformSync("export var hi = <div {foo} />")).toBe( `export var hi = jsx("div", { foo }, undefined, false, undefined, this); -` +`, ); expect(bun.transformSync("export var hi = <div {foo.bar.baz} />")).toBe( `export var hi = jsx("div", { baz: foo.bar.baz }, undefined, false, undefined, this); -` +`, ); expect(bun.transformSync("export var hi = <div {foo?.bar?.baz} />")).toBe( `export var hi = jsx("div", { baz: foo?.bar?.baz }, undefined, false, undefined, this); -` +`, ); expect( - bun.transformSync("export var hi = <div {foo['baz'].bar?.baz} />") + bun.transformSync("export var hi = <div {foo['baz'].bar?.baz} />"), ).toBe( `export var hi = jsx("div", { baz: foo["baz"].bar?.baz }, undefined, false, undefined, this); -` +`, ); // cursed expect( bun.transformSync( - "export var hi = <div {foo[{name: () => true}.name].hi} />" - ) + "export var hi = <div {foo[{name: () => true}.name].hi} />", + ), ).toBe( `export var hi = jsx("div", { hi: foo[{ name: () => true }.name].hi }, undefined, false, undefined, this); -` +`, ); expect( - bun.transformSync("export var hi = <Foo {process.env.NODE_ENV} />") + bun.transformSync("export var hi = <Foo {process.env.NODE_ENV} />"), ).toBe( `export var hi = jsx(Foo, { NODE_ENV: "development" }, undefined, false, undefined, this); -` +`, ); expect( - bun.transformSync("export var hi = <div {foo['baz'].bar?.baz} />") + bun.transformSync("export var hi = <div {foo['baz'].bar?.baz} />"), ).toBe( `export var hi = jsx("div", { baz: foo["baz"].bar?.baz }, undefined, false, undefined, this); -` +`, ); try { bun.transformSync("export var hi = <div {foo}={foo}= />"); @@ -550,22 +550,22 @@ export default <>hi</> } expect( - bun.transformSync("export var hi = <div {Foo}><Foo></Foo></div>") + bun.transformSync("export var hi = <div {Foo}><Foo></Foo></div>"), ).toBe( `export var hi = jsx("div", { Foo, children: jsx(Foo, {}, undefined, false, undefined, this) }, undefined, false, undefined, this); -` +`, ); expect( - bun.transformSync("export var hi = <div {Foo}><Foo></Foo></div>") + bun.transformSync("export var hi = <div {Foo}><Foo></Foo></div>"), ).toBe( `export var hi = jsx("div", { Foo, children: jsx(Foo, {}, undefined, false, undefined, this) }, undefined, false, undefined, this); -` +`, ); expect(bun.transformSync("export var hi = <div>{123}}</div>").trim()).toBe( @@ -575,7 +575,7 @@ export default <>hi</> "}" ] }, undefined, true, undefined, this); - `.trim() + `.trim(), ); }); @@ -604,9 +604,9 @@ export var ComponentThatChecksDefaultProps = <Hello></Hello> export var ComponentThatChecksDefaultPropsAndHasChildren = <Hello>my child</Hello> export var ComponentThatHasSpreadCausesDeopt = <Hello {...spread} /> -`.trim() +`.trim(), ) - .trim() + .trim(), ).toBe( `var $$typeof = Symbol.for("react.element"); export var hi = { @@ -654,7 +654,7 @@ export var ComponentThatChecksDefaultPropsAndHasChildren = { export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { ...spread }); -`.trim() +`.trim(), ); }); }); @@ -662,25 +662,25 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { it("require with a dynamic non-string expression", () => { var nodeTranspiler = new Bun.Transpiler({ platform: "node" }); expect(nodeTranspiler.transformSync("require('hi' + bar)")).toBe( - 'require("hi" + bar);\n' + 'require("hi" + bar);\n', ); }); it("CommonJS", () => { var nodeTranspiler = new Bun.Transpiler({ platform: "node" }); expect(nodeTranspiler.transformSync("module.require('hi' + 123)")).toBe( - 'require("hi" + 123);\n' + 'require("hi" + 123);\n', ); expect( - nodeTranspiler.transformSync("module.require(1 ? 'foo' : 'bar')") + nodeTranspiler.transformSync("module.require(1 ? 'foo' : 'bar')"), ).toBe('require("foo");\n'); expect(nodeTranspiler.transformSync("require(1 ? 'foo' : 'bar')")).toBe( - 'require("foo");\n' + 'require("foo");\n', ); expect( - nodeTranspiler.transformSync("module.require(unknown ? 'foo' : 'bar')") + nodeTranspiler.transformSync("module.require(unknown ? 'foo' : 'bar')"), ).toBe('unknown ? require("foo") : require("bar");\n'); }); @@ -732,7 +732,7 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { code, trim = true, autoExport = false, - transpiler_ = transpiler + transpiler_ = transpiler, ) => { if (autoExport) { code = "export default (" + code + ")"; @@ -880,7 +880,7 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectPrinted_( "async function f() { await delete x }", - "async function f() {\n await delete x;\n}" + "async function f() {\n await delete x;\n}", ); // expectParseError( @@ -892,45 +892,45 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { it("import assert", () => { expectPrinted_( `import json from "./foo.json" assert { type: "json" };`, - `import json from "./foo.json"` + `import json from "./foo.json"`, ); expectPrinted_( `import json from "./foo.json";`, - `import json from "./foo.json"` + `import json from "./foo.json"`, ); expectPrinted_( `import("./foo.json", { type: "json" });`, - `import("./foo.json")` + `import("./foo.json")`, ); }); it("import with unicode escape", () => { expectPrinted_( `import { name } from 'mod\\u1011';`, - `import {name} from "mod\\u1011"` + `import {name} from "mod\\u1011"`, ); }); it("fold string addition", () => { expectPrinted_( `export const foo = "a" + "b";`, - `export const foo = "ab"` + `export const foo = "ab"`, ); expectPrinted_( `export const foo = "F" + "0" + "F" + "0123456789" + "ABCDEF" + "0123456789ABCDEFF0123456789ABCDEF00" + "b";`, - `export const foo = "F0F0123456789ABCDEF0123456789ABCDEFF0123456789ABCDEF00b"` + `export const foo = "F0F0123456789ABCDEF0123456789ABCDEFF0123456789ABCDEF00b"`, ); expectPrinted_( `export const foo = "a" + 1 + "b";`, - `export const foo = "a" + 1 + "b"` + `export const foo = "a" + 1 + "b"`, ); expectPrinted_( `export const foo = "a" + "b" + 1 + "b";`, - `export const foo = "ab" + 1 + "b"` + `export const foo = "ab" + 1 + "b"`, ); expectPrinted_( `export const foo = "a" + "b" + 1 + "b" + "c";`, - `export const foo = "ab" + 1 + "bc"` + `export const foo = "ab" + 1 + "bc"`, ); }); @@ -955,7 +955,7 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { return whatDidIPass(); } `, - object + object, ); expect(output).toBe(`export function foo() { return { @@ -972,11 +972,11 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { it("rewrite string to length", () => { expectPrinted_( `export const foo = "a".length + "b".length;`, - `export const foo = 1 + 1` + `export const foo = 1 + 1`, ); expectBunPrinted_( `export const foo = "a".length + "b".length;`, - `export const foo = 2` + `export const foo = 2`, ); }); @@ -984,21 +984,21 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { it("require -> import.meta.require", () => { expectBunPrinted_( `export const foo = require('bar.node')`, - `export const foo = import.meta.require("bar.node")` + `export const foo = import.meta.require("bar.node")`, ); }); it("require.resolve -> import.meta.resolveSync", () => { expectBunPrinted_( `export const foo = require.resolve('bar.node')`, - `export const foo = import.meta.resolveSync("bar.node")` + `export const foo = import.meta.resolveSync("bar.node")`, ); }); it('require.resolve(path, {paths: ["blah"]}) -> import.meta.resolveSync', () => { expectBunPrinted_( `export const foo = require.resolve('bar.node', {paths: ["blah"]})`, - `export const foo = import.meta.resolveSync("bar.node", { paths: ["blah"] })` + `export const foo = import.meta.resolveSync("bar.node", { paths: ["blah"] })`, ); }); }); @@ -1009,7 +1009,7 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { // so in this test, it becomes the same path string expectPrinted_( `export const foo = require.resolve('my-module')`, - `export const foo = "my-module"` + `export const foo = "my-module"`, ); }); }); @@ -1017,16 +1017,16 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { it("define", () => { expectPrinted_( `export default typeof user_undefined === 'undefined';`, - `export default true` + `export default true`, ); expectPrinted_( `export default typeof user_undefined !== 'undefined';`, - `export default false` + `export default false`, ); expectPrinted_( `export default typeof user_undefined !== 'undefined';`, - `export default false` + `export default false`, ); expectPrinted_(`export default !user_undefined;`, `export default true`); }); @@ -1055,15 +1055,15 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { // expectParseError("for (let x;;) ;", ""); expectParseError( "for (const x;;) ;", - 'The constant "x" must be initialized' + 'The constant "x" must be initialized', ); expectParseError( "for (const {};;) ;", - "This constant must be initialized" + "This constant must be initialized", ); expectParseError( "for (const [];;) ;", - "This constant must be initialized" + "This constant must be initialized", ); // Make sure bindings are visited during parsing @@ -1076,23 +1076,23 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectPrinted_( "export var foo = ([...x] = []) => {}", - "export var foo = ([...x] = []) => {\n}" + "export var foo = ([...x] = []) => {\n}", ); expectPrinted_( "export var foo = ({...x} = {}) => {}", - "export var foo = ({ ...x } = {}) => {\n}" + "export var foo = ({ ...x } = {}) => {\n}", ); expectParseError("var [...x,] = []", 'Unexpected "," after rest pattern'); expectParseError("var {...x,} = {}", 'Unexpected "," after rest pattern'); expectParseError( "export default function() { return ([...x,] = []) => {} }", - "Unexpected trailing comma after rest element" + "Unexpected trailing comma after rest element", ); expectParseError( "({...x,} = {}) => {}", - "Unexpected trailing comma after rest element" + "Unexpected trailing comma after rest element", ); expectPrinted_("[b, ...c] = d", "[b, ...c] = d"); @@ -1123,16 +1123,16 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectParseError("({x: ({})} = {x: {}})", "Invalid assignment target"); expectParseError( "(([]) = []) => {}", - "Unexpected parentheses in binding pattern" + "Unexpected parentheses in binding pattern", ); expectParseError( "(({}) = {}) => {}", - "Unexpected parentheses in binding pattern" + "Unexpected parentheses in binding pattern", ); expectParseError("function f(([]) = []) {}", "Parse error"); expectParseError( "function f(({}) = {}) {}", - "Parse error" + "Parse error", // 'Expected identifier but found "("\n' ); @@ -1154,11 +1154,11 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectParseError("[{...a, b}] = c", 'Unexpected "," after rest pattern'); expectParseError( "({x: [...a, b]} = c)", - 'Unexpected "," after rest pattern' + 'Unexpected "," after rest pattern', ); expectParseError( "({x: {...a, b}} = c)", - 'Unexpected "," after rest pattern' + 'Unexpected "," after rest pattern', ); expectParseError("[b, ...c,] = d", 'Unexpected "," after rest pattern'); expectParseError("([b, ...c,] = d)", 'Unexpected "," after rest pattern'); @@ -1169,11 +1169,11 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectPrinted_( "for ([{a = {}}] in b) {}", - "for ([{ a = {} }] in b) {\n}" + "for ([{ a = {} }] in b) {\n}", ); expectPrinted_( "for ([{a = {}}] of b) {}", - "for ([{ a = {} }] of b) {\n}" + "for ([{ a = {} }] of b) {\n}", ); expectPrinted_("for ({a = {}} in b) {}", "for ({ a = {} } in b) {\n}"); expectPrinted_("for ({a = {}} of b) {}", "for ({ a = {} } of b) {\n}"); @@ -1182,11 +1182,11 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectParseError("[{a = {}}]\nof()", 'Unexpected "="'); expectParseError( "for ([...a, b] in c) {}", - 'Unexpected "," after rest pattern' + 'Unexpected "," after rest pattern', ); expectParseError( "for ([...a, b] of c) {}", - 'Unexpected "," after rest pattern' + 'Unexpected "," after rest pattern', ); }); @@ -1202,7 +1202,7 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectParseError( "/x/msuygig", - 'Duplicate flag "g" in regular expression' + 'Duplicate flag "g" in regular expression', ); }); @@ -1210,11 +1210,11 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectPrinted_("var _\u0076\u0061\u0072", "var _var"); expectParseError( "var \u0076\u0061\u0072", - 'Expected identifier but found "\u0076\u0061\u0072"' + 'Expected identifier but found "\u0076\u0061\u0072"', ); expectParseError( "\\u0076\\u0061\\u0072 foo", - "Unexpected \\u0076\\u0061\\u0072" + "Unexpected \\u0076\\u0061\\u0072", ); expectPrinted_("foo._\u0076\u0061\u0072", "foo._var"); @@ -1233,108 +1233,108 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectParseError("({ #foo: 1 })", 'Expected identifier but found "#foo"'); expectParseError( "class Foo { x = { #foo: 1 } }", - 'Expected identifier but found "#foo"' + 'Expected identifier but found "#foo"', ); expectParseError("class Foo { x = #foo }", 'Expected "in" but found "}"'); expectParseError( "class Foo { #foo; foo() { delete this.#foo } }", - 'Deleting the private name "#foo" is forbidden' + 'Deleting the private name "#foo" is forbidden', ); expectParseError( "class Foo { #foo; foo() { delete this?.#foo } }", - 'Deleting the private name "#foo" is forbidden' + 'Deleting the private name "#foo" is forbidden', ); expectParseError( "class Foo extends Bar { #foo; foo() { super.#foo } }", - 'Expected identifier but found "#foo"' + 'Expected identifier but found "#foo"', ); expectParseError( "class Foo { #foo = () => { for (#foo in this) ; } }", - "Unexpected #foo" + "Unexpected #foo", ); expectParseError( "class Foo { #foo = () => { for (x = #foo in this) ; } }", - "Unexpected #foo" + "Unexpected #foo", ); expectPrinted_("class Foo { #foo }", "class Foo {\n #foo;\n}"); expectPrinted_("class Foo { #foo = 1 }", "class Foo {\n #foo = 1;\n}"); expectPrinted_( "class Foo { #foo = #foo in this }", - "class Foo {\n #foo = #foo in this;\n}" + "class Foo {\n #foo = #foo in this;\n}", ); expectPrinted_( "class Foo { #foo = #foo in (#bar in this); #bar }", - "class Foo {\n #foo = #foo in (#bar in this);\n #bar;\n}" + "class Foo {\n #foo = #foo in (#bar in this);\n #bar;\n}", ); expectPrinted_( "class Foo { #foo() {} }", - "class Foo {\n #foo() {\n }\n}" + "class Foo {\n #foo() {\n }\n}", ); expectPrinted_( "class Foo { get #foo() {} }", - "class Foo {\n get #foo() {\n }\n}" + "class Foo {\n get #foo() {\n }\n}", ); expectPrinted_( "class Foo { set #foo(x) {} }", - "class Foo {\n set #foo(x) {\n }\n}" + "class Foo {\n set #foo(x) {\n }\n}", ); expectPrinted_( "class Foo { static #foo }", - "class Foo {\n static #foo;\n}" + "class Foo {\n static #foo;\n}", ); expectPrinted_( "class Foo { static #foo = 1 }", - "class Foo {\n static #foo = 1;\n}" + "class Foo {\n static #foo = 1;\n}", ); expectPrinted_( "class Foo { static #foo() {} }", - "class Foo {\n static #foo() {\n }\n}" + "class Foo {\n static #foo() {\n }\n}", ); expectPrinted_( "class Foo { static get #foo() {} }", - "class Foo {\n static get #foo() {\n }\n}" + "class Foo {\n static get #foo() {\n }\n}", ); expectPrinted_( "class Foo { static set #foo(x) {} }", - "class Foo {\n static set #foo(x) {\n }\n}" + "class Foo {\n static set #foo(x) {\n }\n}", ); expectParseError( "class Foo { #foo = #foo in #bar in this; #bar }", - "Unexpected #bar" + "Unexpected #bar", ); expectParseError( "class Foo { #constructor }", - 'Invalid field name "#constructor"' + 'Invalid field name "#constructor"', ); expectParseError( "class Foo { #constructor() {} }", - 'Invalid method name "#constructor"' + 'Invalid method name "#constructor"', ); expectParseError( "class Foo { static #constructor }", - 'Invalid field name "#constructor"' + 'Invalid field name "#constructor"', ); expectParseError( "class Foo { static #constructor() {} }", - 'Invalid method name "#constructor"' + 'Invalid method name "#constructor"', ); expectParseError( "class Foo { #\\u0063onstructor }", - 'Invalid field name "#constructor"' + 'Invalid field name "#constructor"', ); expectParseError( "class Foo { #\\u0063onstructor() {} }", - 'Invalid method name "#constructor"' + 'Invalid method name "#constructor"', ); expectParseError( "class Foo { static #\\u0063onstructor }", - 'Invalid field name "#constructor"' + 'Invalid field name "#constructor"', ); expectParseError( "class Foo { static #\\u0063onstructor() {} }", - 'Invalid method name "#constructor"' + 'Invalid method name "#constructor"', ); const errorText = '"#foo" has already been declared'; expectParseError("class Foo { #foo; #foo }", errorText); @@ -1350,44 +1350,44 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectParseError("class Foo { set #foo(x) {} set #foo(x) {} }", errorText); expectParseError( "class Foo { get #foo() {} set #foo(x) {} #foo }", - errorText + errorText, ); expectParseError( "class Foo { set #foo(x) {} get #foo() {} #foo }", - errorText + errorText, ); expectPrinted_( "class Foo { get #foo() {} set #foo(x) { this.#foo } }", - "class Foo {\n get #foo() {\n }\n set #foo(x) {\n this.#foo;\n }\n}" + "class Foo {\n get #foo() {\n }\n set #foo(x) {\n this.#foo;\n }\n}", ); expectPrinted_( "class Foo { set #foo(x) { this.#foo } get #foo() {} }", - "class Foo {\n set #foo(x) {\n this.#foo;\n }\n get #foo() {\n }\n}" + "class Foo {\n set #foo(x) {\n this.#foo;\n }\n get #foo() {\n }\n}", ); expectPrinted_( "class Foo { #foo } class Bar { #foo }", - "class Foo {\n #foo;\n}\n\nclass Bar {\n #foo;\n}" + "class Foo {\n #foo;\n}\n\nclass Bar {\n #foo;\n}", ); expectPrinted_( "class Foo { foo = this.#foo; #foo }", - "class Foo {\n foo = this.#foo;\n #foo;\n}" + "class Foo {\n foo = this.#foo;\n #foo;\n}", ); expectPrinted_( "class Foo { foo = this?.#foo; #foo }", - "class Foo {\n foo = this?.#foo;\n #foo;\n}" + "class Foo {\n foo = this?.#foo;\n #foo;\n}", ); expectParseError( "class Foo { #foo } class Bar { foo = this.#foo }", - 'Private name "#foo" must be declared in an enclosing class' + 'Private name "#foo" must be declared in an enclosing class', ); expectParseError( "class Foo { #foo } class Bar { foo = this?.#foo }", - 'Private name "#foo" must be declared in an enclosing class' + 'Private name "#foo" must be declared in an enclosing class', ); expectParseError( "class Foo { #foo } class Bar { foo = #foo in this }", - 'Private name "#foo" must be declared in an enclosing class' + 'Private name "#foo" must be declared in an enclosing class', ); expectPrinted_( @@ -1421,7 +1421,7 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { } }; } -}` +}`, ); }); @@ -1434,63 +1434,63 @@ export var ComponentThatHasSpreadCausesDeopt = jsx(Hello, { expectPrinted_("export type {default} from 'bar'", ""); expectPrinted_( "export { type } from 'mod'; type", - 'export { type } from "mod";\ntype' + 'export { type } from "mod";\ntype', ); expectPrinted_( "export { type, as } from 'mod'", - 'export { type, as } from "mod"' + 'export { type, as } from "mod"', ); expectPrinted_( "export { x, type foo } from 'mod'; x", - 'export { x } from "mod";\nx' + 'export { x } from "mod";\nx', ); expectPrinted_( "export { x, type as } from 'mod'; x", - 'export { x } from "mod";\nx' + 'export { x } from "mod";\nx', ); expectPrinted_( "export { x, type foo as bar } from 'mod'; x", - 'export { x } from "mod";\nx' + 'export { x } from "mod";\nx', ); expectPrinted_( "export { x, type foo as as } from 'mod'; x", - 'export { x } from "mod";\nx' + 'export { x } from "mod";\nx', ); expectPrinted_( "export { type as as } from 'mod'; as", - 'export { type as as } from "mod";\nas' + 'export { type as as } from "mod";\nas', ); expectPrinted_( "export { type as foo } from 'mod'; foo", - 'export { type as foo } from "mod";\nfoo' + 'export { type as foo } from "mod";\nfoo', ); expectPrinted_( "export { type as type } from 'mod'; type", - 'export { type } from "mod";\ntype' + 'export { type } from "mod";\ntype', ); expectPrinted_( "export { x, type as as foo } from 'mod'; x", - 'export { x } from "mod";\nx' + 'export { x } from "mod";\nx', ); expectPrinted_( "export { x, type as as as } from 'mod'; x", - 'export { x } from "mod";\nx' + 'export { x } from "mod";\nx', ); expectPrinted_( "export { x, type type as as } from 'mod'; x", - 'export { x } from "mod";\nx' + 'export { x } from "mod";\nx', ); expectPrinted_( "export { x, \\u0074ype y }; let x, y", - "export { x };\nlet x, y" + "export { x };\nlet x, y", ); expectPrinted_( "export { x, \\u0074ype y } from 'mod'", - 'export { x } from "mod"' + 'export { x } from "mod"', ); expectPrinted_( "export { x, type if } from 'mod'", - 'export { x } from "mod"' + 'export { x } from "mod"', ); expectPrinted_("export { x, type y as if }; let x", "export { x };\nlet x"); expectPrinted_("export { type x };", ""); @@ -1519,78 +1519,78 @@ class Foo { } bar; } -`.trim() +`.trim(), ); }); it("class static blocks", () => { expectPrinted_( "class Foo { static {} }", - "class Foo {\n static {\n }\n}" + "class Foo {\n static {\n }\n}", ); expectPrinted_( "class Foo { static {} x = 1 }", - "class Foo {\n static {\n }\n x = 1;\n}" + "class Foo {\n static {\n }\n x = 1;\n}", ); expectPrinted_( "class Foo { static { this.foo() } }", - "class Foo {\n static {\n this.foo();\n }\n}" + "class Foo {\n static {\n this.foo();\n }\n}", ); expectParseError( "class Foo { static { yield } }", - '"yield" is a reserved word and cannot be used in strict mode' + '"yield" is a reserved word and cannot be used in strict mode', ); expectParseError( "class Foo { static { await } }", - 'The keyword "await" cannot be used here' + 'The keyword "await" cannot be used here', ); expectParseError( "class Foo { static { return } }", - "A return statement cannot be used here" + "A return statement cannot be used here", ); expectParseError( "class Foo { static { break } }", - 'Cannot use "break" here' + 'Cannot use "break" here', ); expectParseError( "class Foo { static { continue } }", - 'Cannot use "continue" here' + 'Cannot use "continue" here', ); expectParseError( "x: { class Foo { static { break x } } }", - 'There is no containing label named "x"' + 'There is no containing label named "x"', ); expectParseError( "x: { class Foo { static { continue x } } }", - 'There is no containing label named "x"' + 'There is no containing label named "x"', ); expectParseError( "class Foo { get #x() { this.#x = 1 } }", - 'Writing to getter-only property "#x" will throw' + 'Writing to getter-only property "#x" will throw', ); expectParseError( "class Foo { get #x() { this.#x += 1 } }", - 'Writing to getter-only property "#x" will throw' + 'Writing to getter-only property "#x" will throw', ); expectParseError( "class Foo { set #x(x) { this.#x } }", - 'Reading from setter-only property "#x" will throw' + 'Reading from setter-only property "#x" will throw', ); expectParseError( "class Foo { set #x(x) { this.#x += 1 } }", - 'Reading from setter-only property "#x" will throw' + 'Reading from setter-only property "#x" will throw', ); // Writing to method warnings expectParseError( "class Foo { #x() { this.#x = 1 } }", - 'Writing to read-only method "#x" will throw' + 'Writing to read-only method "#x" will throw', ); expectParseError( "class Foo { #x() { this.#x += 1 } }", - 'Writing to read-only method "#x" will throw' + 'Writing to read-only method "#x" will throw', ); }); diff --git a/test/bun.js/tsconfig.json b/test/bun.js/tsconfig.json index 975c49fe4..4763c09e6 100644 --- a/test/bun.js/tsconfig.json +++ b/test/bun.js/tsconfig.json @@ -1,15 +1,16 @@ { + "extends": "../../tsconfig.base.json", "compilerOptions": { - "lib": ["ESNext"], - "module": "esnext", - "target": "esnext", - "noEmit": true, - "allowJs": true, - "types": ["bun-types"], "allowSyntheticDefaultImports": true, - "baseUrl": ".", "paths": { - "foo/bar": ["baz.js"] - } - } -} + "foo/bar": [ + "baz.js" + ] + }, + "baseUrl": "." + }, + "exclude": [ + "solid-dom-fixtures", + "bundled" + ] +}
\ No newline at end of file diff --git a/test/bun.js/url.test.ts b/test/bun.js/url.test.ts index 87291a09c..f7ad84752 100644 --- a/test/bun.js/url.test.ts +++ b/test/bun.js/url.test.ts @@ -3,38 +3,21 @@ import { describe, it, expect } from "bun:test"; describe("url", () => { it("prints", () => { expect(Bun.inspect(new URL("https://example.com"))).toBe( - "https://example.com/" + "https://example.com/", ); expect( Bun.inspect( new URL( - "https://github.com/oven-sh/bun/issues/135?hello%20i%20have%20spaces%20thank%20you%20good%20night" - ) - ) + "https://github.com/oven-sh/bun/issues/135?hello%20i%20have%20spaces%20thank%20you%20good%20night", + ), + ), ).toBe( - "https://github.com/oven-sh/bun/issues/135?hello%20i%20have%20spaces%20thank%20you%20good%20night" + "https://github.com/oven-sh/bun/issues/135?hello%20i%20have%20spaces%20thank%20you%20good%20night", ); }); it("works", () => { - const inputs: [ - [ - string, - { - hash: string; - host: string; - hostname: string; - href: string; - origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - username: string; - } - ] - ] = [ + const inputs = [ [ "https://username:password@api.foo.bar.com:9999/baz/okay/i/123?ran=out&of=things#to-use-as-a-placeholder", { @@ -83,7 +66,7 @@ describe("url", () => { username: "", }, ], - ]; + ] as const; for (let [url, values] of inputs) { const result = new URL(url); diff --git a/test/bun.js/util/util-promisify.test.js b/test/bun.js/util/util-promisify.test.js index 251de0cc6..067751321 100644 --- a/test/bun.js/util/util-promisify.test.js +++ b/test/bun.js/util/util-promisify.test.js @@ -21,10 +21,10 @@ // Tests adapted from https://github.com/nodejs/node/blob/main/test/parallel/test-util-promisify.js import { describe, it } from "bun:test"; -import fs from 'node:fs'; +import fs from "node:fs"; // TODO: vm module not implemented by bun yet // import vm from 'node:vm'; -import { promisify } from 'util'; +import { promisify } from "util"; import assert from "assert"; const stat = promisify(fs.stat); @@ -34,10 +34,10 @@ function invalidArgTypeHelper(input) { if (input == null) { return ` Received ${input}`; } - if (typeof input === 'function' && input.name) { + if (typeof input === "function" && input.name) { return ` Received function ${input.name}`; } - if (typeof input === 'object') { + if (typeof input === "object") { if (input.constructor?.name) { return ` Received an instance of ${input.constructor.name}`; } @@ -45,7 +45,9 @@ function invalidArgTypeHelper(input) { } let inspected = inspect(input, { colors: false }); - if (inspected.length > 28) { inspected = `${inspected.slice(inspected, 0, 25)}...`; } + if (inspected.length > 28) { + inspected = `${inspected.slice(inspected, 0, 25)}...`; + } return ` Received type ${typeof input} (${inspected})`; } @@ -57,18 +59,23 @@ describe("util.promisify", () => { it.skip("all cases", () => { const promise = stat(__filename); assert.equal(promise instanceof Promise, true); - promise.then(common.mustCall((value) => { - assert.deepStrictEqual(value, fs.statSync(__filename)); - })); - - - const promiseFileDontExist = stat('/dontexist'); - promiseFileDontExist.catch(common.mustCall((error) => { - assert(error.message.includes('ENOENT: no such file or directory, stat')); - })); - }) - }) - + promise.then( + common.mustCall((value) => { + assert.deepStrictEqual(value, fs.statSync(__filename)); + }), + ); + + const promiseFileDontExist = stat("/dontexist"); + promiseFileDontExist.catch( + common.mustCall((error) => { + assert( + error.message.includes("ENOENT: no such file or directory, stat"), + ); + }), + ); + }); + }); + describe("promisify.custom", () => { it("double promisify", () => { function fn() {} @@ -77,7 +84,7 @@ describe("util.promisify", () => { fn[promisify.custom] = promisifedFn; assert.strictEqual(promisify(fn), promisifedFn); assert.strictEqual(promisify(promisify(fn)), promisifedFn); - }) + }); it.skip("should register shared promisify symbol", () => { function fn() {} @@ -87,14 +94,16 @@ describe("util.promisify", () => { // TODO: register shared symbol promisify.custom // util.promisify.custom is a shared symbol which can be accessed // as `Symbol.for("nodejs.util.promisify.custom")`. - const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom'); + const kCustomPromisifiedSymbol = Symbol.for( + "nodejs.util.promisify.custom", + ); fn[kCustomPromisifiedSymbol] = promisifiedFn; assert.strictEqual(kCustomPromisifiedSymbol, promisify.custom); assert.strictEqual(promisify(fn), promisifiedFn); assert.strictEqual(promisify(promisify(fn)), promisifiedFn); - }) - }) + }); + }); it("should fail when type is not a function", () => { function fn() {} @@ -103,28 +112,28 @@ describe("util.promisify", () => { () => promisify(fn), // TODO: error code is not the same as node's. // { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' } - { name: 'TypeError' } + { name: "TypeError" }, ); - }) - + }); + it("should call custom promised promised function with proper args", () => { const firstValue = 5; const secondValue = 17; var called = false; function fn(callback) { - called = true + called = true; callback(null, firstValue, secondValue); } - fn[Symbol('customPromisifyArgs')] = ['first', 'second']; + fn[Symbol("customPromisifyArgs")] = ["first", "second"]; promisify(fn)().then((firstValue, secondValue) => { assert.strictEqual(called, true); assert.strictEqual(firstValue, 5); assert.strictEqual(secondValue, 17); }); - }) + }); // TODO: unable to test since vm module not implemented // it("should run in new vm context", () => { @@ -133,17 +142,17 @@ describe("util.promisify", () => { // }); describe("callback cases", () => { - it('should run basic callback', async () => { + it("should run basic callback", async () => { var called = false; function fn(callback) { called = true; - callback(null, 'foo', 'bar'); + callback(null, "foo", "bar"); } await promisify(fn)().then((value) => { - assert.strictEqual(value, 'foo'); + assert.strictEqual(value, "foo"); assert.strictEqual(called, true); }); - }) + }); it("should not require value to be returned in callback", async () => { var called = false; @@ -155,7 +164,7 @@ describe("util.promisify", () => { assert.strictEqual(value, undefined); assert.strictEqual(called, true); }); - }) + }); it("should not require error to be passed", async () => { var called = false; @@ -167,7 +176,7 @@ describe("util.promisify", () => { assert.strictEqual(value, undefined); assert.strictEqual(called, true); }); - }) + }); it("custom callback", async () => { var called = false; @@ -179,7 +188,7 @@ describe("util.promisify", () => { assert.strictEqual(value, 42); assert.strictEqual(called, true); }); - }) + }); it("should catch error", async () => { var called = false; @@ -187,12 +196,12 @@ describe("util.promisify", () => { called = true; callback(err, val); } - await promisify(fn)(new Error('oops'), null).catch(err => { - assert.strictEqual(err.message, 'oops') + await promisify(fn)(new Error("oops"), null).catch((err) => { + assert.strictEqual(err.message, "oops"); assert.strictEqual(called, true); }); - }) - + }); + it("should call promisify properly inside async block", async () => { var called = false; function fn(err, val, callback) { @@ -206,12 +215,12 @@ describe("util.promisify", () => { })().then(() => { assert.strictEqual(called, true); }); - }) + }); it("should not break this reference", async () => { const o = {}; var called = false; - const fn = promisify(function(cb) { + const fn = promisify(function (cb) { called = true; cb(null, this === o); }); @@ -219,22 +228,24 @@ describe("util.promisify", () => { o.fn = fn; await o.fn().then((val) => { - assert.strictEqual(called, true) + assert.strictEqual(called, true); assert.strictEqual(val, true); }); - }) + }); - it("should not have called callback with error", async() => { - const err = new Error('Should not have called the callback with the error.'); + it("should not have called callback with error", async () => { + const err = new Error( + "Should not have called the callback with the error.", + ); const stack = err.stack; var called = false; - - const fn = promisify(function(cb) { + + const fn = promisify(function (cb) { called = true; cb(null); cb(err); }); - + await (async () => { await fn(); await Promise.resolve(); @@ -242,58 +253,58 @@ describe("util.promisify", () => { })().then(() => { assert.strictEqual(called, true); }); - }) - - it('should compare promised objects properly', () => { - function c() { } - const a = promisify(function() { }); + }); + + it("should compare promised objects properly", () => { + function c() {} + const a = promisify(function () {}); const b = promisify(a); assert.notStrictEqual(c, a); assert.strictEqual(a, b); - }) + }); it("should throw error", async () => { let errToThrow; - const thrower = promisify(function(a, b, c, cb) { + const thrower = promisify(function (a, b, c, cb) { errToThrow = new Error(); throw errToThrow; }); await thrower(1, 2, 3) .then(assert.fail) .then(assert.fail, (e) => assert.strictEqual(e, errToThrow)); - }) + }); it("should also throw error inside Promise.all", async () => { const err = new Error(); const a = promisify((cb) => cb(err))(); - const b = promisify(() => { throw err; })(); + const b = promisify(() => { + throw err; + })(); await Promise.all([ - a.then(assert.fail, function(e) { + a.then(assert.fail, function (e) { assert.strictEqual(err, e); }), - b.then(assert.fail, function(e) { + b.then(assert.fail, function (e) { assert.strictEqual(err, e); }), ]); - }) - }) + }); + }); describe("invalid input", () => { // This test is failing because 'code' property // is not thrown in the error. does it have different // throw error implementation in bun? it("should throw on invalid inputs for promisify", () => { - [undefined, null, true, 0, 'str', {}, [], Symbol()].forEach((input) => { - assert.throws( - () => promisify(input), - { - code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError', - message: 'The "original" argument must be of type Function' - }); + [undefined, null, true, 0, "str", {}, [], Symbol()].forEach((input) => { + assert.throws(() => promisify(input), { + code: "ERR_INVALID_ARG_TYPE", + name: "TypeError", + message: 'The "original" argument must be of type Function', + }); }); - }) - }) + }); + }); }); diff --git a/test/bun.js/util/util.test.js b/test/bun.js/util/util.test.js index 15d3cd221..ded15a435 100644 --- a/test/bun.js/util/util.test.js +++ b/test/bun.js/util/util.test.js @@ -112,7 +112,7 @@ describe("util", () => { strictEqual(util.isPrimitive(/regexp/), false); strictEqual( util.isPrimitive(function () {}), - false + false, ); strictEqual(util.isPrimitive(new Number(1)), false); strictEqual(util.isPrimitive(new String("bla")), false); @@ -210,11 +210,11 @@ describe("util", () => { it("all cases", () => { strictEqual( util.isFunction(() => {}), - true + true, ); strictEqual( util.isFunction(function () {}), - true + true, ); strictEqual(util.isFunction(), false); strictEqual(util.isFunction("string"), false); @@ -236,7 +236,7 @@ describe("util", () => { strictEqual(util.types.isNativeError({}), false); strictEqual( util.types.isNativeError({ name: "Error", message: "" }), - false + false, ); strictEqual(util.types.isNativeError([]), false); // strictEqual( // FIXME: failing test @@ -263,7 +263,7 @@ describe("util", () => { expect(util.TextEncoder === globalThis.TextEncoder).toBe(true); }); }); - + describe("TextDecoder", () => { // test/bun.js/text-decoder.test.js covers test cases for TextDecoder // here we test only if we use the same via util.TextDecoder diff --git a/test/bun.js/web-crypto.test.ts b/test/bun.js/web-crypto.test.ts index 72730f8ff..19d068180 100644 --- a/test/bun.js/web-crypto.test.ts +++ b/test/bun.js/web-crypto.test.ts @@ -13,7 +13,7 @@ describe("Web Crypto", () => { length: 256, }, true, - ["encrypt", "decrypt"] + ["encrypt", "decrypt"], ); const iv = crypto.getRandomValues(new Uint8Array(12)); const data = new TextEncoder().encode("Hello World!"); @@ -23,7 +23,7 @@ describe("Web Crypto", () => { iv, }, key, - data + data, ); const decrypted = await crypto.subtle.decrypt( { @@ -31,7 +31,7 @@ describe("Web Crypto", () => { iv, }, key, - encrypted + encrypted, ); expect(new TextDecoder().decode(decrypted)).toBe("Hello World!"); }); @@ -43,7 +43,7 @@ describe("Web Crypto", () => { new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, - ["sign", "verify"] + ["sign", "verify"], ); } @@ -52,7 +52,7 @@ describe("Web Crypto", () => { const signature = await crypto.subtle.sign( "HMAC", key, - new TextEncoder().encode(message) + new TextEncoder().encode(message), ); // Convert ArrayBuffer to Base64 @@ -69,7 +69,7 @@ describe("Web Crypto", () => { "HMAC", key, sigBuf, - new TextEncoder().encode(message) + new TextEncoder().encode(message), ); } diff --git a/test/bun.js/web-globals.test.js b/test/bun.js/web-globals.test.js index afcded6db..2f966aa03 100644 --- a/test/bun.js/web-globals.test.js +++ b/test/bun.js/web-globals.test.js @@ -54,7 +54,7 @@ it("crypto.getRandomValues", () => { var array = crypto.getRandomValues(foo); expect(array).toBe(foo); expect(array.reduce((sum, a) => (sum += a === 0), 0) != foo.length).toBe( - true + true, ); } @@ -66,7 +66,7 @@ it("crypto.getRandomValues", () => { // run it on a large input expect( - !!crypto.getRandomValues(new Uint8Array(8096)).find((a) => a > 0) + !!crypto.getRandomValues(new Uint8Array(8096)).find((a) => a > 0), ).toBe(true); { @@ -74,7 +74,7 @@ it("crypto.getRandomValues", () => { var array = crypto.getRandomValues(foo, "unbuffered"); expect(array).toBe(foo); expect(array.reduce((sum, a) => (sum += a === 0), 0) != foo.length).toBe( - true + true, ); } }); diff --git a/test/bun.js/websocket-server.test.ts b/test/bun.js/websocket-server.test.ts index 7c7869fad..dd88d6707 100644 --- a/test/bun.js/websocket-server.test.ts +++ b/test/bun.js/websocket-server.test.ts @@ -1,6 +1,6 @@ import { serve } from "bun"; import { describe, expect, it } from "bun:test"; -import { gcTick } from "gc"; +import { gcTick } from "./gc"; var port = 4321; function getPort() { @@ -25,7 +25,7 @@ describe("websocket server", () => { close(ws) { ws[method]( "all", - method === "publishBinary" ? Buffer.from("bye!") : "bye!" + method === "publishBinary" ? Buffer.from("bye!") : "bye!", ); }, }, @@ -39,16 +39,16 @@ describe("websocket server", () => { }); try { - const first = await new Promise((resolve2, reject2) => { + const first = await new Promise<WebSocket>((resolve2, reject2) => { var socket = new WebSocket( - `ws://${server.hostname}:${server.port}` + `ws://${server.hostname}:${server.port}`, ); socket.onopen = () => resolve2(socket); }); - const second = await new Promise((resolve2, reject2) => { + const second = await new Promise<WebSocket>((resolve2, reject2) => { var socket = new WebSocket( - `ws://${server.hostname}:${server.port}` + `ws://${server.hostname}:${server.port}`, ); socket.onmessage = (ev) => { var msg = ev.data; @@ -107,7 +107,7 @@ describe("websocket server", () => { }, }); - await new Promise((resolve_, reject) => { + await new Promise<void>((resolve_, reject) => { resolve = resolve_; const websocket = new WebSocket(`ws://${server.hostname}:${server.port}`); websocket.onopen = () => { @@ -138,8 +138,7 @@ describe("websocket server", () => { if ( server.upgrade(req, { data: "hello world", - - headers: 1238, + headers: 1238 as any, }) ) { reject(); @@ -155,7 +154,7 @@ describe("websocket server", () => { }, }); - await new Promise((resolve_, reject) => { + await new Promise<void>((resolve_, reject) => { resolve = resolve_; const websocket = new WebSocket(`ws://${server.hostname}:${server.port}`); websocket.onopen = () => websocket.close(); @@ -194,7 +193,7 @@ describe("websocket server", () => { }, }); - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { const websocket = new WebSocket(`ws://${server.hostname}:${server.port}`); websocket.onopen = () => { websocket.send("hello world"); @@ -253,7 +252,7 @@ describe("websocket server", () => { }, }); - return new Promise((resolve, reject) => { + return new Promise<void>((resolve, reject) => { const websocket = new WebSocket(`ws://${server.hostname}:${server.port}`); websocket.onopen = () => { websocket.send("hello world"); @@ -312,7 +311,7 @@ describe("websocket server", () => { return new Response("noooooo hello world"); }, }); - return new Promise((resolve, reject) => { + return new Promise<void>((resolve, reject) => { const websocket = new WebSocket(`ws://${server.hostname}:${server.port}`); websocket.onopen = () => { websocket.send("hello world"); @@ -367,7 +366,7 @@ describe("websocket server", () => { }, }); - await new Promise((resolve, reject) => { + await new Promise<boolean>((resolve, reject) => { var counter = 0; const websocket = new WebSocket(`ws://${server.hostname}:${server.port}`); websocket.onopen = () => { @@ -399,7 +398,7 @@ describe("websocket server", () => { }); it("does not upgrade for non-websocket connections", async () => { - await new Promise(async (resolve, reject) => { + await new Promise<void>(async (resolve, reject) => { var server = serve({ port: getPort(), websocket: { @@ -425,7 +424,7 @@ describe("websocket server", () => { }); it("does not upgrade for non-websocket servers", async () => { - await new Promise(async (resolve, reject) => { + await new Promise<void>(async (resolve, reject) => { var server = serve({ port: getPort(), @@ -465,7 +464,7 @@ describe("websocket server", () => { }, }); - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { const websocket = new WebSocket(`ws://${server.hostname}:${server.port}`); websocket.onmessage = (e) => { @@ -487,7 +486,7 @@ describe("websocket server", () => { }); it("publishText()", async () => { - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { var server = serve({ port: getPort(), websocket: { @@ -515,7 +514,7 @@ describe("websocket server", () => { it("publishBinary()", async () => { const bytes = Buffer.from("hello"); - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { var server = serve({ port: getPort(), websocket: { @@ -542,7 +541,7 @@ describe("websocket server", () => { }); it("sendText()", async () => { - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { var server = serve({ port: getPort(), websocket: { @@ -570,7 +569,7 @@ describe("websocket server", () => { it("sendBinary()", async () => { const bytes = Buffer.from("hello"); - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { var server = serve({ port: getPort(), websocket: { @@ -616,7 +615,7 @@ describe("websocket server", () => { }, }); - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { const websocket = new WebSocket(`ws://${server.hostname}:${server.port}`); websocket.onmessage = (e) => { @@ -654,14 +653,14 @@ describe("websocket server", () => { fetch(req, server) { if ( server.upgrade(req, { - count: 0, + data: { count: 0 }, }) ) return new Response("noooooo hello world"); }, }); - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { const websocket = new WebSocket(`ws://${server.hostname}:${server.port}`); websocket.onerror = (e) => { reject(e); @@ -708,7 +707,7 @@ describe("websocket server", () => { it("send rope strings", async () => { var ropey = "hello world".repeat(10); - var sendQueue = []; + var sendQueue: any[] = []; for (var i = 0; i < 100; i++) { sendQueue.push(ropey + " " + i); } @@ -737,7 +736,7 @@ describe("websocket server", () => { }, }); - await new Promise((resolve, reject) => { + await new Promise<void>((resolve, reject) => { const websocket = new WebSocket(`ws://${server.hostname}:${server.port}`); websocket.onerror = (e) => { reject(e); @@ -771,7 +770,7 @@ describe("websocket server", () => { // this test sends 100 messages to 10 connected clients via pubsub it("pub/sub", async () => { var ropey = "hello world".repeat(10); - var sendQueue = []; + var sendQueue: any[] = []; for (var i = 0; i < 100; i++) { sendQueue.push(ropey + " " + i); gcTick(); @@ -817,7 +816,7 @@ describe("websocket server", () => { const connections = new Array(10); const websockets = new Array(connections.length); var doneCounter = 0; - await new Promise((done) => { + await new Promise<void>((done) => { for (var i = 0; i < connections.length; i++) { var j = i; var resolve, reject, resolveConnection, rejectConnection; @@ -831,7 +830,7 @@ describe("websocket server", () => { }); gcTick(); const websocket = new WebSocket( - `ws://${server.hostname}:${server.port}` + `ws://${server.hostname}:${server.port}`, ); websocket.onerror = (e) => { reject(e); diff --git a/test/bun.js/which.test.ts b/test/bun.js/which.test.ts index 7fd4b8400..150bfa767 100644 --- a/test/bun.js/which.test.ts +++ b/test/bun.js/which.test.ts @@ -15,27 +15,27 @@ test("which", () => { // You can override PATH which("myscript.sh", { PATH: "/tmp", - }) + }), ).toBe("/tmp/myscript.sh"); expect( which("myscript.sh", { PATH: "/not-tmp", - }) + }), ).toBe(null); expect( // PATH works like the $PATH environment variable, respecting colons which("myscript.sh", { PATH: "/not-tmp:/tmp", - }) + }), ).toBe("/tmp/myscript.sh"); expect( // cwd is checked first which("myscript.sh", { cwd: "/tmp", - }) + }), ).toBe("/tmp/myscript.sh"); }); diff --git a/test/macro/fetchSync.tsx b/test/macro/fetchSync.tsx index ebe1566e6..51d1ca4f5 100644 --- a/test/macro/fetchSync.tsx +++ b/test/macro/fetchSync.tsx @@ -1,3 +1,4 @@ +// @ts-nocheck export async function fetchSync(ctx) { const str = ctx.arguments[0].toString(); diff --git a/test/macro/macro.d.ts b/test/macro/macro.d.ts new file mode 100644 index 000000000..ba02c03ed --- /dev/null +++ b/test/macro/macro.d.ts @@ -0,0 +1 @@ +declare module "macro:*"; diff --git a/test/scripts/browser.js b/test/scripts/browser.js index bd0bc23de..15b009671 100644 --- a/test/scripts/browser.js +++ b/test/scripts/browser.js @@ -70,7 +70,7 @@ function writeSnapshot(name, code) { ".debug" + path.extname(file) : file, - code + code, ); } @@ -114,7 +114,7 @@ async function main() { var shouldClose = true; page.on("console", (obj) => - console.log(`[console.${obj.type()}] ${obj.text()}`) + console.log(`[console.${obj.type()}] ${obj.text()}`), ); page.exposeFunction("testFail", (error) => { console.log(`❌ ${error}`); @@ -135,7 +135,7 @@ async function main() { } catch (err) { if (canRetry) { console.log( - `❌ ${key} failed once (incase it's still booting on universal binary for the first time). Retrying...` + `❌ ${key} failed once (incase it's still booting on universal binary for the first time). Retrying...`, ); canRetry = false; return await runPage(key); @@ -187,5 +187,5 @@ async function main() { main().catch((error) => setTimeout(() => { throw error; - }) + }), ); diff --git a/test/snippets/bun.lockb b/test/snippets/bun.lockb Binary files differindex cc2676be1..9553d3a11 100755 --- a/test/snippets/bun.lockb +++ b/test/snippets/bun.lockb diff --git a/test/snippets/caught-require.js b/test/snippets/caught-require.js index 6111d2b10..257cce4ec 100644 --- a/test/snippets/caught-require.js +++ b/test/snippets/caught-require.js @@ -9,7 +9,7 @@ try { import("this-package-should-not-exist").then( () => {}, - () => {} + () => {}, ); export async function test() { @@ -24,7 +24,7 @@ export async function test() { import("this-package-should-not-exist").then( () => {}, - () => {} + () => {}, ); return testDone(import.meta.url); diff --git a/test/snippets/code-simplification-neql-define.js b/test/snippets/code-simplification-neql-define.js index ed5c5c395..c7676dc9b 100644 --- a/test/snippets/code-simplification-neql-define.js +++ b/test/snippets/code-simplification-neql-define.js @@ -14,7 +14,7 @@ export var $f332019d = $$m( { "relay-runtime/lib/network/RelayQueryResponseCache.js": ( module, - exports + exports, ) => { var RelayQueryResponseCache = function () { var foo = function RelayQueryResponseCache(_ref) { @@ -26,7 +26,7 @@ export var $f332019d = $$m( false, "RelayQueryResponseCache: Expected the max cache size to be > 0, got " + "`%s`.", - size + size, ) : invariant(false) : void 0; @@ -35,7 +35,7 @@ export var $f332019d = $$m( ? invariant( false, "RelayQueryResponseCache: Expected the max ttl to be > 0, got `%s`.", - ttl + ttl, ) : invariant(false) : void 0; @@ -44,7 +44,7 @@ export var $f332019d = $$m( }; RelayQueryResponseCache(); }, - }["relay-runtime/lib/network/RelayQueryResponseCache.js"] + }["relay-runtime/lib/network/RelayQueryResponseCache.js"], ); export function test() { diff --git a/test/snippets/export.js b/test/snippets/export.js index fe0abfa53..2a757269f 100644 --- a/test/snippets/export.js +++ b/test/snippets/export.js @@ -23,7 +23,7 @@ export function test() { } console.assert( powerLevel.description === "9001", - "Symbol is not exported correctly" + "Symbol is not exported correctly", ); return testDone(import.meta.url); } diff --git a/test/snippets/jsx-entities.jsx b/test/snippets/jsx-entities.jsx index adabace2c..ac5d32225 100644 --- a/test/snippets/jsx-entities.jsx +++ b/test/snippets/jsx-entities.jsx @@ -928,7 +928,7 @@ export function test() { console.assert( elements[rawKey] === key.codePointAt(0), - `${key} is not ${elements[rawKey]}` + `${key} is not ${elements[rawKey]}`, ); } diff --git a/test/snippets/jsx-spacing.js b/test/snippets/jsx-spacing.js index 9b9f28a33..dfdd09560 100644 --- a/test/snippets/jsx-spacing.js +++ b/test/snippets/jsx-spacing.js @@ -3,27 +3,40 @@ exports.__esModule = true; exports.test = void 0; var ReactDOM = require("react-dom/server"); var ReturnDescriptionAsString = function (_a) { - var description = _a.description; - return description; + var description = _a.description; + return description; }; function test() { - var _bun = ReactDOM.renderToString(<ReturnDescriptionAsString description="line1 + var _bun = ReactDOM.renderToString( + <ReturnDescriptionAsString + description="line1 line2 trailing space line4 no trailing space 'single quote' \t\f\v\uF000 `template string` line6 no trailing space line7 trailing newline that ${terminates} the string literal -"></ReturnDescriptionAsString>); - // convert HTML entities to unicode - var el = document.createElement("textarea"); - el.innerHTML = _bun; - var bun = el.value; - var esbuild = "line1\nline2 trailing space \n\nline4 no trailing space 'single quote' \\t\\f\\v\\uF000 `template string`\n\nline6 no trailing space\nline7 trailing newline that ${terminates} the string literal\n"; - console.assert(bun === esbuild, "strings did not match: " + JSON.stringify({ - received: bun, - expected: esbuild - }, null, 2)); - testDone(import.meta.url); +" + ></ReturnDescriptionAsString>, + ); + // convert HTML entities to unicode + var el = document.createElement("textarea"); + el.innerHTML = _bun; + var bun = el.value; + var esbuild = + "line1\nline2 trailing space \n\nline4 no trailing space 'single quote' \\t\\f\\v\\uF000 `template string`\n\nline6 no trailing space\nline7 trailing newline that ${terminates} the string literal\n"; + console.assert( + bun === esbuild, + "strings did not match: " + + JSON.stringify( + { + received: bun, + expected: esbuild, + }, + null, + 2, + ), + ); + testDone(import.meta.url); } exports.test = test; diff --git a/test/snippets/jsx-spacing.jsx b/test/snippets/jsx-spacing.jsx index b6d13f97a..7e83171e6 100644 --- a/test/snippets/jsx-spacing.jsx +++ b/test/snippets/jsx-spacing.jsx @@ -13,7 +13,7 @@ line4 no trailing space 'single quote' \t\f\v\uF000 `template string` line6 no trailing space line7 trailing newline that ${terminates} the string literal " - ></ReturnDescriptionAsString> + ></ReturnDescriptionAsString>, ); // convert HTML entities to unicode @@ -35,8 +35,8 @@ line7 trailing newline that ${terminates} the string literal expected: esbuild, }, null, - 2 - )}` + 2, + )}`, ); testDone(import.meta.url); diff --git a/test/snippets/jsx-top-level.tsx b/test/snippets/jsx-top-level.tsx index 2b49b5959..a3caafccf 100644 --- a/test/snippets/jsx-top-level.tsx +++ b/test/snippets/jsx-top-level.tsx @@ -1,3 +1,4 @@ +// @ts-nocheck const isDropdown = true; const iconName = ""; const adjustedPadding = 5; diff --git a/test/snippets/latin1-chars-in-regexp.js b/test/snippets/latin1-chars-in-regexp.js index e4d613f5e..1a533b1e1 100644 --- a/test/snippets/latin1-chars-in-regexp.js +++ b/test/snippets/latin1-chars-in-regexp.js @@ -15,7 +15,7 @@ export var re_btou = new RegExp( "[\xE0-\xEF][\x80-\xBF]{2}", "[\xF0-\xF7][\x80-\xBF]{3}", ].join("|"), - "g" + "g", ); const encoder = new TextEncoder(); @@ -46,7 +46,7 @@ export function test() { ) { throw new Error( `test failed -${JSON.stringify({ expected, real }, null, 2)}` +${JSON.stringify({ expected, real }, null, 2)}`, ); } @@ -57,12 +57,12 @@ ${JSON.stringify({ expected, real }, null, 2)}` const decoder = new TextDecoder("utf8"); if ( !realLines.every( - (line, i) => decoder.decode(Uint8Array.from(expected[i])) === line + (line, i) => decoder.decode(Uint8Array.from(expected[i])) === line, ) ) { throw new Error( `test failed. Lines did not match. -${JSON.stringify({ expected, real }, null, 2)}` +${JSON.stringify({ expected, real }, null, 2)}`, ); } diff --git a/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/dir/foo.js b/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/dir/foo.js index e54d9d4d6..26ab53d5b 100644 --- a/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/dir/foo.js +++ b/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/dir/foo.js @@ -1 +1 @@ -export const target = 'browser';
\ No newline at end of file +export const target = "browser"; diff --git a/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/foo.js b/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/foo.js index e54d9d4d6..26ab53d5b 100644 --- a/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/foo.js +++ b/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/foo.js @@ -1 +1 @@ -export const target = 'browser';
\ No newline at end of file +export const target = "browser"; diff --git a/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/index.js b/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/index.js index e54d9d4d6..26ab53d5b 100644 --- a/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/index.js +++ b/test/snippets/package-json-exports/_node_modules_copy/inexact/browser/index.js @@ -1 +1 @@ -export const target = 'browser';
\ No newline at end of file +export const target = "browser"; diff --git a/test/snippets/package-json-exports/_node_modules_copy/inexact/default/foo.js b/test/snippets/package-json-exports/_node_modules_copy/inexact/default/foo.js index 8fb5eac0c..826077c96 100644 --- a/test/snippets/package-json-exports/_node_modules_copy/inexact/default/foo.js +++ b/test/snippets/package-json-exports/_node_modules_copy/inexact/default/foo.js @@ -1 +1 @@ -export const target = 'default'; +export const target = "default"; diff --git a/test/snippets/package-json-exports/_node_modules_copy/inexact/node/foo.js b/test/snippets/package-json-exports/_node_modules_copy/inexact/node/foo.js index b9504cdf9..301a88090 100644 --- a/test/snippets/package-json-exports/_node_modules_copy/inexact/node/foo.js +++ b/test/snippets/package-json-exports/_node_modules_copy/inexact/node/foo.js @@ -1 +1 @@ -export const target = 'node';
\ No newline at end of file +export const target = "node"; diff --git a/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/dir/foo.js b/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/dir/foo.js index e54d9d4d6..26ab53d5b 100644 --- a/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/dir/foo.js +++ b/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/dir/foo.js @@ -1 +1 @@ -export const target = 'browser';
\ No newline at end of file +export const target = "browser"; diff --git a/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/foo.js b/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/foo.js index e54d9d4d6..26ab53d5b 100644 --- a/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/foo.js +++ b/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/foo.js @@ -1 +1 @@ -export const target = 'browser';
\ No newline at end of file +export const target = "browser"; diff --git a/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/index.js b/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/index.js index e54d9d4d6..26ab53d5b 100644 --- a/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/index.js +++ b/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/browser/index.js @@ -1 +1 @@ -export const target = 'browser';
\ No newline at end of file +export const target = "browser"; diff --git a/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/default/foo.js b/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/default/foo.js index 8fb5eac0c..826077c96 100644 --- a/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/default/foo.js +++ b/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/default/foo.js @@ -1 +1 @@ -export const target = 'default'; +export const target = "default"; diff --git a/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/node/foo.js b/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/node/foo.js index b9504cdf9..301a88090 100644 --- a/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/node/foo.js +++ b/test/snippets/package-json-exports/_node_modules_copy/js-only-exports/node/foo.js @@ -1 +1 @@ -export const target = 'node';
\ No newline at end of file +export const target = "node"; diff --git a/test/snippets/react-context-value-func.tsx b/test/snippets/react-context-value-func.tsx index 5f38a5d1c..e7ced1292 100644 --- a/test/snippets/react-context-value-func.tsx +++ b/test/snippets/react-context-value-func.tsx @@ -1,3 +1,4 @@ +// @ts-nocheck import React from "react"; const Context = React.createContext({}); diff --git a/test/snippets/simple-lit-example.ts b/test/snippets/simple-lit-example.ts index 34446e418..3c53f03ab 100644 --- a/test/snippets/simple-lit-example.ts +++ b/test/snippets/simple-lit-example.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { LitElement, html, css } from "lit"; import { customElement, property, eventOptions } from "lit/decorators.js"; @@ -12,7 +13,7 @@ if (document?.readyState === "loading") { () => { loadedResolve(); }, - { once: true } + { once: true }, ); } else { loadedResolve(); diff --git a/test/snippets/spread_with_key.tsx b/test/snippets/spread_with_key.tsx index 9c26ea5ba..d9f842d27 100644 --- a/test/snippets/spread_with_key.tsx +++ b/test/snippets/spread_with_key.tsx @@ -1,3 +1,4 @@ +// @ts-nocheck import React from "react"; export function SpreadWithTheKey({ className }: Props) { diff --git a/test/snippets/styledcomponents-output.js b/test/snippets/styledcomponents-output.js index a79b5e24d..fca6e8407 100644 --- a/test/snippets/styledcomponents-output.js +++ b/test/snippets/styledcomponents-output.js @@ -39,18 +39,18 @@ export function test() { <ErrorScreenRoot id="error-el"> The react child should have this text </ErrorScreenRoot>, - reactEl + reactEl, ); const style = document.querySelector("style[data-styled]"); console.assert(style, "style tag should exist"); console.assert( style.textContent.split("").every((a) => a.codePointAt(0) < 128), - "style tag should not contain invalid unicode codepoints" + "style tag should not contain invalid unicode codepoints", ); console.assert( document.querySelector("#error-el").textContent === - "The react child should have this text" + "The react child should have this text", ); ReactDOM.unmountComponentAtNode(reactEl); diff --git a/test/snippets/template-literal.js b/test/snippets/template-literal.js index ff4e08a4d..a5749a555 100644 --- a/test/snippets/template-literal.js +++ b/test/snippets/template-literal.js @@ -37,14 +37,14 @@ export function test() { for (let foo of [fooNoBracesUT16, fooNoBracesUTF8, fooUTF16, fooUTF8]) { console.assert( foo.includes("before"), - `Expected ${foo} to include "before"` + `Expected ${foo} to include "before"`, ); console.assert(foo.includes("after"), `Expected ${foo} to include "after"`); } console.assert( templateLiteralWhichDefinesAFunction.includes("true"), - "Expected fooFunction to include 'true'" + "Expected fooFunction to include 'true'", ); return testDone(import.meta.url); diff --git a/test/snippets/ts-fallback-rewrite-works.ts b/test/snippets/ts-fallback-rewrite-works.ts index 8e6dabcdb..8054897b8 100644 --- a/test/snippets/ts-fallback-rewrite-works.ts +++ b/test/snippets/ts-fallback-rewrite-works.ts @@ -1,3 +1,4 @@ +// @ts-nocheck // This looks like it does nothing // But if you import /ts-fallback-rewrite-works.js, it should resolve the import to /ts-fallback-rewrite-works.ts export function test() { diff --git a/test/snippets/tsx-fallback-rewrite-works.tsx b/test/snippets/tsx-fallback-rewrite-works.tsx index b18619914..918db3b04 100644 --- a/test/snippets/tsx-fallback-rewrite-works.tsx +++ b/test/snippets/tsx-fallback-rewrite-works.tsx @@ -1,3 +1,4 @@ +// @ts-nocheck // This looks like it does nothing // But if you import /tsx-fallback-rewrite-works.js, it should resolve the import to /tsx-fallback-rewrite-works.tsx export function test() { diff --git a/test/snippets/type-only-imports.ts b/test/snippets/type-only-imports.ts index 447f86793..c43fcf278 100644 --- a/test/snippets/type-only-imports.ts +++ b/test/snippets/type-only-imports.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type Bacon from "tree"; import type { SilentSymbolCollisionsAreOkayInTypeScript } from "./app"; diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 000000000..b6fdf3087 --- /dev/null +++ b/tsconfig.base.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "lib": [ + "ESNext" + ], + "module": "esnext", + "target": "esnext", + "moduleResolution": "nodenext", + "strict": true, + "noImplicitAny": false, + "allowSyntheticDefaultImports": true, + "allowJs": true, + "downlevelIteration": true, + "esModuleInterop": true, + "skipLibCheck": true, + "jsx": "react-jsx", + "types": [ + "bun-types" + ], + "typeRoots": [ + "./packages" + ], + } +}
\ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index 3f648150e..38b67ef1d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,11 +1,27 @@ { + "extends": "./tsconfig.base.json", "compilerOptions": { - "lib": ["ESNext"], - "module": "esnext", - "target": "esnext", - "typeRoots": ["./types"], - "types": ["bun-types"], + "experimentalDecorators": true, + "allowSyntheticDefaultImports": true, + "noEmit": true, + "skipLibCheck": true, "allowJs": true }, - "exclude": ["src"] -} + "include": [ + "." + ], + "exclude": [ + "src/test", + "packages", + "bench", + "examples/react-fast-refresh-test", + "examples/macros", + "test/bun.js/solid-dom-fixtures", + "test/bun.js/bundled", + // JavaScriptCore builtins use a non-standard "@" symbol to indicate a private identifier which no other tool supports + "src/bun.js/builtins", + "src/api/demo", + "test/snapshots", + "test/snapshots-no-hmr" + ] +}
\ No newline at end of file |