This page documents the bun-types npm package: its file layout, how the TypeScript declarations are organized, the conflict-resolution mechanism for lib.dom.d.ts, the build pipeline, and the integration test suite.
For documentation on the test-specific type definitions (bun:test matchers, mock types, lifecycle hooks), see page 10.2. For the documentation site itself, see page 10.3.
bun-types is a TypeScript declaration package (@types-style) published to npm. It provides:
declare module "bun" module with the Bun namespace.globalThis additions, Timer, Loader, EventTarget, etc.).stream/web, buffer, url, node:tls, console, node:fs/promises).test-globals.d.ts).The package lives at `packages/bun-types/` and is referenced in the root workspace as bun-types. A sibling package packages/@types/bun re-exports it as @types/bun for tooling that auto-installs @types/* packages.
`packages/bun-types/package.json` specifies:
| Field | Value |
|---|---|
name | bun-types |
types | ./index.d.ts |
dependencies | @types/node: "*" |
scripts.build | bun scripts/build.ts |
scripts.test | tsc |
The files array includes all .d.ts files, vendor/**/*.d.ts, docs/**/*.md, CLAUDE.md, and README.md.
index.d.ts is the entry point. It uses /// <reference path="..." /> directives to include every other declaration file in order.
Diagram: index.d.ts reference graph
Sources: `packages/bun-types/index.d.ts1-33
Each file corresponds to a specific API area:
| File | API Area |
|---|---|
globals.d.ts | Global constructors: ReadableStream, Worker, WebSocket, Crypto, TextEncoder, Timer, Loader |
bun.d.ts | declare module "bun" — the Bun namespace with all core APIs |
overrides.d.ts | Augmentations of stream/web, buffer, url, node:tls, console, NodeJS.Process |
shell.d.ts | Bun.$ shell API — ShellPromise, ShellOutput, ShellError |
serve.d.ts | Bun.serve() — HTTP server types |
fetch.d.ts | fetch and related request/response types |
ffi.d.ts | bun:ffi — dlopen, CFunction, JSCallback |
sqlite.d.ts | bun:sqlite — Database, Statement |
sql.d.ts | Bun.SQL — PostgreSQL/MySQL client |
redis.d.ts | Valkey/Redis client |
s3.d.ts | Bun.S3Client, S3Options |
html-rewriter.d.ts | HTMLRewriter |
test.d.ts | bun:test module types (matchers, mocks) |
test-globals.d.ts | Opt-in global aliases (test, it, describe, jest, vi) |
devserver.d.ts | import.meta.hot HMR API |
jsc.d.ts | bun:jsc internal JSC APIs |
wasm.d.ts | WebAssembly namespace |
bundle.d.ts | bun:bundle feature flags |
security.d.ts | Security-related types |
extensions.d.ts | Additional interface extensions |
deprecated.d.ts | Deprecated types (marked @deprecated) |
bun.ns.d.ts | Final assembly of the Bun global namespace object |
bun.d.ts Namespace`packages/bun-types/bun.d.ts` is the largest file in the package. It uses declare module "bun" to define the Bun namespace. All types inside are accessible as Bun.TypeName from user code, or as named imports from "bun".
The top of bun.d.ts defines utility types that appear across many APIs:
| Type | Description |
|---|---|
PathLike | string | NodeJS.TypedArray | ArrayBufferLike | URL |
BufferSource | NodeJS.TypedArray | DataView | ArrayBufferLike |
StringOrBuffer | string | NodeJS.TypedArray | ArrayBufferLike |
MaybePromise<T> | T | Promise<T> |
BlobPart | string | Blob | BufferSource |
Sources: `packages/bun-types/bun.d.ts17-47
__internal Namespacebun.d.ts contains a namespace __internal with helper types used internally across declaration files.
| Helper Type | Purpose |
|---|---|
LibDomIsLoaded | true if lib.dom.d.ts is active (checks for onabort on globalThis) |
UseLibDomIfAvailable<K, Otherwise> | Picks the DOM type if lib.dom is loaded, otherwise uses Otherwise |
DistributedOmit<T, K> | Omit that distributes over union types |
XOR<A, B> | Exclusive-or of two object types |
Sources: `packages/bun-types/bun.d.ts49-99
globals.d.ts)globals.d.ts declares or augments global-scope symbols. It uses Bun.__internal.UseLibDomIfAvailable extensively to avoid conflicts when a project also loads lib.dom.d.ts.
Diagram: UseLibDomIfAvailable conflict resolution
Sources: `packages/bun-types/bun.d.ts50-69 `packages/bun-types/globals.d.ts72-188
Examples of where this pattern is applied in globals.d.ts:
declare var ReadableStream: Bun.__internal.UseLibDomIfAvailable<"ReadableStream", { ... }>;
declare var Worker: Bun.__internal.UseLibDomIfAvailable<"Worker", { ... }>;
declare var WebSocket: Bun.__internal.UseLibDomIfAvailable<"WebSocket", { ... }>;
declare var TextEncoder: Bun.__internal.UseLibDomIfAvailable<"TextEncoder", { ... }>;
declare var MessageEvent: Bun.__internal.UseLibDomIfAvailable<"MessageEvent", { ... }>;
globals.d.ts also defines:
Timer interface with .ref(), .unref(), .refresh(), .hasRef() — returned by setTimeout/setInterval.Loader global — exposes the JSC ESM module registry via Loader.registry and Loader.resolve.ReadableStreamDirectController — Bun's non-standard direct stream controller.ByteLengthQueuingStrategy, ReadableStreamDefaultController, ReadableStreamDefaultReader.Sources: `packages/bun-types/globals.d.ts1-760
overrides.d.ts)overrides.d.ts patches types from Node.js packages by augmenting their modules. This is how Bun adds methods to objects that are defined in @types/node.
Diagram: Module augmentation targets in overrides.d.ts
The BunConsumerConvenienceMethods interface in overrides.d.ts provides the text(), json(), and bytes() methods shared by ReadableStream and Blob. This interface is then merged into both via module augmentation.
Sources: `packages/bun-types/overrides.d.ts1-383
shell.d.ts)The Bun.$ API is declared in shell.d.ts inside declare module "bun". Key types:
| Type | Role |
|---|---|
$.ShellPromise | Extends Promise<ShellOutput>, fluent API with .cwd(), .env(), .quiet(), .text(), .json(), .lines() |
$.ShellOutput | Result of a completed shell command — .stdout, .stderr, .exitCode, .text(), .json() |
$.ShellError | Extends Error — thrown on non-zero exit. Has .exitCode, .stdout, .stderr |
$.Shell | Constructor for a configurable shell instance |
ShellExpression | Union of all valid interpolation types: string, Subprocess, ReadableStream, arrays, etc. |
$ | The tagged template function itself, also usable as a class |
Sources: `packages/bun-types/shell.d.ts1-200
test-globals.d.ts)test-globals.d.ts is intentionally excluded from index.d.ts. It must be opted into with a triple-slash directive:
It declares the following as module-level globals by aliasing from bun:test:
| Global | Source |
|---|---|
test, it | import("bun:test").test |
describe | import("bun:test").describe |
expect | import("bun:test").expect |
expectTypeOf | import("bun:test").expectTypeOf |
beforeAll, beforeEach, afterEach, afterAll | import("bun:test").* |
jest, vi | import("bun:test").jest, .vi |
xit, xtest, xdescribe | import("bun:test").* |
Without this reference, using test, describe, or expect as bare globals will produce TypeScript errors. This is by design — it prevents inadvertent inclusion of test globals in non-test code.
Sources: `packages/bun-types/test-globals.d.ts1-23
devserver.d.ts)devserver.d.ts extends the ImportMeta interface inside declare module "bun":
ImportMeta.hot — the HMR API object. Has .on(event, handler) and .dispose(handler).HMREventNames — union type of known event names: "beforeUpdate", "afterUpdate", "beforeFullReload", "beforePrune", "invalidate", "error", "ws:disconnect", "ws:connect".The .on() method accepts any string as an event name (for custom events), with known names providing typed payloads.
Sources: `packages/bun-types/devserver.d.ts1-40
The build script at `packages/bun-types/scripts/build.ts` performs two tasks:
BUN_VERSION from the environment (or Bun.version), strips any v prefix, and writes it into package.json. This ensures the published package version matches the Bun runtime version.src/init/rule.md from the repo root into the package as CLAUDE.md (a rules file for Claude/LLM usage).The build step is required before packing the package. It is invoked as:
cd packages/bun-types && bun run build
Sources: `packages/bun-types/scripts/build.ts1-20
The integration test at `test/integration/bun-types/bun-types.test.ts` verifies that the published package type-checks correctly. The test setup:
bun run build inside packages/bun-types.bun pm pack to produce a .tgz tarball.@types/bun shim that points to it.ts.createLanguageService) to type-check all .ts/.tsx files in test/integration/bun-types/fixture/.The diagnose() function in the test runs with skipLibCheck: false and skipDefaultLibCheck: false, catching errors in the declaration files themselves.
Diagram: Integration test pipeline
The fixture files test a broad range of APIs:
| Fixture file | APIs tested |
|---|---|
index.ts | Bun.file, Bun.$, S3Client, fetch, ReadableStream, Worker, HTMLRewriter, URL |
streams.ts | ReadableStream, WritableStream, TransformStream, compression streams |
spawn.ts | Bun.spawn, Bun.spawnSync, FileSink, PipedSubprocess |
serve-types.test.ts | Bun.serve, Bun.Server, WebSocket handler, routes |
websocket.ts | WebSocket constructor overloads |
crypto.ts | crypto.subtle, CryptoKey, randomUUID |
globals.ts | Bun.file, process, fs, http |
env.ts | Bun.env, process.env, ImportMetaEnv augmentation |
The tsgo test in the suite additionally verifies compatibility with TypeScript 7's native Go-based compiler (@typescript/native-preview).
Sources: `test/integration/bun-types/bun-types.test.ts1-310 `test/integration/bun-types/fixture/index.ts1-400
Users have two options for enabling bun-types:
Option 1: tsconfig.json types field
Option 2: Triple-slash reference in a .d.ts file
When @types/bun is installed (e.g. via bun add -d @types/bun), the package automatically re-exports bun-types via its own index.d.ts:
This matches the auto-discovery behavior TypeScript uses for @types/* packages.
Sources: `packages/@types/bun` workspace in `bun.lock23-29
Diagram: File-to-API mapping
Sources: `packages/bun-types/index.d.ts` `packages/bun-types/package.json`
Refresh this wiki
This wiki was recently refreshed. Please wait 2 days to refresh again.