diff --git a/.github/workflows/bun-types-release.yml b/.github/workflows/bun-types-release.yml
new file mode 100644
index 0000000000..ebbe085861
--- /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 0000000000..fad84a1150
--- /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 0000000000..ebb14dfbd0
--- /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 0000000000..495a80fd77
--- /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 0e0f09688f..3dcd4ca35c 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
diff --git a/Makefile b/Makefile
index b45e12327d..b06c88827a 100644
--- a/Makefile
+++ b/Makefile
@@ -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:
diff --git a/README.md b/README.md
index 5f4811944d..731d05864b 100644
--- a/README.md
+++ b/README.md
@@ -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());
```
@@ -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({
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("
hi!
");
+const transpiler = new Bun.Transpiler({loader: 'jsx'});
+transpiler.transformSync('
hi!
');
```
```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("
hi!
");
+const transpiler = new Bun.Transpiler({loader: 'jsx'});
+await transpiler.transform('
hi!
');
```
```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("
hi!
", "tsx");
+await transpiler.transform('
hi!
', '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
new file mode 100755
index 0000000000..14530a5ec0
Binary files /dev/null and b/bench/bun.lockb differ
diff --git a/bench/ffi/src/bun.lockb b/bench/ffi/src/bun.lockb
index 184cb439cf..28144fc51d 100755
Binary files a/bench/ffi/src/bun.lockb and b/bench/ffi/src/bun.lockb differ
diff --git a/bench/hot-module-reloading/css-stress-test/bun.lockb b/bench/hot-module-reloading/css-stress-test/bun.lockb
new file mode 100755
index 0000000000..9cad009bba
Binary files /dev/null and b/bench/hot-module-reloading/css-stress-test/bun.lockb differ
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 43d6a776ad..c330a01552 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 3ef84ffe5a..afdaaae25b 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 (
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 3b67cd111b..2093d924f5 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 (
<>
CSS HMR Stress Test!
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.
@@ -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,
)}
/>
diff --git a/packages/bun-landing/tsconfig.json b/packages/bun-landing/tsconfig.json
index 54b36a1e78..c1e94dd709 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 b2ae22225b..f7899698d8 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
new file mode 100755
index 0000000000..2f64dc3192
Binary files /dev/null and b/packages/bun-macro-relay/bun.lockb differ
diff --git a/packages/bun-types/.eslintignore b/packages/bun-types/.eslintignore
new file mode 100644
index 0000000000..9bb9443850
--- /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 0000000000..d38b920f4e
--- /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 0000000000..04c01ba7ba
--- /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 0000000000..849ddff3b7
--- /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 0000000000..7985ccd986
--- /dev/null
+++ b/packages/bun-types/README.md
@@ -0,0 +1,55 @@
+# Bun TypeScript type definitions
+
+
+
+
+
+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 0000000000..ae3b54ff2a
--- /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 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(
+ 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(
+ 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) | Promise,
+ message?: string | Error,
+ ): Promise;
+ function rejects(
+ block: (() => Promise) | Promise,
+ error: AssertPredicate,
+ message?: string | Error,
+ ): Promise;
+ /**
+ * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
+ * calls the function and awaits the returned promise to complete. It will then
+ * check that the promise is not rejected.
+ *
+ * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If
+ * the function does not return a promise, `assert.doesNotReject()` will return a
+ * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases
+ * the error handler is skipped.
+ *
+ * Using `assert.doesNotReject()` is actually not useful because there is little
+ * benefit in catching a rejection and then rejecting it again. Instead, consider
+ * adding a comment next to the specific code path that should not reject and keep
+ * error messages as expressive as possible.
+ *
+ * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
+ * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation
+ * function. See {@link throws} for more details.
+ *
+ * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}.
+ *
+ * ```js
+ * import assert from 'assert/strict';
+ *
+ * await assert.doesNotReject(
+ * async () => {
+ * throw new TypeError('Wrong value');
+ * },
+ * SyntaxError
+ * );
+ * ```
+ *
+ * ```js
+ * import assert from 'assert/strict';
+ *
+ * assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
+ * .then(() => {
+ * // ...
+ * });
+ * ```
+ */
+ function doesNotReject(
+ block: (() => Promise) | Promise,
+ message?: string | Error,
+ ): Promise;
+ function doesNotReject(
+ block: (() => Promise) | Promise,
+ error: AssertPredicate,
+ message?: string | Error,
+ ): Promise;
+ /**
+ * Expects the `string` input to match the regular expression.
+ *
+ * ```js
+ * import assert from 'assert/strict';
+ *
+ * assert.match('I will fail', /pass/);
+ * // AssertionError [ERR_ASSERTION]: The input did not match the regular ...
+ *
+ * assert.match(123, /pass/);
+ * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
+ *
+ * assert.match('I will pass', /pass/);
+ * // OK
+ * ```
+ *
+ * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal
+ * to the value of the `message` parameter. If the `message` parameter is
+ * undefined, a default error message is assigned. If the `message` parameter is an
+ * instance of an `Error` then it will be thrown instead of the `AssertionError`.
+ */
+ 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 0000000000..a7de0cfe4b
--- /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
+ | {
+ 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): 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,
+ byteOffset?: number,
+ length?: number,
+ ): Buffer;
+ /**
+ * Creates a new Buffer using the passed {data}
+ * @param data data to create a new Buffer
+ */
+ from(data: Uint8Array | ReadonlyArray): Buffer;
+ from(
+ data: WithImplicitCoercion | string>,
+ ): Buffer;
+ /**
+ * Creates a new Buffer containing the given JavaScript string {str}.
+ * If provided, the {encoding} parameter identifies the character encoding.
+ * If not provided, {encoding} defaults to 'utf8'.
+ */
+ from(
+ str:
+ | WithImplicitCoercion
+ | {
+ [Symbol.toPrimitive](hint: "string"): string;
+ },
+ encoding?: BufferEncoding,
+ ): Buffer;
+ /**
+ * Creates a new Buffer using the passed {data}
+ * @param values to create a new Buffer
+ */
+ of(...items: number[]): Buffer;
+ /**
+ * Returns `true` if `obj` is a `Buffer`, `false` otherwise.
+ *
+ * ```js
+ * import { Buffer } from '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:
+ * 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, 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: [ , ]
+ * // (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:
+ * ```
+ *
+ * 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:
+ * ```
+ *
+ * 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:
+ * ```
+ *
+ * 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):
+ *
+ * buf.fill(0);
+ *
+ * console.log(buf);
+ * // Prints:
+ * ```
+ *
+ * A `TypeError` will be thrown if `size` is not a number.
+ *
+ * The `Buffer` module pre-allocates an internal `Buffer` instance of
+ * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`,`Buffer.from(array)`, `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:
+ * ```
+ *
+ * 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: [ , , ]
+ * // (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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ *
+ * 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:
+ * ```
+ *
+ * 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:
+ * ```
+ *
+ * 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:
+ * ```
+ *
+ * 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:
+ * ```
+ *
+ * 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:
+ *
+ * buf1.swap16();
+ *
+ * console.log(buf1);
+ * // Prints:
+ *
+ * const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+ *
+ * buf2.swap16();
+ * // Throws ERR_INVALID_BUFFER_SIZE.
+ * ```
+ *
+ * One convenient use of `buf.swap16()` is to perform a fast in-place conversion
+ * between UTF-16 little-endian and UTF-16 big-endian:
+ *
+ * ```js
+ * import { Buffer } from '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:
+ *
+ * buf1.swap32();
+ *
+ * console.log(buf1);
+ * // Prints:
+ *
+ * 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:
+ *
+ * buf1.swap64();
+ *
+ * console.log(buf1);
+ * // Prints:
+ *
+ * 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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ * @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:
+ * ```
+ *
+ * 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:
+ * console.log(buf.fill('aazz', 'hex'));
+ * // Prints:
+ * 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;
+ /**
+ * 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;
+ }
+ 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 0000000000..1ec84492a2
--- /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;
+ export function test(
+ label: string,
+ test: (done: () => void) => void | Promise,
+ ): 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 0000000000..8611ccb301
--- /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;
+ 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 {
+ * 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 {
+ * return new Response(Bun.file("./package.json"));
+ * },
+ *
+ * // Optional port number - the default value is 3000
+ * port: process.env.PORT || 3000,
+ * });
+ * ```
+ */
+ export function serve>(
+ 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;
+
+ /**
+ *
+ * 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;
+
+ /**
+ *
+ * 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;
+
+ /**
+ *
+ * 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;
+
+ /**
+ *
+ * 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;
+
+ /**
+ *
+ * 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;
+
+ 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,
+ ): 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;
+
+ /**
+ * 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;
+
+ /**
+ * 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;
+
+ /**
+ * 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;
+
+ /**
+ * 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(
+ stream: ReadableStream,
+ ): Promise | 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 {
+ (promise: T | Promise): Promise | T;
+ status(
+ promise: T | Promise,
+ ): "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;
+ /**
+ * Close the file descriptor. This also flushes the internal buffer.
+ */
+ end(error?: Error): number | Promise;
+ }
+
+ /**
+ * [`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>;
+
+ /**
+ * 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;
+
+ /** 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;
+ };
+ 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 = () =>
Hello World
;
+ *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;
+ /**
+ * 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 {
+ /**
+ *
+ * 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) => any) => void | Promise;
+
+ /**
+ * 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 {
+ /**
+ * 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,
+ message: string | Uint8Array,
+ ) => void | Promise;
+
+ /**
+ * The {@link ServerWebSocket} has been opened
+ *
+ * @param ws The {@link ServerWebSocket} that was opened
+ */
+ open?: (ws: ServerWebSocket) => void | Promise;
+ /**
+ * The {@link ServerWebSocket} is ready for more data
+ *
+ * @param ws The {@link ServerWebSocket} that is ready
+ */
+ drain?: (ws: ServerWebSocket) => void | Promise;
+ /**
+ * 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,
+ code: number,
+ message: string,
+ ) => void | Promise;
+
+ /**
+ * 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 | undefined | void | Promise;
+ }
+
+ 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;
+ }
+
+ export interface WebSocketServeOptions
+ 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;
+
+ /**
+ * 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;
+ }
+
+ 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 = (
+ | WebSocketServeOptions
+ | ServerWebSocket
+ ) &
+ TLSOptions & {
+ /**
+ * The keys are [SNI](https://en.wikipedia.org/wiki/Server_Name_Indication) hostnames.
+ * The values are SSL options objects.
+ */
+ serverNames: Record;
+ };
+
+ /**
+ * 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;
+
+ /**
+ * 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(
+ 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 =
+ | TLSServeOptions
+ | WebSocketServeOptions
+ | 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 {
+ /**
+ * 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 {
+ constructor();
+
+ /**
+ * The number of bytes the hash will produce
+ */
+ static readonly byteLength: 20;
+ }
+ export class MD5 extends CryptoHashInterface {
+ constructor();
+
+ /**
+ * The number of bytes the hash will produce
+ */
+ static readonly byteLength: 16;
+ }
+ export class MD4 extends CryptoHashInterface {
+ constructor();
+
+ /**
+ * The number of bytes the hash will produce
+ */
+ static readonly byteLength: 16;
+ }
+ export class SHA224 extends CryptoHashInterface {
+ constructor();
+
+ /**
+ * The number of bytes the hash will produce
+ */
+ static readonly byteLength: 28;
+ }
+ export class SHA512 extends CryptoHashInterface {
+ constructor();
+
+ /**
+ * The number of bytes the hash will produce
+ */
+ static readonly byteLength: 64;
+ }
+ export class SHA384 extends CryptoHashInterface {
+ constructor();
+
+ /**
+ * The number of bytes the hash will produce
+ */
+ static readonly byteLength: 48;
+ }
+ export class SHA256 extends CryptoHashInterface {
+ constructor();
+
+ /**
+ * The number of bytes the hash will produce
+ */
+ static readonly byteLength: 32;
+ }
+ /**
+ * See also {@link sha}
+ */
+ export class SHA512_256 extends CryptoHashInterface {
+ 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;
+ /**
+ * 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;
+
+ 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;
+ }): ReturnType;
+
+ /**
+ * Deactivate all plugins
+ *
+ * This prevents registered plugins from being applied to future builds.
+ */
+ clearAll(): void;
+ }
+
+ var plugin: BunPlugin;
+
+ interface Socket {
+ /**
+ * 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 {
+ stop(): void;
+ ref(): void;
+ unref(): void;
+ reload(options: Pick, "socket">): void;
+ data: Options["data"];
+ }
+ interface TCPSocketListener>
+ extends SocketListener {
+ readonly port: number;
+ readonly hostname: string;
+ }
+ interface UnixSocketListener>
+ extends SocketListener {
+ readonly unix: string;
+ }
+
+ interface TCPSocket extends Socket {}
+ interface TLSSocket extends Socket {}
+
+ interface SocketHandler {
+ open(socket: Socket): void | Promise;
+ close?(socket: Socket): void | Promise;
+ error?(socket: Socket, error: Error): void | Promise;
+ data?(socket: Socket, data: BufferSource): void | Promise;
+ drain?(socket: Socket): void | Promise;
+ }
+
+ interface SocketOptions {
+ socket: SocketHandler;
+ tls?: TLSOptions;
+ data?: Data;
+ }
+ interface TCPSocketOptions extends SocketOptions {
+ hostname: string;
+ port: number;
+ }
+
+ interface UnixSocketOptions extends SocketOptions {
+ 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(
+ options: TCPSocketOptions,
+ ): Promise>;
+ export function connect(
+ options: UnixSocketOptions,
+ ): Promise>;
+
+ /**
+ *
+ * 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(
+ options: TCPSocketOptions,
+ ): TCPSocketListener;
+ export function listen(
+ options: UnixSocketOptions,
+ ): UnixSocketListener;
+
+ 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;
+
+ /**
+ * 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;
+ }
+ }
+
+ interface SubprocessIO {
+ readonly stdin?: undefined | number | ReadableStream | FileSink;
+ readonly stdout?: undefined | number | ReadableStream;
+ readonly stderr?: undefined | number | ReadableStream;
+ }
+ interface Subprocess {
+ 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;
+
+ /**
+ * 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(
+ 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>;
+
+ /**
+ * 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(
+ /**
+ * The command to run
+ * @example
+ * ```ts
+ * const subprocess = Bun.spawn(["echo", "hello"]);
+ */
+ cmds: string[],
+ options?: Opts,
+ ): Subprocess>;
+ type OptionsToSubprocessIO = {
+ 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
new file mode 100755
index 0000000000..cf33f4cab6
Binary files /dev/null and b/packages/bun-types/bun.lockb differ
diff --git a/packages/bun-types/child_process.d.ts b/packages/bun-types/child_process.d.ts
new file mode 100644
index 0000000000..639dcaf621
--- /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;
+ 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,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(command: string, options: SpawnOptions): ChildProcess;
+ // overloads of spawn with 'args'
+ function spawn(
+ command: string,
+ args?: ReadonlyArray,
+ options?: SpawnOptionsWithoutStdio,
+ ): ChildProcessWithoutNullStreams;
+ function spawn(
+ command: string,
+ args: ReadonlyArray,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ args: ReadonlyArray,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ args: ReadonlyArray,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ args: ReadonlyArray,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ args: ReadonlyArray,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ args: ReadonlyArray,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ args: ReadonlyArray,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ args: ReadonlyArray,
+ options: SpawnOptionsWithStdioTuple,
+ ): ChildProcessByStdio;
+ function spawn(
+ command: string,
+ args: ReadonlyArray,
+ options: SpawnOptions,
+ ): ChildProcess;
+ interface ExecOptions extends CommonOptions {
+ shell?: string | undefined;
+ signal?: AbortSignal | undefined;
+ maxBuffer?: number | undefined;
+ killSignal?: NodeJS.Signals | number | undefined;
+ }
+ interface ExecOptionsWithStringEncoding extends ExecOptions {
+ encoding: BufferEncoding;
+ }
+ interface ExecOptionsWithBufferEncoding extends ExecOptions {
+ encoding: BufferEncoding | null; // specify `null`.
+ }
+ interface ExecException extends Error {
+ cmd?: string | undefined;
+ killed?: boolean | undefined;
+ code?: number | undefined;
+ signal?: NodeJS.Signals | undefined;
+ }
+ /**
+ * Spawns a shell then executes the `command` within that shell, buffering any
+ * generated output. The `command` string passed to the exec function is processed
+ * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters))
+ * need to be dealt with accordingly:
+ *
+ * ```js
+ * const { exec } = require('child_process');
+ *
+ * exec('"/path/to/test file/test.sh" arg1 arg2');
+ * // Double quotes are used so that the space in the path is not interpreted as
+ * // a delimiter of multiple arguments.
+ *
+ * exec('echo "The \\$HOME variable is $HOME"');
+ * // The $HOME variable is escaped in the first instance, but not in the second.
+ * ```
+ *
+ * **Never pass unsanitized user input to this function. Any input containing shell**
+ * **metacharacters may be used to trigger arbitrary command execution.**
+ *
+ * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The
+ * `error.code` property will be
+ * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the
+ * process.
+ *
+ * The `stdout` and `stderr` arguments passed to the callback will contain the
+ * stdout and stderr output of the child process. By default, Node.js will decode
+ * the output as UTF-8 and pass strings to the callback. The `encoding` option
+ * can be used to specify the character encoding used to decode the stdout and
+ * stderr output. If `encoding` is `'buffer'`, or an unrecognized character
+ * encoding, `Buffer` objects will be passed to the callback instead.
+ *
+ * ```js
+ * const { exec } = require('child_process');
+ * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
+ * if (error) {
+ * console.error(`exec error: ${error}`);
+ * return;
+ * }
+ * console.log(`stdout: ${stdout}`);
+ * console.error(`stderr: ${stderr}`);
+ * });
+ * ```
+ *
+ * If `timeout` is greater than `0`, the parent will send the signal
+ * identified by the `killSignal` property (the default is `'SIGTERM'`) if the
+ * child runs longer than `timeout` milliseconds.
+ *
+ * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace
+ * the existing process and uses a shell to execute the command.
+ *
+ * If this method is invoked as its `util.promisify()` ed version, it returns
+ * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In
+ * case of an error (including any error resulting in an exit code other than 0), a
+ * rejected promise is returned, with the same `error` object given in the
+ * callback, but with two additional properties `stdout` and `stderr`.
+ *
+ * ```js
+ * const util = require('util');
+ * const exec = util.promisify(require('child_process').exec);
+ *
+ * async function lsExample() {
+ * const { stdout, stderr } = await exec('ls');
+ * console.log('stdout:', stdout);
+ * console.error('stderr:', stderr);
+ * }
+ * lsExample();
+ * ```
+ *
+ * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except
+ * the error passed to the callback will be an `AbortError`:
+ *
+ * ```js
+ * const { exec } = require('child_process');
+ * const controller = new AbortController();
+ * const { signal } = controller;
+ * const child = exec('grep ssh', { signal }, (error) => {
+ * console.log(error); // an AbortError
+ * });
+ * controller.abort();
+ * ```
+ * @since v0.1.90
+ * @param command The command to run, with space-separated arguments.
+ * @param callback called with the output when process terminates.
+ */
+ function exec(
+ command: string,
+ callback?: (
+ error: ExecException | null,
+ stdout: string,
+ stderr: string,
+ ) => void,
+ ): ChildProcess;
+ // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
+ function exec(
+ command: string,
+ options: {
+ encoding: "buffer" | null;
+ } & ExecOptions,
+ callback?: (
+ error: ExecException | null,
+ stdout: Buffer,
+ stderr: Buffer,
+ ) => void,
+ ): ChildProcess;
+ // `options` with well known `encoding` means stdout/stderr are definitely `string`.
+ function exec(
+ command: string,
+ options: {
+ encoding: BufferEncoding;
+ } & ExecOptions,
+ callback?: (
+ error: ExecException | null,
+ stdout: string,
+ stderr: string,
+ ) => void,
+ ): ChildProcess;
+ // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
+ // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
+ function exec(
+ command: string,
+ options: {
+ encoding: BufferEncoding;
+ } & ExecOptions,
+ callback?: (
+ error: ExecException | null,
+ stdout: string | Buffer,
+ stderr: string | Buffer,
+ ) => void,
+ ): ChildProcess;
+ // `options` without an `encoding` means stdout/stderr are definitely `string`.
+ function exec(
+ command: string,
+ options: ExecOptions,
+ callback?: (
+ error: ExecException | null,
+ stdout: string,
+ stderr: string,
+ ) => void,
+ ): ChildProcess;
+ // fallback if nothing else matches. Worst case is always `string | Buffer`.
+ function exec(
+ command: string,
+ options: (ObjectEncodingOptions & ExecOptions) | undefined | null,
+ callback?: (
+ error: ExecException | null,
+ stdout: string | Buffer,
+ stderr: string | Buffer,
+ ) => void,
+ ): ChildProcess;
+ interface PromiseWithChild extends Promise {
+ child: ChildProcess;
+ }
+ namespace exec {
+ function __promisify__(command: string): PromiseWithChild<{
+ stdout: string;
+ stderr: string;
+ }>;
+ function __promisify__(
+ command: string,
+ options: {
+ encoding: "buffer" | null;
+ } & ExecOptions,
+ ): PromiseWithChild<{
+ stdout: Buffer;
+ stderr: Buffer;
+ }>;
+ function __promisify__(
+ command: string,
+ options: {
+ encoding: BufferEncoding;
+ } & ExecOptions,
+ ): PromiseWithChild<{
+ stdout: string;
+ stderr: string;
+ }>;
+ function __promisify__(
+ command: string,
+ options: ExecOptions,
+ ): PromiseWithChild<{
+ stdout: string;
+ stderr: string;
+ }>;
+ function __promisify__(
+ command: string,
+ options?: (ObjectEncodingOptions & ExecOptions) | null,
+ ): PromiseWithChild<{
+ stdout: string | Buffer;
+ stderr: string | Buffer;
+ }>;
+ }
+ interface ExecFileOptions extends CommonOptions, Abortable {
+ maxBuffer?: number | undefined;
+ killSignal?: NodeJS.Signals | number | undefined;
+ windowsVerbatimArguments?: boolean | undefined;
+ shell?: boolean | string | undefined;
+ signal?: AbortSignal | undefined;
+ }
+ interface ExecFileOptionsWithStringEncoding extends ExecFileOptions {
+ encoding: BufferEncoding;
+ }
+ interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions {
+ encoding: "buffer" | null;
+ }
+ interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {
+ encoding: BufferEncoding;
+ }
+ type ExecFileException = 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 | null,
+ ): ChildProcess;
+ function execFile(
+ file: string,
+ args: ReadonlyArray | undefined | null,
+ options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
+ ): ChildProcess;
+ // no `options` definitely means stdout/stderr are `string`.
+ function execFile(
+ file: string,
+ callback: (
+ error: ExecFileException | null,
+ stdout: string,
+ stderr: string,
+ ) => void,
+ ): ChildProcess;
+ function execFile(
+ file: string,
+ args: ReadonlyArray | undefined | null,
+ callback: (
+ error: ExecFileException | null,
+ stdout: string,
+ stderr: string,
+ ) => void,
+ ): ChildProcess;
+ // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
+ function execFile(
+ file: string,
+ options: ExecFileOptionsWithBufferEncoding,
+ callback: (
+ error: ExecFileException | null,
+ stdout: Buffer,
+ stderr: Buffer,
+ ) => void,
+ ): ChildProcess;
+ function execFile(
+ file: string,
+ args: ReadonlyArray | undefined | null,
+ options: ExecFileOptionsWithBufferEncoding,
+ callback: (
+ error: ExecFileException | null,
+ stdout: Buffer,
+ stderr: Buffer,
+ ) => void,
+ ): ChildProcess;
+ // `options` with well known `encoding` means stdout/stderr are definitely `string`.
+ function execFile(
+ file: string,
+ options: ExecFileOptionsWithStringEncoding,
+ callback: (
+ error: ExecFileException | null,
+ stdout: string,
+ stderr: string,
+ ) => void,
+ ): ChildProcess;
+ function execFile(
+ file: string,
+ args: ReadonlyArray | undefined | null,
+ options: ExecFileOptionsWithStringEncoding,
+ callback: (
+ error: ExecFileException | null,
+ stdout: string,
+ stderr: string,
+ ) => void,
+ ): ChildProcess;
+ // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
+ // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
+ function execFile(
+ file: string,
+ options: ExecFileOptionsWithOtherEncoding,
+ callback: (
+ error: ExecFileException | null,
+ stdout: string | Buffer,
+ stderr: string | Buffer,
+ ) => void,
+ ): ChildProcess;
+ function execFile(
+ file: string,
+ args: ReadonlyArray | undefined | null,
+ options: ExecFileOptionsWithOtherEncoding,
+ callback: (
+ error: ExecFileException | null,
+ stdout: string | Buffer,
+ stderr: string | Buffer,
+ ) => void,
+ ): ChildProcess;
+ // `options` without an `encoding` means stdout/stderr are definitely `string`.
+ function execFile(
+ file: string,
+ options: ExecFileOptions,
+ callback: (
+ error: ExecFileException | null,
+ stdout: string,
+ stderr: string,
+ ) => void,
+ ): ChildProcess;
+ function execFile(
+ file: string,
+ args: ReadonlyArray | undefined | null,
+ options: ExecFileOptions,
+ callback: (
+ error: ExecFileException | null,
+ stdout: string,
+ stderr: string,
+ ) => void,
+ ): 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 | 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 | undefined | null,
+ ): PromiseWithChild<{
+ stdout: string;
+ stderr: string;
+ }>;
+ function __promisify__(
+ file: string,
+ options: ExecFileOptionsWithBufferEncoding,
+ ): PromiseWithChild<{
+ stdout: Buffer;
+ stderr: Buffer;
+ }>;
+ function __promisify__(
+ file: string,
+ args: ReadonlyArray | 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 | 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 | 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 | 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 | 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,
+ options?: ForkOptions,
+ ): ChildProcess;
+ interface SpawnSyncOptions extends CommonSpawnOptions {
+ input?: string | NodeJS.ArrayBufferView | undefined;
+ maxBuffer?: number | undefined;
+ encoding?: BufferEncoding | "buffer" | null | undefined;
+ }
+ interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions {
+ encoding: BufferEncoding;
+ }
+ interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions {
+ encoding?: "buffer" | null | undefined;
+ }
+ interface SpawnSyncReturns {
+ pid: number;
+ output: Array;
+ stdout: T;
+ stderr: T;
+ status: number | null;
+ signal: NodeJS.Signals | null;
+ error?: Error | undefined;
+ }
+ /**
+ * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return
+ * until the child process has fully closed. When a timeout has been encountered
+ * and `killSignal` is sent, the method won't return until the process has
+ * completely exited. If the process intercepts and handles the `SIGTERM` signal
+ * and doesn't exit, the parent process will wait until the child process has
+ * exited.
+ *
+ * **If the `shell` option is enabled, do not pass unsanitized user input to this**
+ * **function. Any input containing shell metacharacters may be used to trigger**
+ * **arbitrary command execution.**
+ * @since v0.11.12
+ * @param command The command to run.
+ * @param args List of string arguments.
+ */
+ function spawnSync(command: string): SpawnSyncReturns;
+ function spawnSync(
+ command: string,
+ options: SpawnSyncOptionsWithStringEncoding,
+ ): SpawnSyncReturns