Compare commits

..

1 Commits

Author SHA1 Message Date
Jarred Sumner
e4356ca035 test: add net bytes stats test 2025-05-28 18:06:49 -07:00
2343 changed files with 130208 additions and 215288 deletions

View File

@@ -1,6 +1,8 @@
ARG LLVM_VERSION="19"
ARG REPORTED_LLVM_VERSION="19.1.7"
ARG OLD_BUN_VERSION="1.1.38"
ARG DEFAULT_CFLAGS="-mno-omit-leaf-frame-pointer -fno-omit-frame-pointer -ffunction-sections -fdata-sections -faddrsig -fno-unwind-tables -fno-asynchronous-unwind-tables"
ARG DEFAULT_CXXFLAGS="-flto=full -fwhole-program-vtables -fforce-emit-vtables"
ARG BUILDKITE_AGENT_TAGS="queue=linux,os=linux,arch=${TARGETARCH}"
FROM --platform=$BUILDPLATFORM ubuntu:20.04 as base-arm64
@@ -10,6 +12,8 @@ FROM base-$TARGETARCH as base
ARG LLVM_VERSION
ARG OLD_BUN_VERSION
ARG TARGETARCH
ARG DEFAULT_CXXFLAGS
ARG DEFAULT_CFLAGS
ARG REPORTED_LLVM_VERSION
ENV DEBIAN_FRONTEND=noninteractive \
@@ -60,7 +64,9 @@ RUN echo "ARCH_PATH=$([ "$TARGETARCH" = "arm64" ] && echo "aarch64-linux-gnu" ||
ENV LD_LIBRARY_PATH=/usr/lib/gcc/${ARCH_PATH}/13:/usr/lib/${ARCH_PATH} \
LIBRARY_PATH=/usr/lib/gcc/${ARCH_PATH}/13:/usr/lib/${ARCH_PATH} \
CPLUS_INCLUDE_PATH=/usr/include/c++/13:/usr/include/${ARCH_PATH}/c++/13 \
C_INCLUDE_PATH=/usr/lib/gcc/${ARCH_PATH}/13/include
C_INCLUDE_PATH=/usr/lib/gcc/${ARCH_PATH}/13/include \
CFLAGS=${DEFAULT_CFLAGS} \
CXXFLAGS="${DEFAULT_CFLAGS} ${DEFAULT_CXXFLAGS}"
RUN if [ "$TARGETARCH" = "arm64" ]; then \
export ARCH_PATH="aarch64-linux-gnu"; \

View File

@@ -127,12 +127,12 @@ const testPlatforms = [
{ os: "linux", arch: "x64", distro: "debian", release: "12", tier: "latest" },
{ os: "linux", arch: "x64", baseline: true, distro: "debian", release: "12", tier: "latest" },
{ os: "linux", arch: "x64", profile: "asan", distro: "debian", release: "12", tier: "latest" },
{ os: "linux", arch: "aarch64", distro: "ubuntu", release: "25.04", tier: "latest" },
{ os: "linux", arch: "aarch64", distro: "ubuntu", release: "24.04", tier: "latest" },
{ os: "linux", arch: "x64", distro: "ubuntu", release: "25.04", tier: "latest" },
{ os: "linux", arch: "aarch64", distro: "ubuntu", release: "20.04", tier: "oldest" },
{ os: "linux", arch: "x64", distro: "ubuntu", release: "24.04", tier: "latest" },
{ os: "linux", arch: "x64", baseline: true, distro: "ubuntu", release: "25.04", tier: "latest" },
{ os: "linux", arch: "x64", distro: "ubuntu", release: "20.04", tier: "oldest" },
{ os: "linux", arch: "x64", baseline: true, distro: "ubuntu", release: "24.04", tier: "latest" },
{ os: "linux", arch: "x64", baseline: true, distro: "ubuntu", release: "20.04", tier: "oldest" },
{ os: "linux", arch: "aarch64", abi: "musl", distro: "alpine", release: "3.21", tier: "latest" },
{ os: "linux", arch: "x64", abi: "musl", distro: "alpine", release: "3.21", tier: "latest" },
{ os: "linux", arch: "x64", abi: "musl", baseline: true, distro: "alpine", release: "3.21", tier: "latest" },
@@ -309,19 +309,6 @@ function getCppAgent(platform, options) {
});
}
/**
* @returns {Platform}
*/
function getZigPlatform() {
return {
os: "linux",
arch: "aarch64",
abi: "musl",
distro: "alpine",
release: "3.21",
};
}
/**
* @param {Platform} platform
* @param {PipelineOptions} options
@@ -335,9 +322,19 @@ function getZigAgent(platform, options) {
// queue: "build-zig",
// };
return getEc2Agent(getZigPlatform(), options, {
instanceType: "r8g.large",
});
return getEc2Agent(
{
os: "linux",
arch: "aarch64",
abi: "musl",
distro: "alpine",
release: "3.21",
},
options,
{
instanceType: "r8g.large",
},
);
}
/**
@@ -450,7 +447,7 @@ function getBuildCppStep(platform, options) {
BUN_CPP_ONLY: "ON",
...getBuildEnv(platform, options),
},
// We used to build the C++ dependencies and bun in separate steps.
// We used to build the C++ dependencies and bun in seperate steps.
// However, as long as the zig build takes longer than both sequentially,
// it's cheaper to run them in the same step. Can be revisited in the future.
command: [`${command} --target bun`, `${command} --target dependencies`],
@@ -569,7 +566,7 @@ function getTestBunStep(platform, options, testOptions = {}) {
retry: getRetry(),
cancel_on_build_failing: isMergeQueue(),
parallelism: unifiedTests ? undefined : os === "darwin" ? 2 : 10,
timeout_in_minutes: profile === "asan" || os === "windows" ? 45 : 30,
timeout_in_minutes: profile === "asan" ? 45 : 30,
command:
os === "windows"
? `node .\\scripts\\runner.node.mjs ${args.join(" ")}`
@@ -922,7 +919,7 @@ function getOptionsStep() {
{
key: "unified-builds",
select: "Do you want to build each platform in a single step?",
hint: "If true, builds will not be split into separate steps (this will likely slow down the build)",
hint: "If true, builds will not be split into seperate steps (this will likely slow down the build)",
required: false,
default: "false",
options: booleanOptions,
@@ -930,7 +927,7 @@ function getOptionsStep() {
{
key: "unified-tests",
select: "Do you want to run tests in a single step?",
hint: "If true, tests will not be split into separate steps (this will be very slow)",
hint: "If true, tests will not be split into seperate steps (this will be very slow)",
required: false,
default: "false",
options: booleanOptions,
@@ -1108,11 +1105,6 @@ async function getPipeline(options = {}) {
steps.push(
...relevantBuildPlatforms.map(target => {
const imageKey = getImageKey(target);
const zigImageKey = getImageKey(getZigPlatform());
const dependsOn = imagePlatforms.has(zigImageKey) ? [`${zigImageKey}-build-image`] : [];
if (imagePlatforms.has(imageKey)) {
dependsOn.push(`${imageKey}-build-image`);
}
return getStepWithDependsOn(
{
@@ -1122,7 +1114,7 @@ async function getPipeline(options = {}) {
? [getBuildBunStep(target, options)]
: [getBuildCppStep(target, options), getBuildZigStep(target, options), getLinkBunStep(target, options)],
},
...dependsOn,
imagePlatforms.has(imageKey) ? `${imageKey}-build-image` : undefined,
);
}),
);

View File

@@ -1,92 +0,0 @@
# Upgrading Bun's Self-Reported Node.js Version
This guide explains how to upgrade the Node.js version that Bun reports for compatibility with Node.js packages and native addons.
## Overview
Bun reports a Node.js version for compatibility with the Node.js ecosystem. This affects:
- `process.version` output
- Node-API (N-API) compatibility
- Native addon ABI compatibility
- V8 API compatibility for addons using V8 directly
## Files That Always Need Updates
### 1. Bootstrap Scripts
- `scripts/bootstrap.sh` - Update `NODEJS_VERSION=`
- `scripts/bootstrap.ps1` - Update `$NODEJS_VERSION =`
### 2. CMake Configuration
- `cmake/Options.cmake`
- `NODEJS_VERSION` - The Node.js version string (e.g., "24.3.0")
- `NODEJS_ABI_VERSION` - The ABI version number (find using command below)
### 3. Version Strings
- `src/bun.js/bindings/BunProcess.cpp`
- Update `Bun__versions_node` with the Node.js version
- Update `Bun__versions_v8` with the V8 version (find using command below)
### 4. N-API Version
- `src/napi/js_native_api.h`
- Update `NAPI_VERSION` define (check Node.js release notes)
## Files That May Need Updates
Only check these if the build fails or tests crash after updating version numbers:
- V8 compatibility files in `src/bun.js/bindings/v8/` (if V8 API changed)
- Test files (if Node.js requires newer C++ standard)
## Quick Commands to Find Version Info
```bash
# Get latest Node.js version info
curl -s https://nodejs.org/dist/index.json | jq '.[0]'
# Get V8 version for a specific Node.js version (replace v24.3.0)
curl -s https://nodejs.org/dist/v24.3.0/node-v24.3.0-headers.tar.gz | tar -xzO node-v24.3.0/include/node/node_version.h | grep V8_VERSION
# Get ABI version for a specific Node.js version
curl -s https://nodejs.org/dist/v24.3.0/node-v24.3.0-headers.tar.gz | tar -xzO node-v24.3.0/include/node/node_version.h | grep NODE_MODULE_VERSION
# Or use the ABI registry
curl -s https://raw.githubusercontent.com/nodejs/node/main/doc/abi_version_registry.json | jq '.NODE_MODULE_VERSION."<version>"'
```
## Update Process
1. **Gather version info** using the commands above
2. **Update the required files** listed in the sections above
3. **Build and test**:
```bash
bun bd
bun bd -e "console.log(process.version)"
bun bd -e "console.log(process.versions.v8)"
bun bd test test/v8/v8.test.ts
bun bd test test/napi/napi.test.ts
```
4. **Check for V8 API changes** only if build fails or tests crash:
- Compare v8-function-callback.h between versions
- Check v8-internal.h for Isolate size changes
- Look for new required APIs in build errors
## If Build Fails or Tests Crash
The V8 API rarely has breaking changes between minor Node.js versions. If you encounter issues:
1. Check build errors for missing symbols or type mismatches
2. Compare V8 headers between old and new Node.js versions
3. Most issues can be resolved by implementing missing functions or adjusting structures
## Testing Checklist
- [ ] `process.version` returns correct version
- [ ] `process.versions.v8` returns correct V8 version
- [ ] `process.config.variables.node_module_version` returns correct ABI
- [ ] V8 tests pass
- [ ] N-API tests pass
## Notes
- Most upgrades only require updating version numbers
- Major V8 version changes (rare) may require API updates
- The V8 shim implements only APIs used by common native addons

View File

@@ -1,23 +0,0 @@
Upgrade Bun's Webkit fork to the latest upstream version of Webkit.
To do that:
- cd vendor/WebKit
- git fetch upstream
- git merge upstream main
- Fix the merge conflicts
- cd ../../ (back to bun)
- make jsc-build (this will take about 7 minutes)
- While it compiles, in another task review the JSC commits between the last version of Webkit and the new version. Write up a summary of the webkit changes in a file called "webkit-changes.md"
- bun run build:local (build a build of Bun with the new Webkit, make sure it compiles)
- After making sure it compiles, run some code to make sure things work. something like ./build/debug-local/bun-debug --print '42' should be all you need
- cd vendor/WebKit
- git commit -am "Upgrade Webkit to the latest version"
- git push
- get the commit SHA in the vendor/WebKit directory of your new commit
- cd ../../ (back to bun)
- Update WEBKIT_VERSION in cmake/tools/SetupWebKit.cmake to the commit SHA of your new commit
- git checkout -b bun/webkit-upgrade-<commit-sha>
- commit + push (without adding the webkit-changes.md file)
- create PR titled "Upgrade Webkit to the <commit-sha>", paste your webkit-changes.md into the PR description
- delete the webkit-changes.md file

View File

@@ -1,10 +0,0 @@
{
"snapshot": "snapshot-20250706-71021aff-cc0d-4a7f-a468-d443b16c4bf1",
"install": "bun install",
"terminals": [
{
"name": "bun build",
"command": "bun run build"
}
]
}

View File

@@ -1,41 +1,27 @@
---
description:
globs: src/**/*.cpp,src/**/*.zig
alwaysApply: false
description: How to build Bun
globs:
---
# How to build Bun
### Build Commands
## CMake
- **Build debug version**: `bun bd` or `bun run build:debug`
- Creates a debug build at `./build/debug/bun-debug`
- Compilation takes ~2.5 minutes
- **Run tests with your debug build**: `bun bd test <test-file>`
- **CRITICAL**: Never use `bun test` directly - it won't include your changes
- **Run any command with debug build**: `bun bd <command>`
Bun is built using CMake, which you can find in `CMakeLists.txt` and in the `cmake/` directory.
### Run a file
* `CMakeLists.txt`
* `cmake/`
* `Globals.cmake` - macros and functions used by all the other files
* `Options.cmake` - build options for configuring the build (e.g. debug/release mode)
* `CompilerFlags.cmake` - compiler and linker flags used by all the targets
* `tools/` - setup scripts for various build tools (e.g. llvm, zig, webkit, rust, etc.)
* `targets/` - targets for bun and its dependencies (e.g. brotli, boringssl, libuv, etc.)
To run a file, use:
## How to
There are `package.json` scripts that make it easy to build Bun without calling CMake directly, for example:
```sh
bun bd <file> <...args>
bun run build # builds a debug build: `build/debug/bun-debug`
bun run build:release # builds a release build: `build/release/bun`
bun run build:assert # builds a release build with debug assertions: `build/assert/bun`
```
**CRITICAL**: Never use `bun <file>` directly. It will not have your changes.
### Logging
`BUN_DEBUG_$(SCOPE)=1` enables debug logs for a specific debug log scope.
Debug logs look like this:
```zig
const log = bun.Output.scoped(.${SCOPE}, false);
// ...later
log("MY DEBUG LOG", .{})
```
### Code Generation
Code generation happens automatically as part of the build process. There are no commands to run.

View File

@@ -91,7 +91,7 @@ devTest("html file is watched", {
`files` holds the initial state, and the callback runs with the server running. `dev.fetch()` runs HTTP requests, while `dev.client()` opens a browser instance to the code.
Functions `dev.write` and `dev.patch` and `dev.delete` mutate the filesystem. Do not use `node:fs` APIs, as the dev server ones are hooked to wait for hot-reload, and all connected clients to receive changes.
Functions `dev.write` and `dev.patch` and `dev.delete` mutate the filesystem. Do not use `node:fs` APIs, as the dev server ones are hooked to wait for hot-reload, and all connected clients to recieve changes.
When a change performs a hard-reload, that must be explicitly annotated with `expectReload`. This tells `client-fixture.mjs` that the test is meant to reload the page once; All other hard reloads automatically fail the test.

View File

@@ -360,8 +360,9 @@ JSC_DEFINE_HOST_FUNCTION(x509CertificateConstructorConstruct, (JSGlobalObject *
auto* functionGlobalObject = defaultGlobalObject(getFunctionRealm(globalObject, newTarget.getObject()));
RETURN_IF_EXCEPTION(scope, {});
structure = InternalFunction::createSubclassStructure(globalObject, newTarget.getObject(), functionGlobalObject->NodeVMScriptStructure());
RETURN_IF_EXCEPTION(scope, {});
structure = InternalFunction::createSubclassStructure(
globalObject, newTarget.getObject(), functionGlobalObject->NodeVMScriptStructure());
scope.release();
}
return JSValue::encode(createX509Certificate(vm, globalObject, structure, arg));

View File

@@ -11,10 +11,10 @@ You'll find all of Bun's tests in the `test/` directory.
* `test/`
* `cli/` - CLI command tests, like `bun install` or `bun init`
* `js/` - JavaScript & TypeScript tests
* `bun/` - `Bun` APIs tests, separated by category, for example: `glob/` for `Bun.Glob` tests
* `node/` - Node.js module tests, separated by module, for example: `assert/` for `node:assert` tests
* `bun/` - `Bun` APIs tests, seperated by category, for example: `glob/` for `Bun.Glob` tests
* `node/` - Node.js module tests, seperated by module, for example: `assert/` for `node:assert` tests
* `test/` - Vendored Node.js tests, taken from the Node.js repository (does not conform to Bun's test style)
* `web/` - Web API tests, separated by category, for example: `fetch/` for `Request` and `Response` tests
* `web/` - Web API tests, seperated by category, for example: `fetch/` for `Request` and `Response` tests
* `third_party/` - npm package tests, to validate that basic usage works in Bun
* `napi/` - N-API tests
* `v8/` - V8 C++ API tests

View File

@@ -1,9 +1,8 @@
---
description: How Zig works with JavaScriptCore bindings generator
globs:
globs:
alwaysApply: false
---
# Bun's JavaScriptCore Class Bindings Generator
This document explains how Bun's class bindings generator works to bridge Zig and JavaScript code through JavaScriptCore (JSC).
@@ -25,7 +24,7 @@ The `.classes.ts` files define the JavaScript API using a declarative approach:
```typescript
// Example: encoding.classes.ts
define({
name: "TextDecoder",
name: "TextDecoder",
constructor: true,
JSType: "object",
finalize: true,
@@ -41,18 +40,17 @@ define({
},
fatal: {
// Read-only property
getter: true,
getter: true,
},
ignoreBOM: {
// Read-only property
getter: true,
},
},
}
}
});
```
Each class definition specifies:
- The class name
- Whether it has a constructor
- JavaScript type (object, function, etc.)
@@ -89,7 +87,7 @@ pub const TextDecoder = struct {
// Fields
});
}
// Prototype methods - note return type includes JSError
pub fn decode(
this: *TextDecoder,
@@ -98,23 +96,23 @@ pub const TextDecoder = struct {
) bun.JSError!JSC.JSValue {
// Implementation
}
// Getters
pub fn getEncoding(this: *TextDecoder, globalObject: *JSGlobalObject) JSC.JSValue {
return JSC.JSValue.createStringFromUTF8(globalObject, this.encoding);
}
pub fn getFatal(this: *TextDecoder, globalObject: *JSGlobalObject) JSC.JSValue {
return JSC.JSValue.jsBoolean(this.fatal);
}
// Cleanup - note standard pattern of using deinit/deref
fn deinit(this: *TextDecoder) void {
// Release any retained resources
// Free the pointer at the end.
bun.destroy(this);
}
// Finalize - called by JS garbage collector. This should call deinit, or deref if reference counted.
pub fn finalize(this: *TextDecoder) void {
this.deinit();
@@ -123,7 +121,6 @@ pub const TextDecoder = struct {
```
Key components in the Zig file:
- The struct containing native state
- `pub const js = JSC.Codegen.JS<ClassName>` to include generated code
- Constructor and methods using `bun.JSError!JSValue` return type for proper error handling
@@ -131,7 +128,6 @@ Key components in the Zig file:
- Methods matching the JavaScript interface
- Getters/setters for properties
- Proper resource cleanup pattern with `deinit()` and `finalize()`
- Update `src/bun.js/bindings/generated_classes_list.zig` to include the new class
## Code Generation System
@@ -144,7 +140,6 @@ The binding generator produces C++ code that connects JavaScript and Zig:
5. **Property Caching**: Implements the caching system for properties
The generated C++ code includes:
- A JSC wrapper class (`JSTextDecoder`)
- A prototype class (`JSTextDecoderPrototype`)
- A constructor function (`JSTextDecoderConstructor`)
@@ -157,29 +152,28 @@ The `CallFrame` object provides access to JavaScript execution context:
```zig
pub fn decode(
this: *TextDecoder,
this: *TextDecoder,
globalObject: *JSGlobalObject,
callFrame: *JSC.CallFrame
) bun.JSError!JSC.JSValue {
// Get arguments
const input = callFrame.argument(0);
const options = callFrame.argument(1);
// Get this value
const thisValue = callFrame.thisValue();
// Implementation with error handling
if (input.isUndefinedOrNull()) {
return globalObject.throw("Input cannot be null or undefined", .{});
}
// Return value or throw error
return JSC.JSValue.jsString(globalObject, "result");
}
```
CallFrame methods include:
- `argument(i)`: Get the i-th argument
- `argumentCount()`: Get the number of arguments
- `thisValue()`: Get the `this` value
@@ -207,17 +201,17 @@ JSC_DEFINE_CUSTOM_GETTER(TextDecoderPrototype__encodingGetterWrap, (...)) {
auto throwScope = DECLARE_THROW_SCOPE(vm);
JSTextDecoder* thisObject = jsCast<JSTextDecoder*>(JSValue::decode(encodedThisValue));
JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject);
// Check for cached value and return if present
if (JSValue cachedValue = thisObject->m_encoding.get())
return JSValue::encode(cachedValue);
// Get value from Zig implementation
JSC::JSValue result = JSC::JSValue::decode(
TextDecoderPrototype__getEncoding(thisObject->wrapped(), globalObject)
);
RETURN_IF_EXCEPTION(throwScope, {});
// Store in cache for future access
thisObject->m_encoding.set(vm, thisObject, result);
RELEASE_AND_RETURN(throwScope, JSValue::encode(result));
@@ -259,7 +253,7 @@ This system provides several key benefits:
1. **Automatic Memory Management**: The JavaScriptCore GC tracks and manages these values
2. **Proper Garbage Collection**: The WriteBarrier ensures values are properly visited during GC
3. **Consistent Access**: Zig code can easily get/set these cached JS values
4. **Performance**: Cached values avoid repeated computation or serialization
4. **Performance**: Cached values avoid repeated computation or serialization
### Use Cases
@@ -287,7 +281,7 @@ Bun uses a consistent pattern for resource cleanup:
pub fn deinit(this: *TextDecoder) void {
// Release resources like strings
this._encoding.deref(); // String deref pattern
// Free any buffers
if (this.buffer) |buffer| {
bun.default_allocator.free(buffer);
@@ -318,7 +312,7 @@ Bun uses `bun.JSError!JSValue` return type for proper error handling:
```zig
pub fn decode(
this: *TextDecoder,
this: *TextDecoder,
globalObject: *JSGlobalObject,
callFrame: *JSC.CallFrame
) bun.JSError!JSC.JSValue {
@@ -326,14 +320,13 @@ pub fn decode(
if (callFrame.argumentCount() < 1) {
return globalObject.throw("Missing required argument", .{});
}
// Or returning a success value
return JSC.JSValue.jsString(globalObject, "Success!");
}
```
This pattern allows Zig functions to:
1. Return JavaScript values on success
2. Throw JavaScript exceptions on error
3. Propagate errors automatically through the call stack
@@ -346,7 +339,7 @@ The binding system includes robust error handling:
// Example of type checking in generated code
JSTextDecoder* thisObject = jsDynamicCast<JSTextDecoder*>(callFrame->thisValue());
if (UNLIKELY(!thisObject)) {
scope.throwException(lexicalGlobalObject,
scope.throwException(lexicalGlobalObject,
Bun::createInvalidThisError(lexicalGlobalObject, callFrame->thisValue(), "TextDecoder"_s));
return {};
}
@@ -358,7 +351,7 @@ The binding system creates proper JavaScript prototype chains:
1. **Constructor**: JSTextDecoderConstructor with standard .prototype property
2. **Prototype**: JSTextDecoderPrototype with methods and properties
3. **Instances**: Each JSTextDecoder instance with **proto** pointing to prototype
3. **Instances**: Each JSTextDecoder instance with __proto__ pointing to prototype
This ensures JavaScript inheritance works as expected:
@@ -367,7 +360,7 @@ This ensures JavaScript inheritance works as expected:
void JSTextDecoderConstructor::finishCreation(VM& vm, JSC::JSGlobalObject* globalObject, JSTextDecoderPrototype* prototype)
{
Base::finishCreation(vm, 0, "TextDecoder"_s, PropertyAdditionMode::WithoutStructureTransition);
// Set up the prototype chain
putDirectWithoutTransition(vm, vm.propertyNames->prototype, prototype, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
ASSERT(inherits(info()));
@@ -379,7 +372,7 @@ void JSTextDecoderConstructor::finishCreation(VM& vm, JSC::JSGlobalObject* globa
The binding system is optimized for performance:
1. **Direct Pointer Access**: JavaScript objects maintain a direct pointer to Zig objects
2. **Property Caching**: WriteBarrier caching avoids repeated native calls for stable properties
2. **Property Caching**: WriteBarrier caching avoids repeated native calls for stable properties
3. **Memory Management**: JSC garbage collection integrated with Zig memory management
4. **Type Conversion**: Fast paths for common JavaScript/Zig type conversions
@@ -388,7 +381,6 @@ The binding system is optimized for performance:
To create a new class binding in Bun:
1. **Define the class interface** in a `.classes.ts` file:
```typescript
define({
name: "MyClass",
@@ -401,13 +393,12 @@ To create a new class binding in Bun:
myProperty: {
getter: true,
cache: true,
},
},
}
}
});
```
2. **Implement the native functionality** in a `.zig` file:
```zig
pub const MyClass = struct {
// Generated bindings
@@ -418,9 +409,9 @@ To create a new class binding in Bun:
// State
value: []const u8,
pub const new = bun.TrivialNew(@This());
// Constructor
pub fn constructor(
globalObject: *JSGlobalObject,
@@ -429,7 +420,7 @@ To create a new class binding in Bun:
const arg = callFrame.argument(0);
// Implementation
}
// Method
pub fn myMethod(
this: *MyClass,
@@ -438,17 +429,17 @@ To create a new class binding in Bun:
) bun.JSError!JSC.JSValue {
// Implementation
}
// Getter
pub fn getMyProperty(this: *MyClass, globalObject: *JSGlobalObject) JSC.JSValue {
return JSC.JSValue.jsString(globalObject, this.value);
}
// Resource cleanup
pub fn deinit(this: *MyClass) void {
// Clean up resources
}
pub fn finalize(this: *MyClass) void {
this.deinit();
bun.destroy(this);
@@ -483,13 +474,11 @@ For each Zig class, the system generates:
### 3. Zig Bindings
- **External Function Declarations**:
```zig
extern fn TextDecoderPrototype__decode(*TextDecoder, *JSC.JSGlobalObject, *JSC.CallFrame) callconv(JSC.conv) JSC.EncodedJSValue;
```
- **Cached Value Accessors**:
```zig
pub fn encodingGetCached(thisValue: JSC.JSValue) ?JSC.JSValue { ... }
pub fn encodingSetCached(thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) void { ... }

View File

@@ -5,6 +5,4 @@
#
# git config blame.ignoreRevsFile .git-blame-ignore-revs
#
4ec410e0d7c5f6a712c323444edbf56b48d432d8 # make @import("bun") work in zig (#19096)
dedd433cbf2e2fe38e51bc166e08fbcc601ad42b # JSValue.undefined -> .jsUndefined()
6b4662ff55f58247cc2fd22e85b4f9805b0950a5 # JSValue.jsUndefined() -> .js_undefined
4ec410e0d7c5f6a712c323444edbf56b48d432d8 # make @import("bun") work in zig (#19096)

13
.github/CODEOWNERS vendored
View File

@@ -1,5 +1,18 @@
# Project
/.github/CODEOWNERS @Jarred-Sumner
# Build system
/CMakeLists.txt @Electroid
/cmake/*.cmake @Electroid
/scripts/ @Electroid
# CI
/.buildkite/ @Electroid
/.github/workflows/ @Electroid
# Debugger protocol
/packages/bun-inspector-protocol/ @Electroid
/packages/bun-debug-adapter-protocol/ @Electroid
# Tests
/test/expectations.txt @Jarred-Sumner

View File

@@ -12,7 +12,7 @@ body:
If you need help or support using Bun, and are not reporting a bug, please
join our [Discord](https://discord.gg/CXdq2DP29u) server, where you can ask questions in the [`#help`](https://discord.gg/32EtH6p7HN) forum.
Make sure you are running the [latest](https://bun.com/docs/installation#upgrading) version of Bun.
Make sure you are running the [latest](https://bun.sh/docs/installation#upgrading) version of Bun.
The bug you are experiencing may already have been fixed.
Please try to include as much information as possible.

View File

@@ -2,44 +2,44 @@ name: 🇹 TypeScript Type Bug Report
description: Report an issue with TypeScript types
labels: [bug, types]
body:
- type: markdown
attributes:
value: |
Thank you for submitting a bug report. It helps make Bun better.
- type: markdown
attributes:
value: |
Thank you for submitting a bug report. It helps make Bun better.
If you need help or support using Bun, and are not reporting a bug, please
join our [Discord](https://discord.gg/CXdq2DP29u) server, where you can ask questions in the [`#help`](https://discord.gg/32EtH6p7HN) forum.
If you need help or support using Bun, and are not reporting a bug, please
join our [Discord](https://discord.gg/CXdq2DP29u) server, where you can ask questions in the [`#help`](https://discord.gg/32EtH6p7HN) forum.
Make sure you are running the [latest](https://bun.com/docs/installation#upgrading) version of Bun.
The bug you are experiencing may already have been fixed.
Make sure you are running the [latest](https://bun.sh/docs/installation#upgrading) version of Bun.
The bug you are experiencing may already have been fixed.
Please try to include as much information as possible.
Please try to include as much information as possible.
- type: input
attributes:
label: What version of Bun is running?
description: Copy the output of `bun --revision`
- type: input
attributes:
label: What platform is your computer?
description: |
For MacOS and Linux: copy the output of `uname -mprs`
For Windows: copy the output of `"$([Environment]::OSVersion | ForEach-Object VersionString) $(if ([Environment]::Is64BitOperatingSystem) { "x64" } else { "x86" })"` in the PowerShell console
- type: textarea
attributes:
label: What steps can reproduce the bug?
description: Explain the bug and provide a code snippet that can reproduce it.
validations:
required: true
- type: textarea
attributes:
label: What is the expected behavior?
description: If possible, please provide text instead of a screenshot.
- type: textarea
attributes:
label: What do you see instead?
description: If possible, please provide text instead of a screenshot.
- type: textarea
attributes:
label: Additional information
description: Is there anything else you think we should know?
- type: input
attributes:
label: What version of Bun is running?
description: Copy the output of `bun --revision`
- type: input
attributes:
label: What platform is your computer?
description: |
For MacOS and Linux: copy the output of `uname -mprs`
For Windows: copy the output of `"$([Environment]::OSVersion | ForEach-Object VersionString) $(if ([Environment]::Is64BitOperatingSystem) { "x64" } else { "x86" })"` in the PowerShell console
- type: textarea
attributes:
label: What steps can reproduce the bug?
description: Explain the bug and provide a code snippet that can reproduce it.
validations:
required: true
- type: textarea
attributes:
label: What is the expected behavior?
description: If possible, please provide text instead of a screenshot.
- type: textarea
attributes:
label: What do you see instead?
description: If possible, please provide text instead of a screenshot.
- type: textarea
attributes:
label: Additional information
description: Is there anything else you think we should know?

View File

@@ -2,7 +2,6 @@ name: Prefilled crash report
description: Report a crash in Bun
labels:
- crash
- needs triage
body:
- type: markdown
attributes:

View File

@@ -1,58 +0,0 @@
name: Codex Test Sync
on:
pull_request:
types: [labeled, opened]
env:
BUN_VERSION: "1.2.15"
jobs:
sync-node-tests:
runs-on: ubuntu-latest
if: |
(github.event.action == 'labeled' && github.event.label.name == 'codex') ||
(github.event.action == 'opened' && contains(github.event.pull_request.labels.*.name, 'codex')) ||
contains(github.head_ref, 'codex')
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
- name: Setup Bun
uses: ./.github/actions/setup-bun
with:
bun-version: ${{ env.BUN_VERSION }}
- name: Get changed files
id: changed-files
uses: tj-actions/changed-files@v44
with:
files: |
test/js/node/test/parallel/**/*.{js,mjs,ts}
test/js/node/test/sequential/**/*.{js,mjs,ts}
- name: Sync tests
if: steps.changed-files.outputs.any_changed == 'true'
shell: bash
run: |
echo "Changed test files:"
echo "${{ steps.changed-files.outputs.all_changed_files }}"
# Process each changed test file
for file in ${{ steps.changed-files.outputs.all_changed_files }}; do
# Extract test name from file path
test_name=$(basename "$file" | sed 's/\.[^.]*$//')
echo "Syncing test: $test_name"
bun node:test:cp "$test_name"
done
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "Sync Node.js tests with upstream"

View File

@@ -1,30 +1,28 @@
name: autofix.ci
name: format
permissions:
contents: read
contents: write
on:
workflow_call:
workflow_dispatch:
pull_request:
merge_group:
push:
branches: ["main"]
env:
BUN_VERSION: "1.2.11"
LLVM_VERSION: "19.1.7"
LLVM_VERSION_MAJOR: "19"
jobs:
autofix:
format:
name: Format
runs-on: ubuntu-latest
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Configure Git
run: |
git config --global core.autocrlf true
@@ -46,13 +44,23 @@ jobs:
version: 0.14.0
- name: Zig Format
run: |
zig fmt src
./scripts/sort-imports.ts src
zig fmt src
bun scripts/zig-remove-unreferenced-top-level-decls.ts src/
zig fmt src/**.zig
- name: Commit
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "`bun run zig-format`"
- name: Prettier Format
run: |
bun run prettier
- name: Commit
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "`bun run prettier`"
- name: Clang Format
run: |
bun run clang-format
- uses: autofix-ci/action@635ffb0c9798bd160680f18fd73371e355b85f27
- name: Commit
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "`bun run clang-format`"

View File

@@ -202,7 +202,7 @@ jobs:
body: |
Update `bun-types` version to ${{ steps.bun-version.outputs.BUN_VERSION }}
https://bun.com/blog/${{ env.BUN_VERSION }}
https://bun.sh/blog/${{ env.BUN_VERSION }}
push-to-fork: oven-sh/DefinitelyTyped
branch: ${{env.BUN_VERSION}}
docker:

32
.github/workflows/run-lint.yml vendored Normal file
View File

@@ -0,0 +1,32 @@
name: Lint
permissions:
contents: read
env:
BUN_VERSION: "1.2.0"
on:
workflow_call:
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
outputs:
text_output: ${{ steps.lint.outputs.text_output }}
json_output: ${{ steps.lint.outputs.json_output }}
count: ${{ steps.lint.outputs.count }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: ./.github/actions/setup-bun
with:
bun-version: ${{ env.BUN_VERSION }}
- name: Install Dependencies
run: |
bun --cwd=packages/bun-internal-test install
- name: Lint
id: lint
run: |
bun packages/bun-internal-test/src/linter.ts

View File

@@ -1,99 +0,0 @@
name: Update hdrhistogram
on:
schedule:
- cron: "0 4 * * 0"
workflow_dispatch:
jobs:
check-update:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@v4
- name: Check hdrhistogram version
id: check-version
run: |
set -euo pipefail
# Extract the commit hash from the line after COMMIT
CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildHdrHistogram.cmake)
if [ -z "$CURRENT_VERSION" ]; then
echo "Error: Could not find COMMIT line in BuildHdrHistogram.cmake"
exit 1
fi
# Validate that it looks like a git hash
if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
echo "Error: Invalid git hash format in BuildHdrHistogram.cmake"
echo "Found: $CURRENT_VERSION"
echo "Expected: 40 character hexadecimal string"
exit 1
fi
echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
LATEST_RELEASE=$(curl -sL https://api.github.com/repos/HdrHistogram/HdrHistogram_c/releases/latest)
if [ -z "$LATEST_RELEASE" ]; then
echo "Error: Failed to fetch latest release from GitHub API"
exit 1
fi
LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
echo "Error: Could not extract tag name from GitHub API response"
exit 1
fi
LATEST_TAG_SHA=$(curl -sL "https://api.github.com/repos/HdrHistogram/HdrHistogram_c/git/refs/tags/$LATEST_TAG" | jq -r '.object.sha')
if [ -z "$LATEST_TAG_SHA" ] || [ "$LATEST_TAG_SHA" = "null" ]; then
echo "Error: Could not fetch SHA for tag $LATEST_TAG"
exit 1
fi
LATEST_SHA=$(curl -sL "https://api.github.com/repos/HdrHistogram/HdrHistogram_c/git/tags/$LATEST_TAG_SHA" | jq -r '.object.sha')
if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
echo "Error: Could not fetch SHA for tag $LATEST_TAG @ $LATEST_TAG_SHA"
exit 1
fi
if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
echo "Error: Invalid SHA format received from GitHub"
echo "Found: $LATEST_SHA"
echo "Expected: 40 character hexadecimal string"
exit 1
fi
echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
- name: Update version if needed
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
run: |
set -euo pipefail
# Handle multi-line format where COMMIT and its value are on separate lines
sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildHdrHistogram.cmake
- name: Create Pull Request
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
uses: peter-evans/create-pull-request@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
add-paths: |
cmake/targets/BuildHdrHistogram.cmake
commit-message: "deps: update hdrhistogram to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
title: "deps: update hdrhistogram to ${{ steps.check-version.outputs.tag }}"
delete-branch: true
branch: deps/update-cares-${{ github.run_number }}
body: |
## What does this PR do?
Updates hdrhistogram to version ${{ steps.check-version.outputs.tag }}
Compare: https://github.com/HdrHistogram/HdrHistogram_c/compare/${{ steps.check-version.outputs.current }}...${{ steps.check-version.outputs.latest }}
Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-cares.yml)

View File

@@ -1,99 +0,0 @@
name: Update highway
on:
schedule:
- cron: "0 4 * * 0"
workflow_dispatch:
jobs:
check-update:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@v4
- name: Check highway version
id: check-version
run: |
set -euo pipefail
# Extract the commit hash from the line after COMMIT
CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildHighway.cmake)
if [ -z "$CURRENT_VERSION" ]; then
echo "Error: Could not find COMMIT line in BuildHighway.cmake"
exit 1
fi
# Validate that it looks like a git hash
if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
echo "Error: Invalid git hash format in BuildHighway.cmake"
echo "Found: $CURRENT_VERSION"
echo "Expected: 40 character hexadecimal string"
exit 1
fi
echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
LATEST_RELEASE=$(curl -sL https://api.github.com/repos/google/highway/releases/latest)
if [ -z "$LATEST_RELEASE" ]; then
echo "Error: Failed to fetch latest release from GitHub API"
exit 1
fi
LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
echo "Error: Could not extract tag name from GitHub API response"
exit 1
fi
LATEST_TAG_SHA=$(curl -sL "https://api.github.com/repos/google/highway/git/refs/tags/$LATEST_TAG" | jq -r '.object.sha')
if [ -z "$LATEST_TAG_SHA" ] || [ "$LATEST_TAG_SHA" = "null" ]; then
echo "Error: Could not fetch SHA for tag $LATEST_TAG"
exit 1
fi
LATEST_SHA=$(curl -sL "https://api.github.com/repos/google/highway/git/tags/$LATEST_TAG_SHA" | jq -r '.object.sha')
if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
echo "Error: Could not fetch SHA for tag $LATEST_TAG @ $LATEST_TAG_SHA"
exit 1
fi
if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
echo "Error: Invalid SHA format received from GitHub"
echo "Found: $LATEST_SHA"
echo "Expected: 40 character hexadecimal string"
exit 1
fi
echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
- name: Update version if needed
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
run: |
set -euo pipefail
# Handle multi-line format where COMMIT and its value are on separate lines
sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildHighway.cmake
- name: Create Pull Request
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
uses: peter-evans/create-pull-request@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
add-paths: |
cmake/targets/BuildHighway.cmake
commit-message: "deps: update highway to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
title: "deps: update highway to ${{ steps.check-version.outputs.tag }}"
delete-branch: true
branch: deps/update-cares-${{ github.run_number }}
body: |
## What does this PR do?
Updates highway to version ${{ steps.check-version.outputs.tag }}
Compare: https://github.com/google/highway/compare/${{ steps.check-version.outputs.current }}...${{ steps.check-version.outputs.latest }}
Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-cares.yml)

View File

@@ -21,16 +21,16 @@ jobs:
set -euo pipefail
# Extract the commit hash from the line after COMMIT
CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/CloneZstd.cmake)
CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildZstd.cmake)
if [ -z "$CURRENT_VERSION" ]; then
echo "Error: Could not find COMMIT line in CloneZstd.cmake"
echo "Error: Could not find COMMIT line in BuildZstd.cmake"
exit 1
fi
# Validate that it looks like a git hash
if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
echo "Error: Invalid git hash format in CloneZstd.cmake"
echo "Error: Invalid git hash format in BuildZstd.cmake"
echo "Found: $CURRENT_VERSION"
echo "Expected: 40 character hexadecimal string"
exit 1
@@ -76,7 +76,7 @@ jobs:
run: |
set -euo pipefail
# Handle multi-line format where COMMIT and its value are on separate lines
sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/CloneZstd.cmake
sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildZstd.cmake
- name: Create Pull Request
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
@@ -84,7 +84,7 @@ jobs:
with:
token: ${{ secrets.GITHUB_TOKEN }}
add-paths: |
cmake/targets/CloneZstd.cmake
cmake/targets/BuildZstd.cmake
commit-message: "deps: update zstd to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
title: "deps: update zstd to ${{ steps.check-version.outputs.tag }}"
delete-branch: true

View File

@@ -1,47 +0,0 @@
name: VSCode Extension Publish
on:
workflow_dispatch:
inputs:
version:
description: "Version to publish (e.g. 0.0.25) - Check the marketplace for the latest version"
required: true
type: string
jobs:
publish:
name: "Publish to VS Code Marketplace"
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: ./.github/actions/setup-bun
with:
bun-version: "1.2.18"
- name: Install dependencies (root)
run: bun install
- name: Install dependencies
run: bun install
working-directory: packages/bun-vscode
- name: Set Version
run: bun pm version ${{ github.event.inputs.version }} --no-git-tag-version --allow-same-version
working-directory: packages/bun-vscode
- name: Build (inspector protocol)
run: bun install && bun run build
working-directory: packages/bun-inspector-protocol
- name: Build (vscode extension)
run: bun run build
working-directory: packages/bun-vscode
- name: Publish
if: success()
run: bunx vsce publish
env:
VSCE_PAT: ${{ secrets.VSCODE_EXTENSION }}
working-directory: packages/bun-vscode/extension

1
.gitignore vendored
View File

@@ -36,7 +36,6 @@
*.out.refresh.js
*.pdb
*.sqlite
*.swp
*.tmp
*.trace
*.wat

View File

@@ -1 +1,16 @@
command source -C -s true -e true misctools/lldb/init.lldb
# Tell LLDB what to do when the debugged process receives SIGPWR: pass it through to the process
# (-p), but do not stop the process (-s) or notify the user (-n).
#
# JSC's garbage collector sends this signal (as configured by Bun WebKit in
# Thread::initializePlatformThreading() in ThreadingPOSIX.cpp) to the JS thread to suspend or resume
# it. So stopping the process would just create noise when debugging any long-running script.
process handle -p true -s false -n false SIGPWR
command script import misctools/lldb/lldb_pretty_printers.py
type category enable zig.lang
type category enable zig.std
command script import misctools/lldb/lldb_webkit.py
command script delete btjs
command alias btjs p {printf("gathering btjs trace...\n");printf("%s\n", (char*)dumpBtjsTrace())}

1005
.vscode/launch.json generated vendored

File diff suppressed because it is too large Load Diff

View File

@@ -168,5 +168,4 @@
"WebKit/WebInspectorUI": true,
},
"git.detectSubmodules": false,
// "bun.test.customScript": "./build/debug/bun-debug test"
}

View File

@@ -1 +0,0 @@
CLAUDE.md

36
AGENTS.md Normal file
View File

@@ -0,0 +1,36 @@
## bun tests
**IMPORTANT**: use the `bun bd` command instead of the `bun` command. For example:
✅ Good
```sh
bun bd test internal/ban-words.test.ts
bun bd ./foo.ts
```
The `bun bd` command runs the DEBUG build. If you forget to run the debug build, your changes will not be reflected..
### Run a file
To run a file, you can use the `bun bd <file-path>` command.
```sh
bun bd ./foo.ts
```
### Run tests
To run a single test, you need to use the `bun bd test <test-name>` command.
```sh
bun bd test internal/ban-words.test.ts
```
You must ALWAYS make sure to pass a file path to the `bun bd test <file-path>` command. DO NOT try to run ALL the tests at once unless you're in a specific subdirectory.
### Run a Node.js test
```sh
bun bd --silent node:test test-fs-link
```

245
CLAUDE.md
View File

@@ -1,245 +0,0 @@
This is the Bun repository - an all-in-one JavaScript runtime & toolkit designed for speed, with a bundler, test runner, and Node.js-compatible package manager. It's written primarily in Zig with C++ for JavaScriptCore integration, powered by WebKit's JavaScriptCore engine.
## Building and Running Bun
### Build Commands
- **Build debug version**: `bun bd`
- Creates a debug build at `./build/debug/bun-debug`
- Compilation takes ~5 minutes. Don't timeout, be patient.
- **Run tests with your debug build**: `bun bd test <test-file>`
- **CRITICAL**: Never use `bun test` directly - it won't include your changes
- **Run any command with debug build**: `bun bd <command>`
### Other Build Variants
- `bun run build:release` - Release build
Address sanitizer is enabled by default in debug builds of Bun.
## Testing
### Running Tests
- **Single test file**: `bun bd test test/js/bun/http/serve.test.ts`
- **Fuzzy match test file**: `bun bd test http/serve.test.ts`
- **With filter**: `bun bd test test/js/bun/http/serve.test.ts -t "should handle"`
### Test Organization
- `test/js/bun/` - Bun-specific API tests (http, crypto, ffi, shell, etc.)
- `test/js/node/` - Node.js compatibility tests
- `test/js/web/` - Web API tests (fetch, WebSocket, streams, etc.)
- `test/cli/` - CLI command tests (install, run, test, etc.)
- `test/regression/issue/` - Regression tests (create one per bug fix)
- `test/bundler/` - Bundler and transpiler tests
- `test/integration/` - End-to-end integration tests
- `test/napi/` - N-API compatibility tests
- `test/v8/` - V8 C++ API compatibility tests
### Writing Tests
Tests use Bun's Jest-compatible test runner with proper test fixtures:
```typescript
import { test, expect } from "bun:test";
import { bunEnv, bunExe, tempDirWithFiles } from "harness";
test("my feature", async () => {
// Create temp directory with test files
const dir = tempDirWithFiles("test-prefix", {
"index.js": `console.log("hello");`,
});
// Spawn Bun process
await using proc = Bun.spawn({
cmd: [bunExe(), "index.js"],
env: bunEnv,
cwd: dir,
});
const [stdout, stderr, exitCode] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);
expect(exitCode).toBe(0);
expect(stdout).toBe("hello\n");
});
```
## Code Architecture
### Language Structure
- **Zig code** (`src/*.zig`): Core runtime, JavaScript bindings, package manager
- **C++ code** (`src/bun.js/bindings/*.cpp`): JavaScriptCore bindings, Web APIs
- **TypeScript** (`src/js/`): Built-in JavaScript modules with special syntax (see JavaScript Modules section)
- **Generated code**: Many files are auto-generated from `.classes.ts` and other sources
### Core Source Organization
#### Runtime Core (`src/`)
- `bun.zig` - Main entry point
- `cli.zig` - CLI command orchestration
- `js_parser.zig`, `js_lexer.zig`, `js_printer.zig` - JavaScript parsing/printing
- `transpiler.zig` - Wrapper around js_parser with sourcemap support
- `resolver/` - Module resolution system
- `allocators/` - Custom memory allocators for performance
#### JavaScript Runtime (`src/bun.js/`)
- `bindings/` - C++ JavaScriptCore bindings
- Generated classes from `.classes.ts` files
- Manual bindings for complex APIs
- `api/` - Bun-specific APIs
- `server.zig` - HTTP server implementation
- `FFI.zig` - Foreign Function Interface
- `crypto.zig` - Cryptographic operations
- `glob.zig` - File pattern matching
- `node/` - Node.js compatibility layer
- Module implementations (fs, path, crypto, etc.)
- Process and Buffer APIs
- `webcore/` - Web API implementations
- `fetch.zig` - Fetch API
- `streams.zig` - Web Streams
- `Blob.zig`, `Response.zig`, `Request.zig`
- `event_loop/` - Event loop and task management
#### Build Tools & Package Manager
- `src/bundler/` - JavaScript bundler
- Advanced tree-shaking
- CSS processing
- HTML handling
- `src/install/` - Package manager
- `lockfile/` - Lockfile handling
- `npm.zig` - npm registry client
- `lifecycle_script_runner.zig` - Package scripts
#### Other Key Components
- `src/shell/` - Cross-platform shell implementation
- `src/css/` - CSS parser and processor
- `src/http/` - HTTP client implementation
- `websocket_client/` - WebSocket client (including deflate support)
- `src/sql/` - SQL database integrations
- `src/bake/` - Server-side rendering framework
### JavaScript Class Implementation (C++)
When implementing JavaScript classes in C++:
1. Create three classes if there's a public constructor:
- `class Foo : public JSC::JSDestructibleObject` (if has C++ fields)
- `class FooPrototype : public JSC::JSNonFinalObject`
- `class FooConstructor : public JSC::InternalFunction`
2. Define properties using HashTableValue arrays
3. Add iso subspaces for classes with C++ fields
4. Cache structures in ZigGlobalObject
## Development Workflow
### Code Formatting
- `bun run prettier` - Format JS/TS files
- `bun run zig-format` - Format Zig files
- `bun run clang-format` - Format C++ files
### Watching for Changes
- `bun run watch` - Incremental Zig compilation with error checking
- `bun run watch-windows` - Windows-specific watch mode
### Code Generation
Code generation happens automatically as part of the build process. The main scripts are:
- `src/codegen/generate-classes.ts` - Generates Zig & C++ bindings from `*.classes.ts` files
- `src/codegen/generate-jssink.ts` - Generates stream-related classes
- `src/codegen/bundle-modules.ts` - Bundles built-in modules like `node:fs`
- `src/codegen/bundle-functions.ts` - Bundles global functions like `ReadableStream`
In development, bundled modules can be reloaded without rebuilding Zig by running `bun run build`.
## JavaScript Modules (`src/js/`)
Built-in JavaScript modules use special syntax and are organized as:
- `node/` - Node.js compatibility modules (`node:fs`, `node:path`, etc.)
- `bun/` - Bun-specific modules (`bun:ffi`, `bun:sqlite`, etc.)
- `thirdparty/` - NPM modules we replace (like `ws`)
- `internal/` - Internal modules not exposed to users
- `builtins/` - Core JavaScript builtins (streams, console, etc.)
### Special Syntax in Built-in Modules
1. **`$` prefix** - Access to private properties and JSC intrinsics:
```js
const arr = $Array.from(...); // Private global
map.$set(...); // Private method
const arr2 = $newArrayWithSize(5); // JSC intrinsic
```
2. **`require()`** - Must use string literals, resolved at compile time:
```js
const fs = require("fs"); // Directly loads by numeric ID
```
3. **Debug helpers**:
- `$debug()` - Like console.log but stripped in release builds
- `$assert()` - Assertions stripped in release builds
- `if($debug) {}` - Check if debug env var is set
4. **Platform detection**: `process.platform` and `process.arch` are inlined and dead-code eliminated
5. **Export syntax**: Use `export default` which gets converted to a return statement:
```js
export default {
readFile,
writeFile,
};
```
Note: These are NOT ES modules. The preprocessor converts `$` to `@` (JSC's actual syntax) and handles the special functions.
## CI
Bun uses BuildKite for CI. To get the status of a PR, you can use the following command:
```bash
bun ci
```
## Important Development Notes
1. **Never use `bun test` or `bun <file>` directly** - always use `bun bd test` or `bun bd <command>`. `bun bd` compiles & runs the debug build.
2. **Use `await using`** for proper resource cleanup with Bun APIs (Bun.spawn, Bun.serve, Bun.connect, etc.)
3. **Follow existing code style** - check neighboring files for patterns
4. **Create regression tests** in `test/regression/issue/` when fixing bugs
5. **Use absolute paths** - Always use absolute paths in file operations
6. **Avoid shell commands** - Don't use `find` or `grep` in tests; use Bun's Glob and built-in tools
7. **Memory management** - In Zig code, be careful with allocators and use defer for cleanup
8. **Cross-platform** - Test on macOS, Linux, and Windows when making platform-specific changes
9. **Debug builds** - Use `BUN_DEBUG_QUIET_LOGS=1` to disable debug logging, or `BUN_DEBUG_<scope>=1` to enable specific scopes
10. **Transpiled source** - Find transpiled files in `/tmp/bun-debug-src/` for debugging
## Key APIs and Features
### Bun-Specific APIs
- **Bun.serve()** - High-performance HTTP server
- **Bun.spawn()** - Process spawning with better performance than Node.js
- **Bun.file()** - Fast file I/O operations
- **Bun.write()** - Unified API for writing to files, stdout, etc.
- **Bun.$ (Shell)** - Cross-platform shell scripting
- **Bun.SQLite** - Native SQLite integration
- **Bun.FFI** - Call native libraries from JavaScript
- **Bun.Glob** - Fast file pattern matching

View File

@@ -1,6 +1,6 @@
Configuring a development environment for Bun can take 10-30 minutes depending on your internet connection and computer speed. You will need ~10GB of free disk space for the repository and build artifacts.
If you are using Windows, please refer to [this guide](https://bun.com/docs/project/building-windows)
If you are using Windows, please refer to [this guide](https://bun.sh/docs/project/building-windows)
## Install Dependencies
@@ -37,7 +37,7 @@ Before starting, you will need to already have a release build of Bun installed,
{% codetabs %}
```bash#Native
$ curl -fsSL https://bun.com/install | bash
$ curl -fsSL https://bun.sh/install | bash
```
```bash#npm
@@ -144,14 +144,6 @@ $ bun bd test foo.test.ts
$ bun bd ./foo.ts
```
Bun generally takes about 2.5 minutes to compile a debug build when there are Zig changes. If your development workflow is "change one line, save, rebuild", you will spend too much time waiting for the build to finish. Instead:
- Batch up your changes
- Ensure zls is running with incremental watching for LSP errors (if you use VSCode and install Zig and run `bun run build` once to download Zig, this should just work)
- Prefer using the debugger ("CodeLLDB" in VSCode) to step through the code.
- Use debug logs. `BUN_DEBUG_<scope>=1` will enable debug logging for the corresponding `Output.scoped(.<scope>, false)` logs. You can also set `BUN_DEBUG_QUIET_LOGS=1` to disable all debug logging that isn't explicitly enabled. To dump debug lgos into a file, `BUN_DEBUG=<path-to-file>.log`. Debug logs are aggressively removed in release builds.
- src/js/\*\*.ts changes are pretty much instant to rebuild. C++ changes are a bit slower, but still much faster than the Zig code (Zig is one compilation unit, C++ is many).
## Code generation scripts
Several code generation scripts are used during Bun's build process. These are run automatically when changes are made to certain files.
@@ -160,7 +152,6 @@ In particular, these are:
- `./src/codegen/generate-jssink.ts` -- Generates `build/debug/codegen/JSSink.cpp`, `build/debug/codegen/JSSink.h` which implement various classes for interfacing with `ReadableStream`. This is internally how `FileSink`, `ArrayBufferSink`, `"type": "direct"` streams and other code related to streams works.
- `./src/codegen/generate-classes.ts` -- Generates `build/debug/codegen/ZigGeneratedClasses*`, which generates Zig & C++ bindings for JavaScriptCore classes implemented in Zig. In `**/*.classes.ts` files, we define the interfaces for various classes, methods, prototypes, getters/setters etc which the code generator reads to generate boilerplate code implementing the JavaScript objects in C++ and wiring them up to Zig
- `./src/codegen/cppbind.ts` -- Generates automatic Zig bindings for C++ functions marked with `[[ZIG_EXPORT]]` attributes.
- `./src/codegen/bundle-modules.ts` -- Bundles built-in modules like `node:fs`, `bun:ffi` into files we can include in the final binary. In development, these can be reloaded without rebuilding Zig (you still need to run `bun run build`, but it re-reads the transpiled files from disk afterwards). In release builds, these are embedded into the binary.
- `./src/codegen/bundle-functions.ts` -- Bundles globally-accessible functions implemented in JavaScript/TypeScript like `ReadableStream`, `WritableStream`, and a handful more. These are used similarly to the builtin modules, but the output more closely aligns with what WebKit/Safari does for Safari's built-in functions so that we can copy-paste the implementations from WebKit as a starting point.
@@ -188,7 +179,6 @@ To run a release build from a pull request, you can use the `bun-pr` npm package
bunx bun-pr <pr-number>
bunx bun-pr <branch-name>
bunx bun-pr "https://github.com/oven-sh/bun/pull/1234566"
bunx bun-pr --asan <pr-number> # Linux x64 only
```
This will download the release build from the pull request and add it to `$PATH` as `bun-${pr-number}`. You can then run the build with `bun-${pr-number}`.
@@ -199,18 +189,24 @@ bun-1234566 --version
This works by downloading the release build from the GitHub Actions artifacts on the linked pull request. You may need the `gh` CLI installed to authenticate with GitHub.
## AddressSanitizer
## Valgrind
[AddressSanitizer](https://en.wikipedia.org/wiki/AddressSanitizer) helps find memory issues, and is enabled by default in debug builds of Bun on Linux and macOS. This includes the Zig code and all dependencies. It makes the Zig code take about 2x longer to build, if that's stopping you from being productive you can disable it by setting `-Denable_asan=$<IF:$<BOOL:${ENABLE_ASAN}>,true,false>` to `-Denable_asan=false` in the `cmake/targets/BuildBun.cmake` file, but generally we recommend batching your changes up between builds.
On Linux, valgrind can help find memory issues.
To build a release build with Address Sanitizer, run:
Keep in mind:
- JavaScriptCore doesn't support valgrind. It will report spurious errors.
- Valgrind is slow
- Mimalloc will sometimes cause spurious errors when debug build is enabled
You'll need a very recent version of Valgrind due to DWARF 5 debug symbols. You may need to manually compile Valgrind instead of using it from your Linux package manager.
`--fair-sched=try` is necessary if running multithreaded code in Bun (such as the bundler). Otherwise it will hang.
```bash
$ bun run build:release:asan
$ valgrind --fair-sched=try --track-origins=yes bun-debug <args>
```
In CI, we run our test suite with at least one target that is built with Address Sanitizer.
## Building WebKit locally + Debug mode of JSC
WebKit is not cloned by default (to save time and disk space). To clone and build WebKit locally, run:

2
LATEST
View File

@@ -1 +1 @@
1.2.19
1.2.15

View File

@@ -980,7 +980,7 @@ release-create-auto-updater:
.PHONY: release-create
release-create:
gh release create --title "bun v$(PACKAGE_JSON_VERSION)" "$(BUN_BUILD_TAG)"
gh release create --repo=$(BUN_AUTO_UPDATER_REPO) --title "bun v$(PACKAGE_JSON_VERSION)" "$(BUN_BUILD_TAG)" -n "See https://github.com/oven-sh/bun/releases/tag/$(BUN_BUILD_TAG) for release notes. Using the install script or bun upgrade is the recommended way to install bun. Join bun's Discord to get access https://bun.com/discord"
gh release create --repo=$(BUN_AUTO_UPDATER_REPO) --title "bun v$(PACKAGE_JSON_VERSION)" "$(BUN_BUILD_TAG)" -n "See https://github.com/oven-sh/bun/releases/tag/$(BUN_BUILD_TAG) for release notes. Using the install script or bun upgrade is the recommended way to install bun. Join bun's Discord to get access https://bun.sh/discord"
release-bin-entitlements:
@@ -1977,7 +1977,7 @@ integration-test-dev: # to run integration tests
USE_EXISTING_PROCESS=true TEST_SERVER_URL=http://localhost:3000 node test/scripts/browser.js
copy-install:
cp src/cli/install.sh ../bun.com/docs/install.html
cp src/cli/install.sh ../bun.sh/docs/install.html
copy-to-bun-release-dir: copy-to-bun-release-dir-bin copy-to-bun-release-dir-dsym
@@ -2019,28 +2019,28 @@ vendor-dev: assert-deps submodule npm-install-dev vendor-without-npm
.PHONY: bun
bun:
@echo 'makefile is deprecated - use `cmake` / `bun run build`'
@echo 'See https://bun.com/docs/project/contributing for more details'
@echo 'See https://bun.sh/docs/project/contributing for more details'
cpp:
@echo 'makefile is deprecated - use `cmake` / `bun run build`'
@echo 'See https://bun.com/docs/project/contributing for more details'
@echo 'See https://bun.sh/docs/project/contributing for more details'
zig:
@echo 'makefile is deprecated - use `cmake` / `bun run build`'
@echo 'See https://bun.com/docs/project/contributing for more details'
@echo 'See https://bun.sh/docs/project/contributing for more details'
dev:
@echo 'makefile is deprecated - use `cmake` / `bun run build`'
@echo 'See https://bun.com/docs/project/contributing for more details'
@echo 'See https://bun.sh/docs/project/contributing for more details'
setup:
@echo 'makefile is deprecated - use `cmake` / `bun run build`'
@echo 'See https://bun.com/docs/project/contributing for more details'
@echo 'See https://bun.sh/docs/project/contributing for more details'
bindings:
@echo 'makefile is deprecated - use `cmake` / `bun run build`'
@echo 'See https://bun.com/docs/project/contributing for more details'
@echo 'See https://bun.sh/docs/project/contributing for more details'
help:
@echo 'makefile is deprecated - use `cmake` / `bun run build`'
@echo 'See https://bun.com/docs/project/contributing for more details'
@echo 'See https://bun.sh/docs/project/contributing for more details'

588
README.md
View File

@@ -1,16 +1,16 @@
<p align="center">
<a href="https://bun.com"><img src="https://github.com/user-attachments/assets/50282090-adfd-4ddb-9e27-c30753c6b161" alt="Logo" height=170></a>
<a href="https://bun.sh"><img src="https://github.com/user-attachments/assets/50282090-adfd-4ddb-9e27-c30753c6b161" alt="Logo" height=170></a>
</p>
<h1 align="center">Bun</h1>
<p align="center">
<a href="https://bun.com/discord" target="_blank"><img height=20 src="https://img.shields.io/discord/876711213126520882" /></a>
<a href="https://bun.sh/discord" target="_blank"><img height=20 src="https://img.shields.io/discord/876711213126520882" /></a>
<img src="https://img.shields.io/github/stars/oven-sh/bun" alt="stars">
<a href="https://twitter.com/jarredsumner/status/1542824445810642946"><img src="https://img.shields.io/static/v1?label=speed&message=fast&color=success" alt="Bun speed" /></a>
</p>
<div align="center">
<a href="https://bun.com/docs">Documentation</a>
<a href="https://bun.sh/docs">Documentation</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://discord.com/invite/CXdq2DP29u">Discord</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
@@ -20,7 +20,7 @@
<br />
</div>
### [Read the docs →](https://bun.com/docs)
### [Read the docs →](https://bun.sh/docs)
## What is Bun?
@@ -47,14 +47,12 @@ Bun supports Linux (x64 & arm64), macOS (x64 & Apple Silicon) and Windows (x64).
> **Linux users** — Kernel version 5.6 or higher is strongly recommended, but the minimum is 5.1.
> **x64 users** — if you see "illegal instruction" or similar errors, check our [CPU requirements](https://bun.com/docs/installation#cpu-requirements-and-baseline-builds)
```sh
# with install script (recommended)
curl -fsSL https://bun.com/install | bash
curl -fsSL https://bun.sh/install | bash
# on windows
powershell -c "irm bun.com/install.ps1 | iex"
powershell -c "irm bun.sh/install.ps1 | iex"
# with npm
npm install -g bun
@@ -87,329 +85,351 @@ bun upgrade --canary
## Quick links
- Intro
- [What is Bun?](https://bun.com/docs/index)
- [Installation](https://bun.com/docs/installation)
- [Quickstart](https://bun.com/docs/quickstart)
- [TypeScript](https://bun.com/docs/typescript)
- [What is Bun?](https://bun.sh/docs/index)
- [Installation](https://bun.sh/docs/installation)
- [Quickstart](https://bun.sh/docs/quickstart)
- [TypeScript](https://bun.sh/docs/typescript)
- Templating
- [`bun init`](https://bun.com/docs/cli/init)
- [`bun create`](https://bun.com/docs/cli/bun-create)
- [`bun init`](https://bun.sh/docs/cli/init)
- [`bun create`](https://bun.sh/docs/cli/bun-create)
- CLI
- [`bun upgrade`](https://bun.com/docs/cli/bun-upgrade)
- [`bun upgrade`](https://bun.sh/docs/cli/bun-upgrade)
- Runtime
- [`bun run`](https://bun.com/docs/cli/run)
- [File types (Loaders)](https://bun.com/docs/runtime/loaders)
- [TypeScript](https://bun.com/docs/runtime/typescript)
- [JSX](https://bun.com/docs/runtime/jsx)
- [Environment variables](https://bun.com/docs/runtime/env)
- [Bun APIs](https://bun.com/docs/runtime/bun-apis)
- [Web APIs](https://bun.com/docs/runtime/web-apis)
- [Node.js compatibility](https://bun.com/docs/runtime/nodejs-apis)
- [Single-file executable](https://bun.com/docs/bundler/executables)
- [Plugins](https://bun.com/docs/runtime/plugins)
- [Watch mode / Hot Reloading](https://bun.com/docs/runtime/hot)
- [Module resolution](https://bun.com/docs/runtime/modules)
- [Auto-install](https://bun.com/docs/runtime/autoimport)
- [bunfig.toml](https://bun.com/docs/runtime/bunfig)
- [Debugger](https://bun.com/docs/runtime/debugger)
- [$ Shell](https://bun.com/docs/runtime/shell)
- [`bun run`](https://bun.sh/docs/cli/run)
- [File types (Loaders)](https://bun.sh/docs/runtime/loaders)
- [TypeScript](https://bun.sh/docs/runtime/typescript)
- [JSX](https://bun.sh/docs/runtime/jsx)
- [Environment variables](https://bun.sh/docs/runtime/env)
- [Bun APIs](https://bun.sh/docs/runtime/bun-apis)
- [Web APIs](https://bun.sh/docs/runtime/web-apis)
- [Node.js compatibility](https://bun.sh/docs/runtime/nodejs-apis)
- [Single-file executable](https://bun.sh/docs/bundler/executables)
- [Plugins](https://bun.sh/docs/runtime/plugins)
- [Watch mode / Hot Reloading](https://bun.sh/docs/runtime/hot)
- [Module resolution](https://bun.sh/docs/runtime/modules)
- [Auto-install](https://bun.sh/docs/runtime/autoimport)
- [bunfig.toml](https://bun.sh/docs/runtime/bunfig)
- [Debugger](https://bun.sh/docs/runtime/debugger)
- [$ Shell](https://bun.sh/docs/runtime/shell)
- Package manager
- [`bun install`](https://bun.com/docs/cli/install)
- [`bun add`](https://bun.com/docs/cli/add)
- [`bun remove`](https://bun.com/docs/cli/remove)
- [`bun update`](https://bun.com/docs/cli/update)
- [`bun link`](https://bun.com/docs/cli/link)
- [`bun unlink`](https://bun.com/docs/cli/unlink)
- [`bun pm`](https://bun.com/docs/cli/pm)
- [`bun outdated`](https://bun.com/docs/cli/outdated)
- [`bun publish`](https://bun.com/docs/cli/publish)
- [`bun patch`](https://bun.com/docs/install/patch)
- [`bun patch-commit`](https://bun.com/docs/cli/patch-commit)
- [Global cache](https://bun.com/docs/install/cache)
- [Workspaces](https://bun.com/docs/install/workspaces)
- [Lifecycle scripts](https://bun.com/docs/install/lifecycle)
- [Filter](https://bun.com/docs/cli/filter)
- [Lockfile](https://bun.com/docs/install/lockfile)
- [Scopes and registries](https://bun.com/docs/install/registries)
- [Overrides and resolutions](https://bun.com/docs/install/overrides)
- [`.npmrc`](https://bun.com/docs/install/npmrc)
- [`bun install`](https://bun.sh/docs/cli/install)
- [`bun add`](https://bun.sh/docs/cli/add)
- [`bun remove`](https://bun.sh/docs/cli/remove)
- [`bun update`](https://bun.sh/docs/cli/update)
- [`bun link`](https://bun.sh/docs/cli/link)
- [`bun unlink`](https://bun.sh/docs/cli/unlink)
- [`bun pm`](https://bun.sh/docs/cli/pm)
- [`bun outdated`](https://bun.sh/docs/cli/outdated)
- [`bun publish`](https://bun.sh/docs/cli/publish)
- [`bun patch`](https://bun.sh/docs/install/patch)
- [`bun patch-commit`](https://bun.sh/docs/cli/patch-commit)
- [Global cache](https://bun.sh/docs/install/cache)
- [Workspaces](https://bun.sh/docs/install/workspaces)
- [Lifecycle scripts](https://bun.sh/docs/install/lifecycle)
- [Filter](https://bun.sh/docs/cli/filter)
- [Lockfile](https://bun.sh/docs/install/lockfile)
- [Scopes and registries](https://bun.sh/docs/install/registries)
- [Overrides and resolutions](https://bun.sh/docs/install/overrides)
- [`.npmrc`](https://bun.sh/docs/install/npmrc)
- Bundler
- [`Bun.build`](https://bun.com/docs/bundler)
- [Loaders](https://bun.com/docs/bundler/loaders)
- [Plugins](https://bun.com/docs/bundler/plugins)
- [Macros](https://bun.com/docs/bundler/macros)
- [vs esbuild](https://bun.com/docs/bundler/vs-esbuild)
- [Single-file executable](https://bun.com/docs/bundler/executables)
- [CSS](https://bun.com/docs/bundler/css)
- [HTML](https://bun.com/docs/bundler/html)
- [Hot Module Replacement (HMR)](https://bun.com/docs/bundler/hmr)
- [Full-stack with HTML imports](https://bun.com/docs/bundler/fullstack)
- [`Bun.build`](https://bun.sh/docs/bundler)
- [Loaders](https://bun.sh/docs/bundler/loaders)
- [Plugins](https://bun.sh/docs/bundler/plugins)
- [Macros](https://bun.sh/docs/bundler/macros)
- [vs esbuild](https://bun.sh/docs/bundler/vs-esbuild)
- [Single-file executable](https://bun.sh/docs/bundler/executables)
- [CSS](https://bun.sh/docs/bundler/css)
- [HTML](https://bun.sh/docs/bundler/html)
- [Hot Module Replacement (HMR)](https://bun.sh/docs/bundler/hmr)
- [Full-stack with HTML imports](https://bun.sh/docs/bundler/fullstack)
- Test runner
- [`bun test`](https://bun.com/docs/cli/test)
- [Writing tests](https://bun.com/docs/test/writing)
- [Watch mode](https://bun.com/docs/test/hot)
- [Lifecycle hooks](https://bun.com/docs/test/lifecycle)
- [Mocks](https://bun.com/docs/test/mocks)
- [Snapshots](https://bun.com/docs/test/snapshots)
- [Dates and times](https://bun.com/docs/test/time)
- [DOM testing](https://bun.com/docs/test/dom)
- [Code coverage](https://bun.com/docs/test/coverage)
- [Configuration](https://bun.com/docs/test/configuration)
- [Discovery](https://bun.com/docs/test/discovery)
- [Reporters](https://bun.com/docs/test/reporters)
- [Runtime Behavior](https://bun.com/docs/test/runtime-behavior)
- [`bun test`](https://bun.sh/docs/cli/test)
- [Writing tests](https://bun.sh/docs/test/writing)
- [Watch mode](https://bun.sh/docs/test/hot)
- [Lifecycle hooks](https://bun.sh/docs/test/lifecycle)
- [Mocks](https://bun.sh/docs/test/mocks)
- [Snapshots](https://bun.sh/docs/test/snapshots)
- [Dates and times](https://bun.sh/docs/test/time)
- [DOM testing](https://bun.sh/docs/test/dom)
- [Code coverage](https://bun.sh/docs/test/coverage)
- [Configuration](https://bun.sh/docs/test/configuration)
- [Discovery](https://bun.sh/docs/test/discovery)
- [Reporters](https://bun.sh/docs/test/reporters)
- [Runtime Behavior](https://bun.sh/docs/test/runtime-behavior)
- Package runner
- [`bunx`](https://bun.com/docs/cli/bunx)
- [`bunx`](https://bun.sh/docs/cli/bunx)
- API
- [HTTP server (`Bun.serve`)](https://bun.com/docs/api/http)
- [WebSockets](https://bun.com/docs/api/websockets)
- [Workers](https://bun.com/docs/api/workers)
- [Binary data](https://bun.com/docs/api/binary-data)
- [Streams](https://bun.com/docs/api/streams)
- [File I/O (`Bun.file`)](https://bun.com/docs/api/file-io)
- [import.meta](https://bun.com/docs/api/import-meta)
- [SQLite (`bun:sqlite`)](https://bun.com/docs/api/sqlite)
- [PostgreSQL (`Bun.sql`)](https://bun.com/docs/api/sql)
- [Redis (`Bun.redis`)](https://bun.com/docs/api/redis)
- [S3 Client (`Bun.s3`)](https://bun.com/docs/api/s3)
- [FileSystemRouter](https://bun.com/docs/api/file-system-router)
- [TCP sockets](https://bun.com/docs/api/tcp)
- [UDP sockets](https://bun.com/docs/api/udp)
- [Globals](https://bun.com/docs/api/globals)
- [$ Shell](https://bun.com/docs/runtime/shell)
- [Child processes (spawn)](https://bun.com/docs/api/spawn)
- [Transpiler (`Bun.Transpiler`)](https://bun.com/docs/api/transpiler)
- [Hashing](https://bun.com/docs/api/hashing)
- [Colors (`Bun.color`)](https://bun.com/docs/api/color)
- [Console](https://bun.com/docs/api/console)
- [FFI (`bun:ffi`)](https://bun.com/docs/api/ffi)
- [C Compiler (`bun:ffi` cc)](https://bun.com/docs/api/cc)
- [HTMLRewriter](https://bun.com/docs/api/html-rewriter)
- [Testing (`bun:test`)](https://bun.com/docs/api/test)
- [Cookies (`Bun.Cookie`)](https://bun.com/docs/api/cookie)
- [Utils](https://bun.com/docs/api/utils)
- [Node-API](https://bun.com/docs/api/node-api)
- [Glob (`Bun.Glob`)](https://bun.com/docs/api/glob)
- [Semver (`Bun.semver`)](https://bun.com/docs/api/semver)
- [DNS](https://bun.com/docs/api/dns)
- [fetch API extensions](https://bun.com/docs/api/fetch)
- [HTTP server (`Bun.serve`)](https://bun.sh/docs/api/http)
- [WebSockets](https://bun.sh/docs/api/websockets)
- [Workers](https://bun.sh/docs/api/workers)
- [Binary data](https://bun.sh/docs/api/binary-data)
- [Streams](https://bun.sh/docs/api/streams)
- [File I/O (`Bun.file`)](https://bun.sh/docs/api/file-io)
- [import.meta](https://bun.sh/docs/api/import-meta)
- [SQLite (`bun:sqlite`)](https://bun.sh/docs/api/sqlite)
- [PostgreSQL (`Bun.sql`)](https://bun.sh/docs/api/sql)
- [Redis (`Bun.redis`)](https://bun.sh/docs/api/redis)
- [S3 Client (`Bun.s3`)](https://bun.sh/docs/api/s3)
- [FileSystemRouter](https://bun.sh/docs/api/file-system-router)
- [TCP sockets](https://bun.sh/docs/api/tcp)
- [UDP sockets](https://bun.sh/docs/api/udp)
- [Globals](https://bun.sh/docs/api/globals)
- [$ Shell](https://bun.sh/docs/runtime/shell)
- [Child processes (spawn)](https://bun.sh/docs/api/spawn)
- [Transpiler (`Bun.Transpiler`)](https://bun.sh/docs/api/transpiler)
- [Hashing](https://bun.sh/docs/api/hashing)
- [Colors (`Bun.color`)](https://bun.sh/docs/api/color)
- [Console](https://bun.sh/docs/api/console)
- [FFI (`bun:ffi`)](https://bun.sh/docs/api/ffi)
- [C Compiler (`bun:ffi` cc)](https://bun.sh/docs/api/cc)
- [HTMLRewriter](https://bun.sh/docs/api/html-rewriter)
- [Testing (`bun:test`)](https://bun.sh/docs/api/test)
- [Cookies (`Bun.Cookie`)](https://bun.sh/docs/api/cookie)
- [Utils](https://bun.sh/docs/api/utils)
- [Node-API](https://bun.sh/docs/api/node-api)
- [Glob (`Bun.Glob`)](https://bun.sh/docs/api/glob)
- [Semver (`Bun.semver`)](https://bun.sh/docs/api/semver)
- [DNS](https://bun.sh/docs/api/dns)
- [fetch API extensions](https://bun.sh/docs/api/fetch)
## Guides
- Binary
- [Convert a Blob to a string](https://bun.com/guides/binary/blob-to-string)
- [Convert a Buffer to a blob](https://bun.com/guides/binary/buffer-to-blob)
- [Convert a Blob to a DataView](https://bun.com/guides/binary/blob-to-dataview)
- [Convert a Buffer to a string](https://bun.com/guides/binary/buffer-to-string)
- [Convert a Blob to a ReadableStream](https://bun.com/guides/binary/blob-to-stream)
- [Convert a Blob to a Uint8Array](https://bun.com/guides/binary/blob-to-typedarray)
- [Convert a DataView to a string](https://bun.com/guides/binary/dataview-to-string)
- [Convert a Uint8Array to a Blob](https://bun.com/guides/binary/typedarray-to-blob)
- [Convert a Blob to an ArrayBuffer](https://bun.com/guides/binary/blob-to-arraybuffer)
- [Convert an ArrayBuffer to a Blob](https://bun.com/guides/binary/arraybuffer-to-blob)
- [Convert a Buffer to a Uint8Array](https://bun.com/guides/binary/buffer-to-typedarray)
- [Convert a Uint8Array to a Buffer](https://bun.com/guides/binary/typedarray-to-buffer)
- [Convert a Uint8Array to a string](https://bun.com/guides/binary/typedarray-to-string)
- [Convert a Buffer to an ArrayBuffer](https://bun.com/guides/binary/buffer-to-arraybuffer)
- [Convert an ArrayBuffer to a Buffer](https://bun.com/guides/binary/arraybuffer-to-buffer)
- [Convert an ArrayBuffer to a string](https://bun.com/guides/binary/arraybuffer-to-string)
- [Convert a Uint8Array to a DataView](https://bun.com/guides/binary/typedarray-to-dataview)
- [Convert a Buffer to a ReadableStream](https://bun.com/guides/binary/buffer-to-readablestream)
- [Convert a Uint8Array to an ArrayBuffer](https://bun.com/guides/binary/typedarray-to-arraybuffer)
- [Convert an ArrayBuffer to a Uint8Array](https://bun.com/guides/binary/arraybuffer-to-typedarray)
- [Convert an ArrayBuffer to an array of numbers](https://bun.com/guides/binary/arraybuffer-to-array)
- [Convert a Uint8Array to a ReadableStream](https://bun.com/guides/binary/typedarray-to-readablestream)
- [Convert a Blob to a string](https://bun.sh/guides/binary/blob-to-string)
- [Convert a Buffer to a blob](https://bun.sh/guides/binary/buffer-to-blob)
- [Convert a Blob to a DataView](https://bun.sh/guides/binary/blob-to-dataview)
- [Convert a Buffer to a string](https://bun.sh/guides/binary/buffer-to-string)
- [Convert a Blob to a ReadableStream](https://bun.sh/guides/binary/blob-to-stream)
- [Convert a Blob to a Uint8Array](https://bun.sh/guides/binary/blob-to-typedarray)
- [Convert a DataView to a string](https://bun.sh/guides/binary/dataview-to-string)
- [Convert a Uint8Array to a Blob](https://bun.sh/guides/binary/typedarray-to-blob)
- [Convert a Blob to an ArrayBuffer](https://bun.sh/guides/binary/blob-to-arraybuffer)
- [Convert an ArrayBuffer to a Blob](https://bun.sh/guides/binary/arraybuffer-to-blob)
- [Convert a Buffer to a Uint8Array](https://bun.sh/guides/binary/buffer-to-typedarray)
- [Convert a Uint8Array to a Buffer](https://bun.sh/guides/binary/typedarray-to-buffer)
- [Convert a Uint8Array to a string](https://bun.sh/guides/binary/typedarray-to-string)
- [Convert a Buffer to an ArrayBuffer](https://bun.sh/guides/binary/buffer-to-arraybuffer)
- [Convert an ArrayBuffer to a Buffer](https://bun.sh/guides/binary/arraybuffer-to-buffer)
- [Convert an ArrayBuffer to a string](https://bun.sh/guides/binary/arraybuffer-to-string)
- [Convert a Uint8Array to a DataView](https://bun.sh/guides/binary/typedarray-to-dataview)
- [Convert a Buffer to a ReadableStream](https://bun.sh/guides/binary/buffer-to-readablestream)
- [Convert a Uint8Array to an ArrayBuffer](https://bun.sh/guides/binary/typedarray-to-arraybuffer)
- [Convert an ArrayBuffer to a Uint8Array](https://bun.sh/guides/binary/arraybuffer-to-typedarray)
- [Convert an ArrayBuffer to an array of numbers](https://bun.sh/guides/binary/arraybuffer-to-array)
- [Convert a Uint8Array to a ReadableStream](https://bun.sh/guides/binary/typedarray-to-readablestream)
- Ecosystem
- [Use React and JSX](https://bun.com/guides/ecosystem/react)
- [Use EdgeDB with Bun](https://bun.com/guides/ecosystem/edgedb)
- [Use Prisma with Bun](https://bun.com/guides/ecosystem/prisma)
- [Add Sentry to a Bun app](https://bun.com/guides/ecosystem/sentry)
- [Create a Discord bot](https://bun.com/guides/ecosystem/discordjs)
- [Run Bun as a daemon with PM2](https://bun.com/guides/ecosystem/pm2)
- [Use Drizzle ORM with Bun](https://bun.com/guides/ecosystem/drizzle)
- [Build an app with Nuxt and Bun](https://bun.com/guides/ecosystem/nuxt)
- [Build an app with Qwik and Bun](https://bun.com/guides/ecosystem/qwik)
- [Build an app with Astro and Bun](https://bun.com/guides/ecosystem/astro)
- [Build an app with Remix and Bun](https://bun.com/guides/ecosystem/remix)
- [Build a frontend using Vite and Bun](https://bun.com/guides/ecosystem/vite)
- [Build an app with Next.js and Bun](https://bun.com/guides/ecosystem/nextjs)
- [Run Bun as a daemon with systemd](https://bun.com/guides/ecosystem/systemd)
- [Deploy a Bun application on Render](https://bun.com/guides/ecosystem/render)
- [Build an HTTP server using Hono and Bun](https://bun.com/guides/ecosystem/hono)
- [Build an app with SvelteKit and Bun](https://bun.com/guides/ecosystem/sveltekit)
- [Build an app with SolidStart and Bun](https://bun.com/guides/ecosystem/solidstart)
- [Build an HTTP server using Elysia and Bun](https://bun.com/guides/ecosystem/elysia)
- [Build an HTTP server using StricJS and Bun](https://bun.com/guides/ecosystem/stric)
- [Containerize a Bun application with Docker](https://bun.com/guides/ecosystem/docker)
- [Build an HTTP server using Express and Bun](https://bun.com/guides/ecosystem/express)
- [Use Neon Postgres through Drizzle ORM](https://bun.com/guides/ecosystem/neon-drizzle)
- [Server-side render (SSR) a React component](https://bun.com/guides/ecosystem/ssr-react)
- [Read and write data to MongoDB using Mongoose and Bun](https://bun.com/guides/ecosystem/mongoose)
- [Use Neon's Serverless Postgres with Bun](https://bun.com/guides/ecosystem/neon-serverless-postgres)
- [Use React and JSX](https://bun.sh/guides/ecosystem/react)
- [Use EdgeDB with Bun](https://bun.sh/guides/ecosystem/edgedb)
- [Use Prisma with Bun](https://bun.sh/guides/ecosystem/prisma)
- [Add Sentry to a Bun app](https://bun.sh/guides/ecosystem/sentry)
- [Create a Discord bot](https://bun.sh/guides/ecosystem/discordjs)
- [Run Bun as a daemon with PM2](https://bun.sh/guides/ecosystem/pm2)
- [Use Drizzle ORM with Bun](https://bun.sh/guides/ecosystem/drizzle)
- [Build an app with Nuxt and Bun](https://bun.sh/guides/ecosystem/nuxt)
- [Build an app with Qwik and Bun](https://bun.sh/guides/ecosystem/qwik)
- [Build an app with Astro and Bun](https://bun.sh/guides/ecosystem/astro)
- [Build an app with Remix and Bun](https://bun.sh/guides/ecosystem/remix)
- [Build a frontend using Vite and Bun](https://bun.sh/guides/ecosystem/vite)
- [Build an app with Next.js and Bun](https://bun.sh/guides/ecosystem/nextjs)
- [Run Bun as a daemon with systemd](https://bun.sh/guides/ecosystem/systemd)
- [Deploy a Bun application on Render](https://bun.sh/guides/ecosystem/render)
- [Build an HTTP server using Hono and Bun](https://bun.sh/guides/ecosystem/hono)
- [Build an app with SvelteKit and Bun](https://bun.sh/guides/ecosystem/sveltekit)
- [Build an app with SolidStart and Bun](https://bun.sh/guides/ecosystem/solidstart)
- [Build an HTTP server using Elysia and Bun](https://bun.sh/guides/ecosystem/elysia)
- [Build an HTTP server using StricJS and Bun](https://bun.sh/guides/ecosystem/stric)
- [Containerize a Bun application with Docker](https://bun.sh/guides/ecosystem/docker)
- [Build an HTTP server using Express and Bun](https://bun.sh/guides/ecosystem/express)
- [Use Neon Postgres through Drizzle ORM](https://bun.sh/guides/ecosystem/neon-drizzle)
- [Server-side render (SSR) a React component](https://bun.sh/guides/ecosystem/ssr-react)
- [Read and write data to MongoDB using Mongoose and Bun](https://bun.sh/guides/ecosystem/mongoose)
- [Use Neon's Serverless Postgres with Bun](https://bun.sh/guides/ecosystem/neon-serverless-postgres)
- HTMLRewriter
- [Extract links from a webpage using HTMLRewriter](https://bun.com/guides/html-rewriter/extract-links)
- [Extract social share images and Open Graph tags](https://bun.com/guides/html-rewriter/extract-social-meta)
- [Extract links from a webpage using HTMLRewriter](https://bun.sh/guides/html-rewriter/extract-links)
- [Extract social share images and Open Graph tags](https://bun.sh/guides/html-rewriter/extract-social-meta)
- HTTP
- [Hot reload an HTTP server](https://bun.com/guides/http/hot)
- [Common HTTP server usage](https://bun.com/guides/http/server)
- [Write a simple HTTP server](https://bun.com/guides/http/simple)
- [Configure TLS on an HTTP server](https://bun.com/guides/http/tls)
- [Send an HTTP request using fetch](https://bun.com/guides/http/fetch)
- [Proxy HTTP requests using fetch()](https://bun.com/guides/http/proxy)
- [Start a cluster of HTTP servers](https://bun.com/guides/http/cluster)
- [Stream a file as an HTTP Response](https://bun.com/guides/http/stream-file)
- [fetch with unix domain sockets in Bun](https://bun.com/guides/http/fetch-unix)
- [Upload files via HTTP using FormData](https://bun.com/guides/http/file-uploads)
- [Streaming HTTP Server with Async Iterators](https://bun.com/guides/http/stream-iterator)
- [Streaming HTTP Server with Node.js Streams](https://bun.com/guides/http/stream-node-streams-in-bun)
- [Hot reload an HTTP server](https://bun.sh/guides/http/hot)
- [Common HTTP server usage](https://bun.sh/guides/http/server)
- [Write a simple HTTP server](https://bun.sh/guides/http/simple)
- [Configure TLS on an HTTP server](https://bun.sh/guides/http/tls)
- [Send an HTTP request using fetch](https://bun.sh/guides/http/fetch)
- [Proxy HTTP requests using fetch()](https://bun.sh/guides/http/proxy)
- [Start a cluster of HTTP servers](https://bun.sh/guides/http/cluster)
- [Stream a file as an HTTP Response](https://bun.sh/guides/http/stream-file)
- [fetch with unix domain sockets in Bun](https://bun.sh/guides/http/fetch-unix)
- [Upload files via HTTP using FormData](https://bun.sh/guides/http/file-uploads)
- [Streaming HTTP Server with Async Iterators](https://bun.sh/guides/http/stream-iterator)
- [Streaming HTTP Server with Node.js Streams](https://bun.sh/guides/http/stream-node-streams-in-bun)
- Install
- [Add a dependency](https://bun.com/guides/install/add)
- [Add a Git dependency](https://bun.com/guides/install/add-git)
- [Add a peer dependency](https://bun.com/guides/install/add-peer)
- [Add a trusted dependency](https://bun.com/guides/install/trusted)
- [Add a development dependency](https://bun.com/guides/install/add-dev)
- [Add a tarball dependency](https://bun.com/guides/install/add-tarball)
- [Add an optional dependency](https://bun.com/guides/install/add-optional)
- [Generate a yarn-compatible lockfile](https://bun.com/guides/install/yarnlock)
- [Configuring a monorepo using workspaces](https://bun.com/guides/install/workspaces)
- [Install a package under a different name](https://bun.com/guides/install/npm-alias)
- [Install dependencies with Bun in GitHub Actions](https://bun.com/guides/install/cicd)
- [Using bun install with Artifactory](https://bun.com/guides/install/jfrog-artifactory)
- [Configure git to diff Bun's lockb lockfile](https://bun.com/guides/install/git-diff-bun-lockfile)
- [Override the default npm registry for bun install](https://bun.com/guides/install/custom-registry)
- [Using bun install with an Azure Artifacts npm registry](https://bun.com/guides/install/azure-artifacts)
- [Migrate from npm install to bun install](https://bun.com/guides/install/from-npm-install-to-bun-install)
- [Configure a private registry for an organization scope with bun install](https://bun.com/guides/install/registry-scope)
- [Add a dependency](https://bun.sh/guides/install/add)
- [Add a Git dependency](https://bun.sh/guides/install/add-git)
- [Add a peer dependency](https://bun.sh/guides/install/add-peer)
- [Add a trusted dependency](https://bun.sh/guides/install/trusted)
- [Add a development dependency](https://bun.sh/guides/install/add-dev)
- [Add a tarball dependency](https://bun.sh/guides/install/add-tarball)
- [Add an optional dependency](https://bun.sh/guides/install/add-optional)
- [Generate a yarn-compatible lockfile](https://bun.sh/guides/install/yarnlock)
- [Configuring a monorepo using workspaces](https://bun.sh/guides/install/workspaces)
- [Install a package under a different name](https://bun.sh/guides/install/npm-alias)
- [Install dependencies with Bun in GitHub Actions](https://bun.sh/guides/install/cicd)
- [Using bun install with Artifactory](https://bun.sh/guides/install/jfrog-artifactory)
- [Configure git to diff Bun's lockb lockfile](https://bun.sh/guides/install/git-diff-bun-lockfile)
- [Override the default npm registry for bun install](https://bun.sh/guides/install/custom-registry)
- [Using bun install with an Azure Artifacts npm registry](https://bun.sh/guides/install/azure-artifacts)
- [Migrate from npm install to bun install](https://bun.sh/guides/install/from-npm-install-to-bun-install)
- [Configure a private registry for an organization scope with bun install](https://bun.sh/guides/install/registry-scope)
- Process
- [Read from stdin](https://bun.com/guides/process/stdin)
- [Listen for CTRL+C](https://bun.com/guides/process/ctrl-c)
- [Spawn a child process](https://bun.com/guides/process/spawn)
- [Listen to OS signals](https://bun.com/guides/process/os-signals)
- [Parse command-line arguments](https://bun.com/guides/process/argv)
- [Read stderr from a child process](https://bun.com/guides/process/spawn-stderr)
- [Read stdout from a child process](https://bun.com/guides/process/spawn-stdout)
- [Get the process uptime in nanoseconds](https://bun.com/guides/process/nanoseconds)
- [Spawn a child process and communicate using IPC](https://bun.com/guides/process/ipc)
- [Read from stdin](https://bun.sh/guides/process/stdin)
- [Listen for CTRL+C](https://bun.sh/guides/process/ctrl-c)
- [Spawn a child process](https://bun.sh/guides/process/spawn)
- [Listen to OS signals](https://bun.sh/guides/process/os-signals)
- [Parse command-line arguments](https://bun.sh/guides/process/argv)
- [Read stderr from a child process](https://bun.sh/guides/process/spawn-stderr)
- [Read stdout from a child process](https://bun.sh/guides/process/spawn-stdout)
- [Get the process uptime in nanoseconds](https://bun.sh/guides/process/nanoseconds)
- [Spawn a child process and communicate using IPC](https://bun.sh/guides/process/ipc)
- Read file
- [Read a JSON file](https://bun.com/guides/read-file/json)
- [Check if a file exists](https://bun.com/guides/read-file/exists)
- [Read a file as a string](https://bun.com/guides/read-file/string)
- [Read a file to a Buffer](https://bun.com/guides/read-file/buffer)
- [Get the MIME type of a file](https://bun.com/guides/read-file/mime)
- [Watch a directory for changes](https://bun.com/guides/read-file/watch)
- [Read a file as a ReadableStream](https://bun.com/guides/read-file/stream)
- [Read a file to a Uint8Array](https://bun.com/guides/read-file/uint8array)
- [Read a file to an ArrayBuffer](https://bun.com/guides/read-file/arraybuffer)
- [Read a JSON file](https://bun.sh/guides/read-file/json)
- [Check if a file exists](https://bun.sh/guides/read-file/exists)
- [Read a file as a string](https://bun.sh/guides/read-file/string)
- [Read a file to a Buffer](https://bun.sh/guides/read-file/buffer)
- [Get the MIME type of a file](https://bun.sh/guides/read-file/mime)
- [Watch a directory for changes](https://bun.sh/guides/read-file/watch)
- [Read a file as a ReadableStream](https://bun.sh/guides/read-file/stream)
- [Read a file to a Uint8Array](https://bun.sh/guides/read-file/uint8array)
- [Read a file to an ArrayBuffer](https://bun.sh/guides/read-file/arraybuffer)
- Runtime
- [Delete files](https://bun.com/guides/runtime/delete-file)
- [Run a Shell Command](https://bun.com/guides/runtime/shell)
- [Import a JSON file](https://bun.com/guides/runtime/import-json)
- [Import a TOML file](https://bun.com/guides/runtime/import-toml)
- [Set a time zone in Bun](https://bun.com/guides/runtime/timezone)
- [Set environment variables](https://bun.com/guides/runtime/set-env)
- [Re-map import paths](https://bun.com/guides/runtime/tsconfig-paths)
- [Delete directories](https://bun.com/guides/runtime/delete-directory)
- [Read environment variables](https://bun.com/guides/runtime/read-env)
- [Import a HTML file as text](https://bun.com/guides/runtime/import-html)
- [Install and run Bun in GitHub Actions](https://bun.com/guides/runtime/cicd)
- [Debugging Bun with the web debugger](https://bun.com/guides/runtime/web-debugger)
- [Install TypeScript declarations for Bun](https://bun.com/guides/runtime/typescript)
- [Debugging Bun with the VS Code extension](https://bun.com/guides/runtime/vscode-debugger)
- [Inspect memory usage using V8 heap snapshots](https://bun.com/guides/runtime/heap-snapshot)
- [Define and replace static globals & constants](https://bun.com/guides/runtime/define-constant)
- [Codesign a single-file JavaScript executable on macOS](https://bun.com/guides/runtime/codesign-macos-executable)
- [Delete files](https://bun.sh/guides/runtime/delete-file)
- [Run a Shell Command](https://bun.sh/guides/runtime/shell)
- [Import a JSON file](https://bun.sh/guides/runtime/import-json)
- [Import a TOML file](https://bun.sh/guides/runtime/import-toml)
- [Set a time zone in Bun](https://bun.sh/guides/runtime/timezone)
- [Set environment variables](https://bun.sh/guides/runtime/set-env)
- [Re-map import paths](https://bun.sh/guides/runtime/tsconfig-paths)
- [Delete directories](https://bun.sh/guides/runtime/delete-directory)
- [Read environment variables](https://bun.sh/guides/runtime/read-env)
- [Import a HTML file as text](https://bun.sh/guides/runtime/import-html)
- [Install and run Bun in GitHub Actions](https://bun.sh/guides/runtime/cicd)
- [Debugging Bun with the web debugger](https://bun.sh/guides/runtime/web-debugger)
- [Install TypeScript declarations for Bun](https://bun.sh/guides/runtime/typescript)
- [Debugging Bun with the VS Code extension](https://bun.sh/guides/runtime/vscode-debugger)
- [Inspect memory usage using V8 heap snapshots](https://bun.sh/guides/runtime/heap-snapshot)
- [Define and replace static globals & constants](https://bun.sh/guides/runtime/define-constant)
- [Codesign a single-file JavaScript executable on macOS](https://bun.sh/guides/runtime/codesign-macos-executable)
- Streams
- [Convert a ReadableStream to JSON](https://bun.com/guides/streams/to-json)
- [Convert a ReadableStream to a Blob](https://bun.com/guides/streams/to-blob)
- [Convert a ReadableStream to a Buffer](https://bun.com/guides/streams/to-buffer)
- [Convert a ReadableStream to a string](https://bun.com/guides/streams/to-string)
- [Convert a ReadableStream to a Uint8Array](https://bun.com/guides/streams/to-typedarray)
- [Convert a ReadableStream to an array of chunks](https://bun.com/guides/streams/to-array)
- [Convert a Node.js Readable to JSON](https://bun.com/guides/streams/node-readable-to-json)
- [Convert a ReadableStream to an ArrayBuffer](https://bun.com/guides/streams/to-arraybuffer)
- [Convert a Node.js Readable to a Blob](https://bun.com/guides/streams/node-readable-to-blob)
- [Convert a Node.js Readable to a string](https://bun.com/guides/streams/node-readable-to-string)
- [Convert a Node.js Readable to an Uint8Array](https://bun.com/guides/streams/node-readable-to-uint8array)
- [Convert a Node.js Readable to an ArrayBuffer](https://bun.com/guides/streams/node-readable-to-arraybuffer)
- [Convert a ReadableStream to JSON](https://bun.sh/guides/streams/to-json)
- [Convert a ReadableStream to a Blob](https://bun.sh/guides/streams/to-blob)
- [Convert a ReadableStream to a Buffer](https://bun.sh/guides/streams/to-buffer)
- [Convert a ReadableStream to a string](https://bun.sh/guides/streams/to-string)
- [Convert a ReadableStream to a Uint8Array](https://bun.sh/guides/streams/to-typedarray)
- [Convert a ReadableStream to an array of chunks](https://bun.sh/guides/streams/to-array)
- [Convert a Node.js Readable to JSON](https://bun.sh/guides/streams/node-readable-to-json)
- [Convert a ReadableStream to an ArrayBuffer](https://bun.sh/guides/streams/to-arraybuffer)
- [Convert a Node.js Readable to a Blob](https://bun.sh/guides/streams/node-readable-to-blob)
- [Convert a Node.js Readable to a string](https://bun.sh/guides/streams/node-readable-to-string)
- [Convert a Node.js Readable to an Uint8Array](https://bun.sh/guides/streams/node-readable-to-uint8array)
- [Convert a Node.js Readable to an ArrayBuffer](https://bun.sh/guides/streams/node-readable-to-arraybuffer)
- Test
- [Spy on methods in `bun test`](https://bun.com/guides/test/spy-on)
- [Bail early with the Bun test runner](https://bun.com/guides/test/bail)
- [Mock functions in `bun test`](https://bun.com/guides/test/mock-functions)
- [Run tests in watch mode with Bun](https://bun.com/guides/test/watch-mode)
- [Use snapshot testing in `bun test`](https://bun.com/guides/test/snapshot)
- [Skip tests with the Bun test runner](https://bun.com/guides/test/skip-tests)
- [Using Testing Library with Bun](https://bun.com/guides/test/testing-library)
- [Update snapshots in `bun test`](https://bun.com/guides/test/update-snapshots)
- [Run your tests with the Bun test runner](https://bun.com/guides/test/run-tests)
- [Set the system time in Bun's test runner](https://bun.com/guides/test/mock-clock)
- [Set a per-test timeout with the Bun test runner](https://bun.com/guides/test/timeout)
- [Migrate from Jest to Bun's test runner](https://bun.com/guides/test/migrate-from-jest)
- [Write browser DOM tests with Bun and happy-dom](https://bun.com/guides/test/happy-dom)
- [Mark a test as a "todo" with the Bun test runner](https://bun.com/guides/test/todo-tests)
- [Re-run tests multiple times with the Bun test runner](https://bun.com/guides/test/rerun-each)
- [Generate code coverage reports with the Bun test runner](https://bun.com/guides/test/coverage)
- [import, require, and test Svelte components with bun test](https://bun.com/guides/test/svelte-test)
- [Set a code coverage threshold with the Bun test runner](https://bun.com/guides/test/coverage-threshold)
- [Spy on methods in `bun test`](https://bun.sh/guides/test/spy-on)
- [Bail early with the Bun test runner](https://bun.sh/guides/test/bail)
- [Mock functions in `bun test`](https://bun.sh/guides/test/mock-functions)
- [Run tests in watch mode with Bun](https://bun.sh/guides/test/watch-mode)
- [Use snapshot testing in `bun test`](https://bun.sh/guides/test/snapshot)
- [Skip tests with the Bun test runner](https://bun.sh/guides/test/skip-tests)
- [Using Testing Library with Bun](https://bun.sh/guides/test/testing-library)
- [Update snapshots in `bun test`](https://bun.sh/guides/test/update-snapshots)
- [Run your tests with the Bun test runner](https://bun.sh/guides/test/run-tests)
- [Set the system time in Bun's test runner](https://bun.sh/guides/test/mock-clock)
- [Set a per-test timeout with the Bun test runner](https://bun.sh/guides/test/timeout)
- [Migrate from Jest to Bun's test runner](https://bun.sh/guides/test/migrate-from-jest)
- [Write browser DOM tests with Bun and happy-dom](https://bun.sh/guides/test/happy-dom)
- [Mark a test as a "todo" with the Bun test runner](https://bun.sh/guides/test/todo-tests)
- [Re-run tests multiple times with the Bun test runner](https://bun.sh/guides/test/rerun-each)
- [Generate code coverage reports with the Bun test runner](https://bun.sh/guides/test/coverage)
- [import, require, and test Svelte components with bun test](https://bun.sh/guides/test/svelte-test)
- [Set a code coverage threshold with the Bun test runner](https://bun.sh/guides/test/coverage-threshold)
- Util
- [Generate a UUID](https://bun.com/guides/util/javascript-uuid)
- [Hash a password](https://bun.com/guides/util/hash-a-password)
- [Escape an HTML string](https://bun.com/guides/util/escape-html)
- [Get the current Bun version](https://bun.com/guides/util/version)
- [Encode and decode base64 strings](https://bun.com/guides/util/base64)
- [Compress and decompress data with gzip](https://bun.com/guides/util/gzip)
- [Sleep for a fixed number of milliseconds](https://bun.com/guides/util/sleep)
- [Detect when code is executed with Bun](https://bun.com/guides/util/detect-bun)
- [Check if two objects are deeply equal](https://bun.com/guides/util/deep-equals)
- [Compress and decompress data with DEFLATE](https://bun.com/guides/util/deflate)
- [Get the absolute path to the current entrypoint](https://bun.com/guides/util/main)
- [Get the directory of the current file](https://bun.com/guides/util/import-meta-dir)
- [Check if the current file is the entrypoint](https://bun.com/guides/util/entrypoint)
- [Get the file name of the current file](https://bun.com/guides/util/import-meta-file)
- [Convert a file URL to an absolute path](https://bun.com/guides/util/file-url-to-path)
- [Convert an absolute path to a file URL](https://bun.com/guides/util/path-to-file-url)
- [Get the absolute path of the current file](https://bun.com/guides/util/import-meta-path)
- [Get the path to an executable bin file](https://bun.com/guides/util/which-path-to-executable-bin)
- [Generate a UUID](https://bun.sh/guides/util/javascript-uuid)
- [Hash a password](https://bun.sh/guides/util/hash-a-password)
- [Escape an HTML string](https://bun.sh/guides/util/escape-html)
- [Get the current Bun version](https://bun.sh/guides/util/version)
- [Encode and decode base64 strings](https://bun.sh/guides/util/base64)
- [Compress and decompress data with gzip](https://bun.sh/guides/util/gzip)
- [Sleep for a fixed number of milliseconds](https://bun.sh/guides/util/sleep)
- [Detect when code is executed with Bun](https://bun.sh/guides/util/detect-bun)
- [Check if two objects are deeply equal](https://bun.sh/guides/util/deep-equals)
- [Compress and decompress data with DEFLATE](https://bun.sh/guides/util/deflate)
- [Get the absolute path to the current entrypoint](https://bun.sh/guides/util/main)
- [Get the directory of the current file](https://bun.sh/guides/util/import-meta-dir)
- [Check if the current file is the entrypoint](https://bun.sh/guides/util/entrypoint)
- [Get the file name of the current file](https://bun.sh/guides/util/import-meta-file)
- [Convert a file URL to an absolute path](https://bun.sh/guides/util/file-url-to-path)
- [Convert an absolute path to a file URL](https://bun.sh/guides/util/path-to-file-url)
- [Get the absolute path of the current file](https://bun.sh/guides/util/import-meta-path)
- [Get the path to an executable bin file](https://bun.sh/guides/util/which-path-to-executable-bin)
- WebSocket
- [Build a publish-subscribe WebSocket server](https://bun.com/guides/websocket/pubsub)
- [Build a simple WebSocket server](https://bun.com/guides/websocket/simple)
- [Enable compression for WebSocket messages](https://bun.com/guides/websocket/compression)
- [Set per-socket contextual data on a WebSocket](https://bun.com/guides/websocket/context)
- [Build a publish-subscribe WebSocket server](https://bun.sh/guides/websocket/pubsub)
- [Build a simple WebSocket server](https://bun.sh/guides/websocket/simple)
- [Enable compression for WebSocket messages](https://bun.sh/guides/websocket/compression)
- [Set per-socket contextual data on a WebSocket](https://bun.sh/guides/websocket/context)
- Write file
- [Delete a file](https://bun.com/guides/write-file/unlink)
- [Write to stdout](https://bun.com/guides/write-file/stdout)
- [Write a file to stdout](https://bun.com/guides/write-file/cat)
- [Write a Blob to a file](https://bun.com/guides/write-file/blob)
- [Write a string to a file](https://bun.com/guides/write-file/basic)
- [Append content to a file](https://bun.com/guides/write-file/append)
- [Write a file incrementally](https://bun.com/guides/write-file/filesink)
- [Write a Response to a file](https://bun.com/guides/write-file/response)
- [Copy a file to another location](https://bun.com/guides/write-file/file-cp)
- [Write a ReadableStream to a file](https://bun.com/guides/write-file/stream)
- [Delete a file](https://bun.sh/guides/write-file/unlink)
- [Write to stdout](https://bun.sh/guides/write-file/stdout)
- [Write a file to stdout](https://bun.sh/guides/write-file/cat)
- [Write a Blob to a file](https://bun.sh/guides/write-file/blob)
- [Write a string to a file](https://bun.sh/guides/write-file/basic)
- [Append content to a file](https://bun.sh/guides/write-file/append)
- [Write a file incrementally](https://bun.sh/guides/write-file/filesink)
- [Write a Response to a file](https://bun.sh/guides/write-file/response)
- [Copy a file to another location](https://bun.sh/guides/write-file/file-cp)
- [Write a ReadableStream to a file](https://bun.sh/guides/write-file/stream)
## Contributing
Refer to the [Project > Contributing](https://bun.com/docs/project/contributing) guide to start contributing to Bun.
Refer to the [Project > Contributing](https://bun.sh/docs/project/contributing) guide to start contributing to Bun.
## License
Refer to the [Project > License](https://bun.com/docs/project/licensing) page for information about Bun's licensing.
Refer to the [Project > License](https://bun.sh/docs/project/licensing) page for information about Bun's licensing.

View File

@@ -8,4 +8,5 @@
## Reporting a Vulnerability
Report any discovered vulnerabilities to the Bun team by emailing `security@bun.com`. Your report will acknowledged within 5 days, and a team member will be assigned as the primary handler. To the greatest extent possible, the security team will endeavor to keep you informed of the progress being made towards a fix and full announcement, and may ask for additional information or guidance surrounding the reported issue.
Report any discovered vulnerabilities to the Bun team by emailing `security@bun.sh`. Your report will acknowledged within 5 days, and a team member will be assigned as the primary handler. To the greatest extent possible, the security team will endeavor to keep you informed of the progress being made towards a fix and full announcement, and may ask for additional information or guidance surrounding the reported issue.

View File

@@ -40,4 +40,4 @@ vitest (node v18.11.0)
> expect().toEqual() x 10000: 401.08ms
This project was created using `bun init` in bun v0.3.0. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
This project was created using `bun init` in bun v0.3.0. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.

Binary file not shown.

View File

@@ -28,7 +28,9 @@ if (+(existingUsers?.[0]?.count ?? existingUsers?.count) < 100) {
}));
// Insert all users
await sql`INSERT INTO users_bun_bench ${sql(users)}`;
await sql`
INSERT INTO users_bun_bench (first_name, last_name, email, dob) ${sql(users)}
`;
}
const type = isBun ? "Bun.sql" : "postgres";

View File

@@ -9,6 +9,6 @@
"typescript": "^5.0.0"
},
"dependencies": {
"postgres": "^3.4.7"
"postgres": "^3.4.5"
}
}

View File

@@ -9,7 +9,7 @@
// To clear your DNS cache on Windows:
// ipconfig /flushdns
//
const url = new URL(process.argv.length > 2 ? process.argv.at(-1) : "https://bun.com");
const url = new URL(process.argv.length > 2 ? process.argv.at(-1) : "https://bun.sh");
const hostname = url.hostname;
const port = url.port ? parseInt(url.port, 10) : url.protocol === "https:" ? 443 : 80;

View File

@@ -50,10 +50,6 @@ bench("murmur64v2 (short)", () => {
Bun.hash.murmur64v2(shortStr);
});
bench("rapidhash (short)", () => {
Bun.hash.rapidhash(shortStr);
});
bench("wyhash (128 KB)", () => {
Bun.hash.wyhash(longStr);
});
@@ -98,8 +94,4 @@ bench("murmur64v2 (128 KB)", () => {
Bun.hash.murmur64v2(longStr);
});
bench("rapidhash (128 KB)", () => {
Bun.hash.rapidhash(longStr);
});
run();

View File

@@ -1,28 +0,0 @@
import { SourceMap } from "node:module";
import { readFileSync } from "node:fs";
import { bench, run } from "../runner.mjs";
const json = JSON.parse(readFileSync(process.argv.at(-1), "utf-8"));
bench("new SourceMap(json)", () => {
return new SourceMap(json);
});
const map = new SourceMap(json);
const toRotate = [];
for (let j = 0; j < 10000; j++) {
if (map.findEntry(0, j).generatedColumn) {
toRotate.push(j);
if (toRotate.length > 5) break;
}
}
let i = 0;
bench("findEntry (match)", () => {
return map.findEntry(0, toRotate[i++ % 3]).generatedColumn;
});
bench("findEntry (no match)", () => {
return map.findEntry(0, 9999).generatedColumn;
});
await run();

View File

@@ -34,4 +34,4 @@ For example, when the client sends `"foo"`, the server sends back `"John: foo"`
The client script waits until it receives all the messages for each client before sending the next batch of messages.
This project was created using `bun init` in bun v0.2.1. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
This project was created using `bun init` in bun v0.2.1. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.

View File

@@ -63,7 +63,6 @@ const BunBuildOptions = struct {
/// `./build/codegen` or equivalent
codegen_path: []const u8,
no_llvm: bool,
override_no_export_cpp_apis: bool,
cached_options_module: ?*Module = null,
windows_shim: ?WindowsShim = null,
@@ -96,7 +95,6 @@ const BunBuildOptions = struct {
opts.addOption(bool, "enable_asan", this.enable_asan);
opts.addOption([]const u8, "reported_nodejs_version", b.fmt("{}", .{this.reported_nodejs_version}));
opts.addOption(bool, "zig_self_hosted_backend", this.no_llvm);
opts.addOption(bool, "override_no_export_cpp_apis", this.override_no_export_cpp_apis);
const mod = opts.createModule();
this.cached_options_module = mod;
@@ -208,7 +206,6 @@ pub fn build(b: *Build) !void {
const obj_format = b.option(ObjectFormat, "obj_format", "Output file for object files") orelse .obj;
const no_llvm = b.option(bool, "no_llvm", "Experiment with Zig self hosted backends. No stability guaranteed") orelse false;
const override_no_export_cpp_apis = b.option(bool, "override-no-export-cpp-apis", "Override the default export_cpp_apis logic to disable exports") orelse false;
var build_options = BunBuildOptions{
.target = target,
@@ -220,7 +217,6 @@ pub fn build(b: *Build) !void {
.codegen_path = codegen_path,
.codegen_embed = codegen_embed,
.no_llvm = no_llvm,
.override_no_export_cpp_apis = override_no_export_cpp_apis,
.version = try Version.parse(bun_version),
.canary_revision = canary: {
@@ -390,12 +386,6 @@ pub fn build(b: *Build) !void {
.{ .os = .windows, .arch = .x86_64 },
}, &.{ .Debug, .ReleaseFast });
}
{
const step = b.step("check-windows-debug", "Check for semantic analysis errors on Windows");
addMultiCheck(b, step, build_options, &.{
.{ .os = .windows, .arch = .x86_64 },
}, &.{.Debug});
}
{
const step = b.step("check-macos", "Check for semantic analysis errors on Windows");
addMultiCheck(b, step, build_options, &.{
@@ -403,13 +393,6 @@ pub fn build(b: *Build) !void {
.{ .os = .mac, .arch = .aarch64 },
}, &.{ .Debug, .ReleaseFast });
}
{
const step = b.step("check-macos-debug", "Check for semantic analysis errors on Windows");
addMultiCheck(b, step, build_options, &.{
.{ .os = .mac, .arch = .x86_64 },
.{ .os = .mac, .arch = .aarch64 },
}, &.{.Debug});
}
{
const step = b.step("check-linux", "Check for semantic analysis errors on Windows");
addMultiCheck(b, step, build_options, &.{
@@ -417,13 +400,6 @@ pub fn build(b: *Build) !void {
.{ .os = .linux, .arch = .aarch64 },
}, &.{ .Debug, .ReleaseFast });
}
{
const step = b.step("check-linux-debug", "Check for semantic analysis errors on Windows");
addMultiCheck(b, step, build_options, &.{
.{ .os = .linux, .arch = .x86_64 },
.{ .os = .linux, .arch = .aarch64 },
}, &.{.Debug});
}
// zig build translate-c-headers
{
@@ -500,7 +476,6 @@ fn addMultiCheck(
.codegen_path = root_build_options.codegen_path,
.no_llvm = root_build_options.no_llvm,
.enable_asan = root_build_options.enable_asan,
.override_no_export_cpp_apis = root_build_options.override_no_export_cpp_apis,
};
var obj = addBunObject(b, &options);
@@ -533,8 +508,6 @@ fn getTranslateC(b: *Build, initial_target: std.Build.ResolvedTarget, optimize:
translate_c.defineCMacroRaw(b.fmt("{s}={d}", .{ str, @intFromBool(value) }));
}
translate_c.addIncludePath(b.path("vendor/zstd/lib"));
if (target.result.os.tag == .windows) {
// translate-c is unable to translate the unsuffixed windows functions
// like `SetCurrentDirectory` since they are defined with an odd macro
@@ -752,13 +725,6 @@ fn addInternalImports(b: *Build, mod: *Module, opts: *BunBuildOptions) void {
});
}
}
{
const cppImport = b.createModule(.{
.root_source_file = (std.Build.LazyPath{ .cwd_relative = opts.codegen_path }).path(b, "cpp.zig"),
});
mod.addImport("cpp", cppImport);
cppImport.addImport("bun", mod);
}
inline for (.{
.{ .import = "completions-bash", .file = b.path("completions/bun.bash") },
.{ .import = "completions-zsh", .file = b.path("completions/bun.zsh") },

View File

@@ -4,8 +4,7 @@
"": {
"name": "bun",
"devDependencies": {
"@lezer/common": "^1.2.3",
"@lezer/cpp": "^1.1.3",
"@types/react": "^18.3.3",
"esbuild": "^0.21.4",
"mitata": "^0.1.11",
"peechy": "0.4.34",
@@ -30,17 +29,13 @@
"@types/node": "*",
},
"devDependencies": {
"@types/react": "^19",
"typescript": "^5.0.2",
},
"peerDependencies": {
"@types/react": "^19",
},
},
},
"overrides": {
"@types/bun": "workspace:packages/@types/bun",
"bun-types": "workspace:packages/bun-types",
"@types/bun": "workspace:packages/@types/bun",
},
"packages": {
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.21.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="],
@@ -89,19 +84,13 @@
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.21.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw=="],
"@lezer/common": ["@lezer/common@1.2.3", "", {}, "sha512-w7ojc8ejBqr2REPsWxJjrMFsA/ysDCFICn8zEOR9mrqzOu2amhITYuLD8ag6XZf0CFXDrhKqw7+tW8cX66NaDA=="],
"@lezer/cpp": ["@lezer/cpp@1.1.3", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-ykYvuFQKGsRi6IcE+/hCSGUhb/I4WPjd3ELhEblm2wS2cOznDFzO+ubK2c+ioysOnlZ3EduV+MVQFCPzAIoY3w=="],
"@lezer/highlight": ["@lezer/highlight@1.2.1", "", { "dependencies": { "@lezer/common": "^1.0.0" } }, "sha512-Z5duk4RN/3zuVO7Jq0pGLJ3qynpxUVsh7IbUbGj88+uV2ApSAn6kWg2au3iJb+0Zi7kKtqffIESgNcRXWZWmSA=="],
"@lezer/lr": ["@lezer/lr@1.4.2", "", { "dependencies": { "@lezer/common": "^1.0.0" } }, "sha512-pu0K1jCIdnQ12aWNaAVU5bzi7Bd1w54J3ECgANPmYLtQKP0HBj2cE/5coBD66MT10xbtIuUr7tg0Shbsvk0mDA=="],
"@types/bun": ["@types/bun@workspace:packages/@types/bun"],
"@types/node": ["@types/node@22.15.18", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-v1DKRfUdyW+jJhZNEI1PYy29S2YRxMV5AOO/x/SjKmW0acCIOqmbj6Haf9eHAhsPmrhlHSxEhv/1WszcLWV4cg=="],
"@types/react": ["@types/react@19.1.8", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-AwAfQ2Wa5bCx9WP8nZL2uMZWod7J7/JSplxbTmBQ5ms6QpqNYm672H0Vu9ZVKVngQ+ii4R/byguVEUZQyeg44g=="],
"@types/prop-types": ["@types/prop-types@15.7.14", "", {}, "sha512-gNMvNH49DJ7OJYv+KAKn0Xp45p8PLl6zo2YnvDIbTd4J6MER2BmWN49TG7n9LvkyihINxeKW8+3bfS2yDC9dzQ=="],
"@types/react": ["@types/react@18.3.21", "", { "dependencies": { "@types/prop-types": "*", "csstype": "^3.0.2" } }, "sha512-gXLBtmlcRJeT09/sI4PxVwyrku6SaNUj/6cMubjE6T6XdY1fDmBL7r0nX0jbSZPU/Xr0KuwLLZh6aOYY5d91Xw=="],
"bun-types": ["bun-types@workspace:packages/bun-types"],

View File

@@ -7,6 +7,3 @@
# Instead, we can only scan the test directory for Bun's runtime tests
root = "test"
preload = "./test/preload.ts"
[install]
linker = "isolated"

View File

@@ -187,14 +187,13 @@ endfunction()
# satisfies_range()
# Description:
# Check if a version satisfies a version range or list of ranges
# Check if a version satisfies a version range
# Arguments:
# version string - The version to check (e.g. "1.2.3")
# range string - The range to check against (e.g. ">=1.2.3" or ">=19.1.0 <20.0.0")
# Multiple space-separated ranges may be supplied; in this case they must all be satisfied
# range string - The range to check against (e.g. ">=1.2.3")
# variable string - The variable to store the result in
function(satisfies_range version ranges variable)
if(ranges STREQUAL "ignore")
function(satisfies_range version range variable)
if(range STREQUAL "ignore")
set(${variable} ON PARENT_SCOPE)
return()
endif()
@@ -207,36 +206,26 @@ function(satisfies_range version ranges variable)
endif()
set(version ${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3})
string(REPLACE " " ";" range_list "${ranges}")
set(all_satisfied ON)
string(REGEX MATCH "(>=|<=|>|<)?([0-9]+)\\.([0-9]+)\\.([0-9]+)" match "${range}")
if(NOT match)
return()
endif()
set(comparator ${CMAKE_MATCH_1})
set(range ${CMAKE_MATCH_2}.${CMAKE_MATCH_3}.${CMAKE_MATCH_4})
foreach(current_item ${range_list})
string(REGEX MATCH "(>=|<=|>|<)?([0-9]+)\\.([0-9]+)\\.([0-9]+)" match "${current_item}")
if(NOT match)
return()
endif()
set(comparator ${CMAKE_MATCH_1})
set(range ${CMAKE_MATCH_2}.${CMAKE_MATCH_3}.${CMAKE_MATCH_4})
if(comparator STREQUAL ">=")
set(comparator VERSION_GREATER_EQUAL)
elseif(comparator STREQUAL ">")
set(comparator VERSION_GREATER)
elseif(comparator STREQUAL "<=")
set(comparator VERSION_LESS_EQUAL)
elseif(comparator STREQUAL "<")
set(comparator VERSION_LESS)
else()
set(comparator VERSION_EQUAL)
endif()
if(comparator STREQUAL ">=")
set(comparator VERSION_GREATER_EQUAL)
elseif(comparator STREQUAL ">")
set(comparator VERSION_GREATER)
elseif(comparator STREQUAL "<=")
set(comparator VERSION_LESS_EQUAL)
elseif(comparator STREQUAL "<")
set(comparator VERSION_LESS)
else()
set(comparator VERSION_EQUAL)
endif()
if(NOT version ${comparator} ${range})
set(all_satisfied OFF)
break()
endif()
endforeach()
if(all_satisfied)
if(version ${comparator} ${range})
set(${variable} ON PARENT_SCOPE)
endif()
endfunction()

View File

@@ -95,7 +95,7 @@ if(LINUX)
optionx(ENABLE_VALGRIND BOOL "If Valgrind support should be enabled" DEFAULT OFF)
endif()
if(DEBUG AND ((APPLE AND ARCH STREQUAL "aarch64") OR LINUX))
if(DEBUG AND APPLE AND ARCH STREQUAL "aarch64")
set(DEFAULT_ASAN ON)
else()
set(DEFAULT_ASAN OFF)
@@ -139,10 +139,10 @@ endif()
optionx(REVISION STRING "The git revision of the build" DEFAULT ${DEFAULT_REVISION})
# Used in process.version, process.versions.node, napi, and elsewhere
setx(NODEJS_VERSION "24.3.0")
optionx(NODEJS_VERSION STRING "The version of Node.js to report" DEFAULT "22.6.0")
# Used in process.versions.modules and compared while loading V8 modules
setx(NODEJS_ABI_VERSION "137")
optionx(NODEJS_ABI_VERSION STRING "The ABI version of Node.js to report" DEFAULT "127")
if(APPLE)
set(DEFAULT_STATIC_SQLITE OFF)

View File

@@ -44,7 +44,6 @@
"src/bun.js/bindings/webcrypto/*/*.cpp",
"src/bun.js/bindings/node/*.cpp",
"src/bun.js/bindings/node/crypto/*.cpp",
"src/bun.js/bindings/node/http/*.cpp",
"src/bun.js/bindings/v8/*.cpp",
"src/bun.js/bindings/v8/shim/*.cpp",
"src/bake/*.cpp",
@@ -61,9 +60,7 @@
"packages/bun-usockets/src/internal/*.c",
"packages/bun-usockets/src/crypto/*.c",
"src/bun.js/bindings/uv-posix-polyfills.c",
"src/bun.js/bindings/uv-posix-stubs.c",
"src/*.c",
"src/bun.js/bindings/node/http/llhttp/*.c"
"src/bun.js/bindings/uv-posix-stubs.c"
]
}
]

View File

@@ -1,31 +0,0 @@
# This script prepares Node.js headers for use with Bun
# It removes conflicting OpenSSL and libuv headers since Bun uses BoringSSL and its own libuv
if(NOT DEFINED NODE_INCLUDE_DIR)
message(FATAL_ERROR "NODE_INCLUDE_DIR not defined")
endif()
if(NOT EXISTS "${NODE_INCLUDE_DIR}/node")
message(FATAL_ERROR "Node headers not found at ${NODE_INCLUDE_DIR}/node")
endif()
# Remove OpenSSL headers that conflict with BoringSSL
if(EXISTS "${NODE_INCLUDE_DIR}/node/openssl")
file(REMOVE_RECURSE "${NODE_INCLUDE_DIR}/node/openssl")
message(STATUS "Removed conflicting OpenSSL headers")
endif()
# Remove libuv headers that might conflict
if(EXISTS "${NODE_INCLUDE_DIR}/node/uv")
file(REMOVE_RECURSE "${NODE_INCLUDE_DIR}/node/uv")
message(STATUS "Removed conflicting libuv headers")
endif()
if(EXISTS "${NODE_INCLUDE_DIR}/node/uv.h")
file(REMOVE "${NODE_INCLUDE_DIR}/node/uv.h")
message(STATUS "Removed conflicting uv.h header")
endif()
# Add the node directory to include path for cppgc
# This is needed because cppgc internal headers use relative includes
file(WRITE "${NODE_INCLUDE_DIR}/.node-headers-prepared" "1")

View File

@@ -1,3 +1,4 @@
src/bake/bake.bind.ts
src/bake/bake.d.ts
src/bake/bake.private.d.ts
src/bake/bun-framework-react/index.ts

View File

@@ -1,4 +1,4 @@
src/bake.bind.ts
src/bake/bake.bind.ts
src/bake/DevServer.bind.ts
src/bun.js/api/BunObject.bind.ts
src/bun.js/bindgen_test.bind.ts

View File

@@ -7,9 +7,5 @@ packages/bun-usockets/src/loop.c
packages/bun-usockets/src/quic.c
packages/bun-usockets/src/socket.c
packages/bun-usockets/src/udp.c
src/asan-config.c
src/bun.js/bindings/node/http/llhttp/api.c
src/bun.js/bindings/node/http/llhttp/http.c
src/bun.js/bindings/node/http/llhttp/llhttp.c
src/bun.js/bindings/uv-posix-polyfills.c
src/bun.js/bindings/uv-posix-stubs.c

View File

@@ -28,7 +28,6 @@ src/bun.js/bindings/BunWorkerGlobalScope.cpp
src/bun.js/bindings/c-bindings.cpp
src/bun.js/bindings/CallSite.cpp
src/bun.js/bindings/CallSitePrototype.cpp
src/bun.js/bindings/CatchScopeBinding.cpp
src/bun.js/bindings/CodeCoverage.cpp
src/bun.js/bindings/ConsoleObject.cpp
src/bun.js/bindings/Cookie.cpp
@@ -100,9 +99,6 @@ src/bun.js/bindings/napi_finalizer.cpp
src/bun.js/bindings/napi_handle_scope.cpp
src/bun.js/bindings/napi_type_tag.cpp
src/bun.js/bindings/napi.cpp
src/bun.js/bindings/NapiClass.cpp
src/bun.js/bindings/NapiRef.cpp
src/bun.js/bindings/NapiWeakValue.cpp
src/bun.js/bindings/ncrpyto_engine.cpp
src/bun.js/bindings/ncrypto.cpp
src/bun.js/bindings/node/crypto/CryptoDhJob.cpp
@@ -148,13 +144,6 @@ src/bun.js/bindings/node/crypto/JSSign.cpp
src/bun.js/bindings/node/crypto/JSVerify.cpp
src/bun.js/bindings/node/crypto/KeyObject.cpp
src/bun.js/bindings/node/crypto/node_crypto_binding.cpp
src/bun.js/bindings/node/http/JSConnectionsList.cpp
src/bun.js/bindings/node/http/JSConnectionsListConstructor.cpp
src/bun.js/bindings/node/http/JSConnectionsListPrototype.cpp
src/bun.js/bindings/node/http/JSHTTPParser.cpp
src/bun.js/bindings/node/http/JSHTTPParserConstructor.cpp
src/bun.js/bindings/node/http/JSHTTPParserPrototype.cpp
src/bun.js/bindings/node/http/NodeHTTPParser.cpp
src/bun.js/bindings/node/NodeTimers.cpp
src/bun.js/bindings/NodeAsyncHooks.cpp
src/bun.js/bindings/NodeDirent.cpp
@@ -170,7 +159,6 @@ src/bun.js/bindings/NodeVM.cpp
src/bun.js/bindings/NodeVMModule.cpp
src/bun.js/bindings/NodeVMScript.cpp
src/bun.js/bindings/NodeVMSourceTextModule.cpp
src/bun.js/bindings/NodeVMSyntheticModule.cpp
src/bun.js/bindings/NoOpForTesting.cpp
src/bun.js/bindings/ObjectBindings.cpp
src/bun.js/bindings/objects.cpp
@@ -179,7 +167,6 @@ src/bun.js/bindings/Path.cpp
src/bun.js/bindings/ProcessBindingBuffer.cpp
src/bun.js/bindings/ProcessBindingConstants.cpp
src/bun.js/bindings/ProcessBindingFs.cpp
src/bun.js/bindings/ProcessBindingHTTPParser.cpp
src/bun.js/bindings/ProcessBindingNatives.cpp
src/bun.js/bindings/ProcessBindingTTYWrap.cpp
src/bun.js/bindings/ProcessBindingUV.cpp

View File

@@ -8,14 +8,11 @@ src/codegen/bundle-functions.ts
src/codegen/bundle-modules.ts
src/codegen/class-definitions.ts
src/codegen/client-js.ts
src/codegen/cppbind.ts
src/codegen/create-hash-table.ts
src/codegen/generate-classes.ts
src/codegen/generate-compact-string-table.ts
src/codegen/generate-js2native.ts
src/codegen/generate-jssink.ts
src/codegen/generate-node-errors.ts
src/codegen/helpers.ts
src/codegen/internal-module-registry-scanner.ts
src/codegen/replacements.ts
src/codegen/shared-types.ts

View File

@@ -52,7 +52,6 @@ src/js/internal/debugger.ts
src/js/internal/errors.ts
src/js/internal/fifo.ts
src/js/internal/fixed_queue.ts
src/js/internal/freelist.ts
src/js/internal/fs/cp-sync.ts
src/js/internal/fs/cp.ts
src/js/internal/fs/glob.ts

View File

@@ -7,14 +7,12 @@ src/bun.js/api/h2.classes.ts
src/bun.js/api/html_rewriter.classes.ts
src/bun.js/api/JSBundler.classes.ts
src/bun.js/api/postgres.classes.ts
src/bun.js/api/ResumableSink.classes.ts
src/bun.js/api/S3Client.classes.ts
src/bun.js/api/S3Stat.classes.ts
src/bun.js/api/server.classes.ts
src/bun.js/api/Shell.classes.ts
src/bun.js/api/ShellArgs.classes.ts
src/bun.js/api/sockets.classes.ts
src/bun.js/api/sourcemap.classes.ts
src/bun.js/api/streams.classes.ts
src/bun.js/api/valkey.classes.ts
src/bun.js/api/zlib.classes.ts

View File

@@ -1,72 +1,38 @@
src/allocators.zig
src/allocators/AllocationScope.zig
src/allocators/basic.zig
src/allocators/LinuxMemFdAllocator.zig
src/allocators/MaxHeapAllocator.zig
src/allocators/linux_memfd_allocator.zig
src/allocators/max_heap_allocator.zig
src/allocators/memory_allocator.zig
src/allocators/MemoryReportingAllocator.zig
src/allocators/mimalloc_arena.zig
src/allocators/mimalloc.zig
src/allocators/MimallocArena.zig
src/allocators/NullableAllocator.zig
src/analytics.zig
src/analytics/schema.zig
src/analytics/analytics_schema.zig
src/analytics/analytics_thread.zig
src/api/schema.zig
src/ast.zig
src/ast/Ast.zig
src/ast/ASTMemoryAllocator.zig
src/ast/B.zig
src/ast/base.zig
src/ast/Binding.zig
src/ast/BundledAst.zig
src/ast/CharFreq.zig
src/ast/E.zig
src/ast/Expr.zig
src/ast/G.zig
src/ast/Macro.zig
src/ast/NewStore.zig
src/ast/Op.zig
src/ast/S.zig
src/ast/Scope.zig
src/ast/ServerComponentBoundary.zig
src/ast/Stmt.zig
src/ast/Symbol.zig
src/ast/TS.zig
src/ast/UseDirective.zig
src/async/posix_event_loop.zig
src/async/stub_event_loop.zig
src/async/windows_event_loop.zig
src/bake.zig
src/baby_list.zig
src/bake/bake.zig
src/bake/DevServer.zig
src/bake/DevServer/Assets.zig
src/bake/DevServer/DirectoryWatchStore.zig
src/bake/DevServer/ErrorReportRequest.zig
src/bake/DevServer/HmrSocket.zig
src/bake/DevServer/HotReloadEvent.zig
src/bake/DevServer/IncrementalGraph.zig
src/bake/DevServer/memory_cost.zig
src/bake/DevServer/PackedMap.zig
src/bake/DevServer/RouteBundle.zig
src/bake/DevServer/SerializedFailure.zig
src/bake/DevServer/SourceMapStore.zig
src/bake/DevServer/WatcherAtomics.zig
src/bake/FrameworkRouter.zig
src/bake/production.zig
src/base64/base64.zig
src/bit_set.zig
src/bits.zig
src/boringssl.zig
src/brotli.zig
src/btjs.zig
src/bun.js.zig
src/bun_js.zig
src/bun.js/api.zig
src/bun.js/api/bun/dns.zig
src/bun.js/api/bun/dns_resolver.zig
src/bun.js/api/bun/h2_frame_parser.zig
src/bun.js/api/bun/lshpack.zig
src/bun.js/api/bun/process.zig
src/bun.js/api/bun/socket.zig
src/bun.js/api/bun/socket/Handlers.zig
src/bun.js/api/bun/socket/Listener.zig
src/bun.js/api/bun/socket/SocketAddress.zig
src/bun.js/api/bun/socket/tls_socket_functions.zig
src/bun.js/api/bun/socket/WindowsNamedPipeContext.zig
src/bun.js/api/bun/spawn.zig
src/bun.js/api/bun/spawn/stdio.zig
src/bun.js/api/bun/ssl_wrapper.zig
@@ -89,25 +55,13 @@ src/bun.js/api/html_rewriter.zig
src/bun.js/api/JSBundler.zig
src/bun.js/api/JSTranspiler.zig
src/bun.js/api/server.zig
src/bun.js/api/server/AnyRequestContext.zig
src/bun.js/api/server/FileRoute.zig
src/bun.js/api/server/HTMLBundle.zig
src/bun.js/api/server/HTTPStatusText.zig
src/bun.js/api/server/InspectorBunFrontendDevServerAgent.zig
src/bun.js/api/server/NodeHTTPResponse.zig
src/bun.js/api/server/RequestContext.zig
src/bun.js/api/server/ServerConfig.zig
src/bun.js/api/server/ServerWebSocket.zig
src/bun.js/api/server/SSLConfig.zig
src/bun.js/api/server/StaticRoute.zig
src/bun.js/api/server/WebSocketServerContext.zig
src/bun.js/api/streams.classes.zig
src/bun.js/api/Timer.zig
src/bun.js/api/Timer/EventLoopTimer.zig
src/bun.js/api/Timer/ImmediateObject.zig
src/bun.js/api/Timer/TimeoutObject.zig
src/bun.js/api/Timer/TimerObjectInternals.zig
src/bun.js/api/Timer/WTFTimer.zig
src/bun.js/api/TOMLObject.zig
src/bun.js/api/UnsafeObject.zig
src/bun.js/bindgen_test.zig
@@ -116,7 +70,6 @@ src/bun.js/bindings/AnyPromise.zig
src/bun.js/bindings/bun-simdutf.zig
src/bun.js/bindings/CachedBytecode.zig
src/bun.js/bindings/CallFrame.zig
src/bun.js/bindings/CatchScope.zig
src/bun.js/bindings/codegen.zig
src/bun.js/bindings/CommonAbortReason.zig
src/bun.js/bindings/CommonStrings.zig
@@ -152,7 +105,6 @@ src/bun.js/bindings/JSPropertyIterator.zig
src/bun.js/bindings/JSRef.zig
src/bun.js/bindings/JSRuntimeType.zig
src/bun.js/bindings/JSString.zig
src/bun.js/bindings/JSType.zig
src/bun.js/bindings/JSUint8Array.zig
src/bun.js/bindings/JSValue.zig
src/bun.js/bindings/NodeModuleModule.zig
@@ -181,21 +133,6 @@ src/bun.js/ConsoleObject.zig
src/bun.js/Counters.zig
src/bun.js/Debugger.zig
src/bun.js/event_loop.zig
src/bun.js/event_loop/AnyEventLoop.zig
src/bun.js/event_loop/AnyTask.zig
src/bun.js/event_loop/AnyTaskWithExtraContext.zig
src/bun.js/event_loop/ConcurrentPromiseTask.zig
src/bun.js/event_loop/ConcurrentTask.zig
src/bun.js/event_loop/CppTask.zig
src/bun.js/event_loop/DeferredTaskQueue.zig
src/bun.js/event_loop/EventLoopHandle.zig
src/bun.js/event_loop/GarbageCollectionController.zig
src/bun.js/event_loop/JSCScheduler.zig
src/bun.js/event_loop/ManagedTask.zig
src/bun.js/event_loop/MiniEventLoop.zig
src/bun.js/event_loop/PosixSignalHandle.zig
src/bun.js/event_loop/Task.zig
src/bun.js/event_loop/WorkTask.zig
src/bun.js/hot_reloader.zig
src/bun.js/ipc.zig
src/bun.js/javascript_core_c_api.zig
@@ -239,9 +176,6 @@ src/bun.js/node/util/parse_args_utils.zig
src/bun.js/node/util/parse_args.zig
src/bun.js/node/util/validators.zig
src/bun.js/node/win_watcher.zig
src/bun.js/node/zlib/NativeBrotli.zig
src/bun.js/node/zlib/NativeZlib.zig
src/bun.js/node/zlib/NativeZstd.zig
src/bun.js/ProcessAutoKiller.zig
src/bun.js/rare_data.zig
src/bun.js/ResolveMessage.zig
@@ -254,6 +188,7 @@ src/bun.js/test/jest.zig
src/bun.js/test/pretty_format.zig
src/bun.js/test/snapshot.zig
src/bun.js/test/test.zig
src/bun.js/unbounded_queue.zig
src/bun.js/uuid.zig
src/bun.js/virtual_machine_exports.zig
src/bun.js/VirtualMachine.zig
@@ -282,7 +217,6 @@ src/bun.js/webcore/prompt.zig
src/bun.js/webcore/ReadableStream.zig
src/bun.js/webcore/Request.zig
src/bun.js/webcore/Response.zig
src/bun.js/webcore/ResumableSink.zig
src/bun.js/webcore/S3Client.zig
src/bun.js/webcore/S3File.zig
src/bun.js/webcore/S3Stat.zig
@@ -292,50 +226,16 @@ src/bun.js/webcore/streams.zig
src/bun.js/webcore/TextDecoder.zig
src/bun.js/webcore/TextEncoder.zig
src/bun.js/webcore/TextEncoderStreamEncoder.zig
src/bun.js/WTFTimer.zig
src/bun.zig
src/bundler/AstBuilder.zig
src/bundler/bundle_v2.zig
src/bundler/BundleThread.zig
src/bundler/Chunk.zig
src/bundler/DeferredBatchTask.zig
src/bundler/entry_points.zig
src/bundler/Graph.zig
src/bundler/HTMLImportManifest.zig
src/bundler/linker_context/computeChunks.zig
src/bundler/linker_context/computeCrossChunkDependencies.zig
src/bundler/linker_context/convertStmtsForChunk.zig
src/bundler/linker_context/convertStmtsForChunkForDevServer.zig
src/bundler/linker_context/doStep5.zig
src/bundler/linker_context/findAllImportedPartsInJSOrder.zig
src/bundler/linker_context/findImportedCSSFilesInJSOrder.zig
src/bundler/linker_context/findImportedFilesInCSSOrder.zig
src/bundler/linker_context/generateChunksInParallel.zig
src/bundler/linker_context/generateCodeForFileInChunkJS.zig
src/bundler/linker_context/generateCodeForLazyExport.zig
src/bundler/linker_context/generateCompileResultForCssChunk.zig
src/bundler/linker_context/generateCompileResultForHtmlChunk.zig
src/bundler/linker_context/generateCompileResultForJSChunk.zig
src/bundler/linker_context/OutputFileListBuilder.zig
src/bundler/linker_context/postProcessCSSChunk.zig
src/bundler/linker_context/postProcessHTMLChunk.zig
src/bundler/linker_context/postProcessJSChunk.zig
src/bundler/linker_context/prepareCssAstsForChunk.zig
src/bundler/linker_context/renameSymbolsInChunk.zig
src/bundler/linker_context/scanImportsAndExports.zig
src/bundler/linker_context/StaticRouteVisitor.zig
src/bundler/linker_context/writeOutputFilesToDisk.zig
src/bundler/LinkerContext.zig
src/bundler/LinkerGraph.zig
src/bundler/ParseTask.zig
src/bundler/ServerComponentParseTask.zig
src/bundler/ThreadPool.zig
src/bunfig.zig
src/cache.zig
src/ci_info.zig
src/cli.zig
src/cli/add_command.zig
src/cli/add_completions.zig
src/cli/Arguments.zig
src/cli/audit_command.zig
src/cli/build_command.zig
src/cli/bunx_command.zig
@@ -355,11 +255,8 @@ src/cli/pack_command.zig
src/cli/package_manager_command.zig
src/cli/patch_command.zig
src/cli/patch_commit_command.zig
src/cli/pm_pkg_command.zig
src/cli/pm_trusted_command.zig
src/cli/pm_version_command.zig
src/cli/pm_view_command.zig
src/cli/pm_why_command.zig
src/cli/publish_command.zig
src/cli/remove_command.zig
src/cli/run_command.zig
@@ -368,15 +265,8 @@ src/cli/test_command.zig
src/cli/test/Scanner.zig
src/cli/unlink_command.zig
src/cli/update_command.zig
src/cli/update_interactive_command.zig
src/cli/upgrade_command.zig
src/cli/why_command.zig
src/codegen/process_windows_translate_c.zig
src/collections.zig
src/collections/baby_list.zig
src/collections/bit_set.zig
src/collections/hive_array.zig
src/collections/multi_array_list.zig
src/compile_target.zig
src/comptime_string_map.zig
src/copy_file.zig
@@ -494,22 +384,7 @@ src/deps/picohttp.zig
src/deps/picohttpparser.zig
src/deps/tcc.zig
src/deps/uws.zig
src/deps/uws/App.zig
src/deps/uws/BodyReaderMixin.zig
src/deps/uws/ConnectingSocket.zig
src/deps/uws/InternalLoopData.zig
src/deps/uws/ListenSocket.zig
src/deps/uws/Loop.zig
src/deps/uws/Request.zig
src/deps/uws/Response.zig
src/deps/uws/socket.zig
src/deps/uws/SocketContext.zig
src/deps/uws/Timer.zig
src/deps/uws/udp.zig
src/deps/uws/UpgradedDuplex.zig
src/deps/uws/us_socket_t.zig
src/deps/uws/WebSocket.zig
src/deps/uws/WindowsNamedPipe.zig
src/deps/zig-clap/clap.zig
src/deps/zig-clap/clap/args.zig
src/deps/zig-clap/clap/comptime.zig
@@ -525,46 +400,31 @@ src/env.zig
src/errno/darwin_errno.zig
src/errno/linux_errno.zig
src/errno/windows_errno.zig
src/exact_size_matcher.zig
src/fd.zig
src/feature_flags.zig
src/fmt.zig
src/fs.zig
src/fs/stat_hash.zig
src/futex.zig
src/generated_perf_trace_events.zig
src/generated_versions_list.zig
src/glob.zig
src/glob/GlobWalker.zig
src/glob/match.zig
src/Global.zig
src/grapheme.zig
src/heap_breakdown.zig
src/highway.zig
src/hive_array.zig
src/hmac.zig
src/HTMLScanner.zig
src/http.zig
src/http/AsyncHTTP.zig
src/http/CertificateInfo.zig
src/http/Decompressor.zig
src/http/Encoding.zig
src/http/FetchRedirect.zig
src/http/HeaderBuilder.zig
src/http/Headers.zig
src/http/HTTPCertError.zig
src/http/HTTPContext.zig
src/http/HTTPRequestBody.zig
src/http/HTTPThread.zig
src/http/InitError.zig
src/http/InternalState.zig
src/http/Method.zig
src/http/mime_type_list_enum.zig
src/http/MimeType.zig
src/http/ProxyTunnel.zig
src/http/SendFile.zig
src/http/Signals.zig
src/http/ThreadSafeStreamBuffer.zig
src/http/URLPath.zig
src/http/header_builder.zig
src/http/method.zig
src/http/mime_type.zig
src/http/url_path.zig
src/http/websocket_client.zig
src/http/websocket_client/CppWebSocket.zig
src/http/websocket_client/WebSocketDeflate.zig
src/http/websocket_client/WebSocketUpgradeClient.zig
src/http/websocket_http_client.zig
src/http/websocket.zig
@@ -574,18 +434,9 @@ src/import_record.zig
src/ini.zig
src/install/bin.zig
src/install/dependency.zig
src/install/ExternalSlice.zig
src/install/extract_tarball.zig
src/install/hoisted_install.zig
src/install/install_binding.zig
src/install/install.zig
src/install/integrity.zig
src/install/isolated_install.zig
src/install/isolated_install/FileCopier.zig
src/install/isolated_install/Hardlinker.zig
src/install/isolated_install/Installer.zig
src/install/isolated_install/Store.zig
src/install/isolated_install/Symlinker.zig
src/install/lifecycle_script_runner.zig
src/install/lockfile.zig
src/install/lockfile/Buffers.zig
@@ -602,28 +453,7 @@ src/install/lockfile/printer/tree_printer.zig
src/install/lockfile/printer/Yarn.zig
src/install/lockfile/Tree.zig
src/install/migration.zig
src/install/NetworkTask.zig
src/install/npm.zig
src/install/PackageInstall.zig
src/install/PackageInstaller.zig
src/install/PackageManager.zig
src/install/PackageManager/CommandLineArguments.zig
src/install/PackageManager/install_with_manager.zig
src/install/PackageManager/PackageJSONEditor.zig
src/install/PackageManager/PackageManagerDirectories.zig
src/install/PackageManager/PackageManagerEnqueue.zig
src/install/PackageManager/PackageManagerLifecycle.zig
src/install/PackageManager/PackageManagerOptions.zig
src/install/PackageManager/PackageManagerResolution.zig
src/install/PackageManager/patchPackage.zig
src/install/PackageManager/processDependencyList.zig
src/install/PackageManager/ProgressStrings.zig
src/install/PackageManager/runTasks.zig
src/install/PackageManager/updatePackageJSONAndInstall.zig
src/install/PackageManager/UpdateRequest.zig
src/install/PackageManager/WorkspacePackageJSONCache.zig
src/install/PackageManagerTask.zig
src/install/PackageManifestMap.zig
src/install/padding_checker.zig
src/install/patch_install.zig
src/install/repository.zig
@@ -632,24 +462,22 @@ src/install/resolvers/folder_resolver.zig
src/install/versioned_url.zig
src/install/windows-shim/BinLinkingShim.zig
src/install/windows-shim/bun_shim_impl.zig
src/interchange.zig
src/interchange/json.zig
src/interchange/toml.zig
src/interchange/toml/lexer.zig
src/io/heap.zig
src/io/io.zig
src/io/MaxBuf.zig
src/io/openForWriting.zig
src/io/PipeReader.zig
src/io/pipes.zig
src/io/PipeWriter.zig
src/io/source.zig
src/io/time.zig
src/js_ast.zig
src/js_lexer_tables.zig
src/js_lexer.zig
src/js_lexer/identifier.zig
src/js_parser.zig
src/js_printer.zig
src/jsc_stub.zig
src/json_parser.zig
src/libarchive/libarchive-bindings.zig
src/libarchive/libarchive.zig
src/linear_fifo.zig
@@ -661,6 +489,8 @@ src/main_test.zig
src/main_wasm.zig
src/main.zig
src/meta.zig
src/multi_array_list.zig
src/Mutex.zig
src/napi/napi.zig
src/node_fallbacks.zig
src/open.zig
@@ -668,11 +498,6 @@ src/options.zig
src/output.zig
src/OutputFile.zig
src/patch.zig
src/paths.zig
src/paths/EnvPath.zig
src/paths/path_buffer_pool.zig
src/paths/Path.zig
src/pe.zig
src/perf.zig
src/pool.zig
src/Progress.zig
@@ -711,7 +536,6 @@ src/semver/SemverString.zig
src/semver/SlicedString.zig
src/semver/Version.zig
src/sha.zig
src/shell/AllocScope.zig
src/shell/braces.zig
src/shell/Builtin.zig
src/shell/builtin/basename.zig
@@ -736,135 +560,42 @@ src/shell/builtin/yes.zig
src/shell/EnvMap.zig
src/shell/EnvStr.zig
src/shell/interpreter.zig
src/shell/IO.zig
src/shell/IOReader.zig
src/shell/IOWriter.zig
src/shell/ParsedShellScript.zig
src/shell/RefCountedStr.zig
src/shell/shell.zig
src/shell/states/Assigns.zig
src/shell/states/Async.zig
src/shell/states/Base.zig
src/shell/states/Binary.zig
src/shell/states/Cmd.zig
src/shell/states/CondExpr.zig
src/shell/states/Expansion.zig
src/shell/states/If.zig
src/shell/states/Pipeline.zig
src/shell/states/Script.zig
src/shell/states/Stmt.zig
src/shell/states/Subshell.zig
src/shell/subproc.zig
src/shell/util.zig
src/shell/Yield.zig
src/sourcemap/CodeCoverage.zig
src/sourcemap/JSSourceMap.zig
src/sourcemap/LineOffsetTable.zig
src/sourcemap/sourcemap.zig
src/sourcemap/VLQ.zig
src/sql/DataCell.zig
src/sql/postgres.zig
src/sql/postgres/AnyPostgresError.zig
src/sql/postgres/AuthenticationState.zig
src/sql/postgres/CommandTag.zig
src/sql/postgres/ConnectionFlags.zig
src/sql/postgres/Data.zig
src/sql/postgres/DataCell.zig
src/sql/postgres/DebugSocketMonitorReader.zig
src/sql/postgres/DebugSocketMonitorWriter.zig
src/sql/postgres/ObjectIterator.zig
src/sql/postgres/PostgresCachedStructure.zig
src/sql/postgres/PostgresProtocol.zig
src/sql/postgres/PostgresRequest.zig
src/sql/postgres/PostgresSQLConnection.zig
src/sql/postgres/PostgresSQLContext.zig
src/sql/postgres/PostgresSQLQuery.zig
src/sql/postgres/PostgresSQLQueryResultMode.zig
src/sql/postgres/PostgresSQLStatement.zig
src/sql/postgres/PostgresTypes.zig
src/sql/postgres/protocol/ArrayList.zig
src/sql/postgres/protocol/Authentication.zig
src/sql/postgres/protocol/BackendKeyData.zig
src/sql/postgres/protocol/Close.zig
src/sql/postgres/protocol/ColumnIdentifier.zig
src/sql/postgres/protocol/CommandComplete.zig
src/sql/postgres/protocol/CopyData.zig
src/sql/postgres/protocol/CopyFail.zig
src/sql/postgres/protocol/CopyInResponse.zig
src/sql/postgres/protocol/CopyOutResponse.zig
src/sql/postgres/protocol/DataRow.zig
src/sql/postgres/protocol/DecoderWrap.zig
src/sql/postgres/protocol/Describe.zig
src/sql/postgres/protocol/ErrorResponse.zig
src/sql/postgres/protocol/Execute.zig
src/sql/postgres/protocol/FieldDescription.zig
src/sql/postgres/protocol/FieldMessage.zig
src/sql/postgres/protocol/FieldType.zig
src/sql/postgres/protocol/NegotiateProtocolVersion.zig
src/sql/postgres/protocol/NewReader.zig
src/sql/postgres/protocol/NewWriter.zig
src/sql/postgres/protocol/NoticeResponse.zig
src/sql/postgres/protocol/NotificationResponse.zig
src/sql/postgres/protocol/ParameterDescription.zig
src/sql/postgres/protocol/ParameterStatus.zig
src/sql/postgres/protocol/Parse.zig
src/sql/postgres/protocol/PasswordMessage.zig
src/sql/postgres/protocol/PortalOrPreparedStatement.zig
src/sql/postgres/protocol/ReadyForQuery.zig
src/sql/postgres/protocol/RowDescription.zig
src/sql/postgres/protocol/SASLInitialResponse.zig
src/sql/postgres/protocol/SASLResponse.zig
src/sql/postgres/protocol/StackReader.zig
src/sql/postgres/protocol/StartupMessage.zig
src/sql/postgres/protocol/TransactionStatusIndicator.zig
src/sql/postgres/protocol/WriteWrap.zig
src/sql/postgres/protocol/zHelpers.zig
src/sql/postgres/QueryBindingIterator.zig
src/sql/postgres/SASL.zig
src/sql/postgres/Signature.zig
src/sql/postgres/SocketMonitor.zig
src/sql/postgres/SSLMode.zig
src/sql/postgres/Status.zig
src/sql/postgres/TLSStatus.zig
src/sql/postgres/types/bool.zig
src/sql/postgres/types/bytea.zig
src/sql/postgres/types/date.zig
src/sql/postgres/types/int_types.zig
src/sql/postgres/types/json.zig
src/sql/postgres/types/numeric.zig
src/sql/postgres/types/PostgresString.zig
src/sql/postgres/types/Tag.zig
src/sql/postgres/postgres_protocol.zig
src/sql/postgres/postgres_types.zig
src/StandaloneModuleGraph.zig
src/StaticHashMap.zig
src/string_immutable.zig
src/string_types.zig
src/string.zig
src/string/HashedString.zig
src/string/immutable.zig
src/string/immutable/escapeHTML.zig
src/string/immutable/exact_size_matcher.zig
src/string/immutable/grapheme.zig
src/string/immutable/paths.zig
src/string/immutable/unicode.zig
src/string/immutable/visible.zig
src/string/MutableString.zig
src/string/PathString.zig
src/string/SmolStr.zig
src/string/StringBuilder.zig
src/string/StringJoiner.zig
src/string/WTFStringImpl.zig
src/sync.zig
src/sys_uv.zig
src/sys.zig
src/system_timer.zig
src/test/fixtures.zig
src/test/recover.zig
src/threading.zig
src/threading/channel.zig
src/threading/Condition.zig
src/threading/Futex.zig
src/threading/guarded_value.zig
src/threading/Mutex.zig
src/threading/ThreadPool.zig
src/threading/unbounded_queue.zig
src/threading/WaitGroup.zig
src/thread_pool.zig
src/tmp.zig
src/toml/toml_lexer.zig
src/toml/toml_parser.zig
src/tracy.zig
src/trait.zig
src/transpiler.zig

View File

@@ -42,29 +42,6 @@ else()
set(CONFIGURE_DEPENDS "")
endif()
# --- Dependencies ---
set(BUN_DEPENDENCIES
BoringSSL
Brotli
Cares
Highway
LibDeflate
LolHtml
Lshpack
Mimalloc
TinyCC
Zlib
LibArchive # must be loaded after zlib
HdrHistogram # must be loaded after zlib
Zstd
)
include(CloneZstd)
# foreach(dependency ${BUN_DEPENDENCIES})
# include(Clone${dependency})
# endforeach()
# --- Codegen ---
set(BUN_ERROR_SOURCE ${CWD}/packages/bun-error)
@@ -255,10 +232,6 @@ set(BUN_ZIG_GENERATED_CLASSES_SCRIPT ${CWD}/src/codegen/generate-classes.ts)
absolute_sources(BUN_ZIG_GENERATED_CLASSES_SOURCES ${CWD}/cmake/sources/ZigGeneratedClassesSources.txt)
# hand written cpp source files. Full list of "source" code (including codegen) is in BUN_CPP_SOURCES
absolute_sources(BUN_CXX_SOURCES ${CWD}/cmake/sources/CxxSources.txt)
absolute_sources(BUN_C_SOURCES ${CWD}/cmake/sources/CSources.txt)
set(BUN_ZIG_GENERATED_CLASSES_OUTPUTS
${CODEGEN_PATH}/ZigGeneratedClasses.h
${CODEGEN_PATH}/ZigGeneratedClasses.cpp
@@ -312,27 +285,6 @@ set(BUN_JAVASCRIPT_OUTPUTS
${CWD}/src/bun.js/bindings/GeneratedJS2Native.zig
)
set(BUN_CPP_OUTPUTS
${CODEGEN_PATH}/cpp.zig
)
register_command(
TARGET
bun-cppbind
COMMENT
"Generating C++ --> Zig bindings"
COMMAND
${BUN_EXECUTABLE}
${CWD}/src/codegen/cppbind.ts
${CWD}/src
${CODEGEN_PATH}
SOURCES
${BUN_JAVASCRIPT_CODEGEN_SOURCES}
${BUN_CXX_SOURCES}
OUTPUTS
${BUN_CPP_OUTPUTS}
)
register_command(
TARGET
bun-js-modules
@@ -456,7 +408,6 @@ set(BUN_OBJECT_LUT_SOURCES
${CWD}/src/bun.js/bindings/ProcessBindingConstants.cpp
${CWD}/src/bun.js/bindings/ProcessBindingFs.cpp
${CWD}/src/bun.js/bindings/ProcessBindingNatives.cpp
${CWD}/src/bun.js/bindings/ProcessBindingHTTPParser.cpp
${CWD}/src/bun.js/modules/NodeModuleModule.cpp
${CODEGEN_PATH}/ZigGeneratedClasses.lut.txt
)
@@ -470,7 +421,6 @@ set(BUN_OBJECT_LUT_OUTPUTS
${CODEGEN_PATH}/ProcessBindingConstants.lut.h
${CODEGEN_PATH}/ProcessBindingFs.lut.h
${CODEGEN_PATH}/ProcessBindingNatives.lut.h
${CODEGEN_PATH}/ProcessBindingHTTPParser.lut.h
${CODEGEN_PATH}/NodeModuleModule.lut.h
${CODEGEN_PATH}/ZigGeneratedClasses.lut.h
)
@@ -562,7 +512,6 @@ set(BUN_ZIG_GENERATED_SOURCES
${BUN_ERROR_CODE_OUTPUTS}
${BUN_ZIG_GENERATED_CLASSES_OUTPUTS}
${BUN_JAVASCRIPT_OUTPUTS}
${BUN_CPP_OUTPUTS}
)
# In debug builds, these are not embedded, but rather referenced at runtime.
@@ -631,8 +580,6 @@ register_command(
${BUN_ZIG_OUTPUT}
TARGETS
clone-zig
clone-zstd
bun-cppbind
SOURCES
${BUN_ZIG_SOURCES}
${BUN_ZIG_GENERATED_SOURCES}
@@ -645,6 +592,10 @@ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "build.zig")
set(BUN_USOCKETS_SOURCE ${CWD}/packages/bun-usockets)
# hand written cpp source files. Full list of "source" code (including codegen) is in BUN_CPP_SOURCES
absolute_sources(BUN_CXX_SOURCES ${CWD}/cmake/sources/CxxSources.txt)
absolute_sources(BUN_C_SOURCES ${CWD}/cmake/sources/CSources.txt)
if(WIN32)
list(APPEND BUN_CXX_SOURCES ${CWD}/src/bun.js/bindings/windows/rescle.cpp)
list(APPEND BUN_CXX_SOURCES ${CWD}/src/bun.js/bindings/windows/rescle-binding.cpp)
@@ -673,13 +624,8 @@ register_command(
-DDOWNLOAD_PATH=${NODEJS_HEADERS_PATH}
-DDOWNLOAD_URL=https://nodejs.org/dist/v${NODEJS_VERSION}/node-v${NODEJS_VERSION}-headers.tar.gz
-P ${CWD}/cmake/scripts/DownloadUrl.cmake
COMMAND
${CMAKE_COMMAND}
-DNODE_INCLUDE_DIR=${NODEJS_HEADERS_PATH}/include
-P ${CWD}/cmake/scripts/PrepareNodeHeaders.cmake
OUTPUTS
${NODEJS_HEADERS_PATH}/include/node/node_version.h
${NODEJS_HEADERS_PATH}/include/.node-headers-prepared
)
list(APPEND BUN_CPP_SOURCES
@@ -701,14 +647,20 @@ if(WIN32)
else()
set(Bun_VERSION_WITH_TAG ${VERSION})
endif()
set(BUN_ICO_PATH ${CWD}/src/bun.ico)
configure_file(${CWD}/src/bun.ico ${CODEGEN_PATH}/bun.ico COPYONLY)
set(BUN_ICO_PATH ${CODEGEN_PATH}/bun.ico)
configure_file(
${CWD}/src/windows-app-info.rc
${CODEGEN_PATH}/windows-app-info.rc
@ONLY
)
set(WINDOWS_RESOURCES ${CODEGEN_PATH}/windows-app-info.rc ${CWD}/src/bun.exe.manifest)
add_custom_command(
OUTPUT ${CODEGEN_PATH}/windows-app-info.res
COMMAND rc.exe /fo ${CODEGEN_PATH}/windows-app-info.res ${CODEGEN_PATH}/windows-app-info.rc
DEPENDS ${CODEGEN_PATH}/windows-app-info.rc ${CODEGEN_PATH}/bun.ico
COMMENT "Adding Windows resource file ${CODEGEN_PATH}/windows-app-info.res with ico in ${CODEGEN_PATH}/bun.ico"
)
set(WINDOWS_RESOURCES ${CODEGEN_PATH}/windows-app-info.res)
endif()
# --- Executable ---
@@ -780,7 +732,6 @@ target_include_directories(${bun} PRIVATE
${CWD}/src/bun.js/bindings/webcore
${CWD}/src/bun.js/bindings/webcrypto
${CWD}/src/bun.js/bindings/node/crypto
${CWD}/src/bun.js/bindings/node/http
${CWD}/src/bun.js/bindings/sqlite
${CWD}/src/bun.js/bindings/v8
${CWD}/src/bun.js/modules
@@ -791,7 +742,6 @@ target_include_directories(${bun} PRIVATE
${VENDOR_PATH}
${VENDOR_PATH}/picohttpparser
${NODEJS_HEADERS_PATH}/include
${NODEJS_HEADERS_PATH}/include/node
)
if(NOT WIN32)
@@ -940,9 +890,6 @@ if(NOT WIN32)
else()
target_compile_options(${bun} PUBLIC
-Wno-nullability-completeness
-Wno-inconsistent-dllimport
-Wno-incompatible-pointer-types
-Wno-deprecated-declarations
)
endif()
@@ -974,32 +921,14 @@ endif()
if(APPLE)
target_link_options(${bun} PUBLIC
-dead_strip
-dead_strip_dylibs
-Wl,-ld_new
-Wl,-no_compact_unwind
-Wl,-stack_size,0x1200000
-fno-keep-static-consts
-Wl,-map,${bun}.linker-map
)
if(DEBUG)
target_link_options(${bun} PUBLIC
# Suppress ALL linker warnings on macOS.
# The intent is to only suppress linker alignment warnings.
# As of July 21st, 2025 there doesn't seem to be a more specific suppression just for linker alignment warnings.
# If you find one, please update this to only be for linker alignment.
-Wl,-w
)
endif()
# don't strip in debug, this seems to be needed so that the Zig std library
# `*dbHelper` DWARF symbols (used by LLDB for pretty printing) are in the
# output executable
if(NOT DEBUG)
target_link_options(${bun} PUBLIC
-dead_strip
-dead_strip_dylibs
)
endif()
endif()
if(LINUX)
@@ -1036,6 +965,7 @@ if(LINUX)
-Wl,-no-pie
-Wl,-icf=safe
-Wl,--as-needed
-Wl,--gc-sections
-Wl,-z,stack-size=12800000
-Wl,--compress-debug-sections=zlib
-Wl,-z,lazy
@@ -1051,15 +981,6 @@ if(LINUX)
-Wl,--build-id=sha1 # Better for debugging than default
-Wl,-Map=${bun}.linker-map
)
# don't strip in debug, this seems to be needed so that the Zig std library
# `*dbHelper` DWARF symbols (used by LLDB for pretty printing) are in the
# output executable
if(NOT DEBUG)
target_link_options(${bun} PUBLIC
-Wl,--gc-sections
)
endif()
endif()
# --- Symbols list ---
@@ -1125,6 +1046,22 @@ endif()
# --- Dependencies ---
set(BUN_DEPENDENCIES
BoringSSL
Brotli
Cares
Highway
LibDeflate
LolHtml
Lshpack
Mimalloc
TinyCC
Zlib
LibArchive # must be loaded after zlib
HdrHistogram # must be loaded after zlib
Zstd
)
if(WIN32)
list(APPEND BUN_DEPENDENCIES Libuv)
endif()

View File

@@ -4,7 +4,7 @@ register_repository(
REPOSITORY
c-ares/c-ares
COMMIT
d3a507e920e7af18a5efb7f9f1d8044ed4750013
4f4912bce7374f787b10576851b687935f018e17
)
register_cmake_command(

View File

@@ -4,7 +4,7 @@ register_repository(
REPOSITORY
libarchive/libarchive
COMMIT
7118f97c26bf0b2f426728b482f86508efc81d02
898dc8319355b7e985f68a9819f182aaed61b53a
)
register_cmake_command(
@@ -20,14 +20,11 @@ register_cmake_command(
-DENABLE_WERROR=OFF
-DENABLE_BZip2=OFF
-DENABLE_CAT=OFF
-DENABLE_CPIO=OFF
-DENABLE_UNZIP=OFF
-DENABLE_EXPAT=OFF
-DENABLE_ICONV=OFF
-DENABLE_LIBB2=OFF
-DENABLE_LibGCC=OFF
-DENABLE_LIBXML2=OFF
-DENABLE_WIN32_XMLLITE=OFF
-DENABLE_LZ4=OFF
-DENABLE_LZMA=OFF
-DENABLE_LZO=OFF

View File

@@ -4,7 +4,7 @@ register_repository(
REPOSITORY
cloudflare/lol-html
COMMIT
d64457d9ff0143deef025d5df7e8586092b9afb7
67f1d4ffd6b74db7e053fb129dcce620193c180d
)
set(LOLHTML_CWD ${VENDOR_PATH}/lolhtml/c-api)

View File

@@ -1,3 +1,12 @@
register_repository(
NAME
zstd
REPOSITORY
facebook/zstd
COMMIT
f8745da6ff1ad1e7bab384bd1f9d742439278e99
)
register_cmake_command(
TARGET
zstd
@@ -14,6 +23,4 @@ register_cmake_command(
LIBRARIES
zstd_static WIN32
zstd UNIX
INCLUDES
lib
)

View File

@@ -1,8 +0,0 @@
register_repository(
NAME
zstd
REPOSITORY
facebook/zstd
COMMIT
f8745da6ff1ad1e7bab384bd1f9d742439278e99
)

View File

@@ -72,14 +72,12 @@ macro(find_llvm_command variable command)
)
endif()
math(EXPR LLVM_VERSION_NEXT_MAJOR "${LLVM_VERSION_MAJOR} + 1")
find_command(
VARIABLE ${variable}
VERSION_VARIABLE LLVM_VERSION
COMMAND ${commands}
PATHS ${LLVM_PATHS}
VERSION ">=${LLVM_VERSION_MAJOR}.1.0 <${LLVM_VERSION_NEXT_MAJOR}.0.0"
VERSION >=${LLVM_VERSION_MAJOR}.1.0
)
list(APPEND CMAKE_ARGS -D${variable}=${${variable}})
endmacro()

View File

@@ -2,7 +2,7 @@ option(WEBKIT_VERSION "The version of WebKit to use")
option(WEBKIT_LOCAL "If a local version of WebKit should be used instead of downloading")
if(NOT WEBKIT_VERSION)
set(WEBKIT_VERSION 1098cc50652ab1eab171f58f7669e19ca6c276ae)
set(WEBKIT_VERSION b98e20b11e6ab044f73218bdd05ab064587b9ead)
endif()
string(SUBSTRING ${WEBKIT_VERSION} 0 16 WEBKIT_VERSION_PREFIX)

View File

@@ -20,7 +20,7 @@ else()
unsupported(CMAKE_SYSTEM_NAME)
endif()
set(ZIG_COMMIT "edc6229b1fafb1701a25fb4e17114cc756991546")
set(ZIG_COMMIT "a207204ee57a061f2fb96c7bae0c491b609e73a5")
optionx(ZIG_TARGET STRING "The zig target to use" DEFAULT ${DEFAULT_ZIG_TARGET})
if(CMAKE_BUILD_TYPE STREQUAL "Release")
@@ -55,13 +55,13 @@ optionx(ZIG_OBJECT_FORMAT "obj|bc" "Output file format for Zig object files" DEF
optionx(ZIG_LOCAL_CACHE_DIR FILEPATH "The path to local the zig cache directory" DEFAULT ${CACHE_PATH}/zig/local)
optionx(ZIG_GLOBAL_CACHE_DIR FILEPATH "The path to the global zig cache directory" DEFAULT ${CACHE_PATH}/zig/global)
if(CI)
if(CI AND CMAKE_HOST_APPLE)
set(ZIG_COMPILER_SAFE_DEFAULT ON)
else()
set(ZIG_COMPILER_SAFE_DEFAULT OFF)
endif()
optionx(ZIG_COMPILER_SAFE BOOL "Download a ReleaseSafe build of the Zig compiler." DEFAULT ${ZIG_COMPILER_SAFE_DEFAULT})
optionx(ZIG_COMPILER_SAFE BOOL "Download a ReleaseSafe build of the Zig compiler. Only availble on macos aarch64." DEFAULT ${ZIG_COMPILER_SAFE_DEFAULT})
setenv(ZIG_LOCAL_CACHE_DIR ${ZIG_LOCAL_CACHE_DIR})
setenv(ZIG_GLOBAL_CACHE_DIR ${ZIG_GLOBAL_CACHE_DIR})

View File

@@ -260,8 +260,8 @@ _bun_pm_completion() {
'hash\:"generate & print the hash of the current lockfile" '
'hash-string\:"print the string used to hash the lockfile" '
'hash-print\:"print the hash stored in the current lockfile" '
'audit\:"run a security audit of dependencies in Bun'\''s lockfile"'
'cache\:"print the path to the cache folder" '
'version\:"bump the version in package.json and create a git tag" '
)
_alternative "args:cmd3:(($sub_commands))"
@@ -300,40 +300,6 @@ _bun_pm_completion() {
$pmargs &&
ret=0
;;
version)
version_args=(
"patch[increment patch version]"
"minor[increment minor version]"
"major[increment major version]"
"prepatch[increment patch version and add pre-release]"
"preminor[increment minor version and add pre-release]"
"premajor[increment major version and add pre-release]"
"prerelease[increment pre-release version]"
"from-git[use version from latest git tag]"
)
pmargs=(
"--no-git-tag-version[don't create a git commit and tag]"
"--allow-same-version[allow bumping to the same version]"
"-m[use the given message for the commit]:message"
"--message[use the given message for the commit]:message"
"--preid[identifier to prefix pre-release versions]:preid"
)
_arguments -s -C \
'1: :->cmd' \
'2: :->cmd2' \
'3: :->increment' \
$pmargs &&
ret=0
case $state in
increment)
_alternative "args:increment:(($version_args))"
;;
esac
;;
esac
@@ -574,7 +540,6 @@ _bun_update_completion() {
'--save[Save to package.json]' \
'--dry-run[Don'"'"'t install anything]' \
'--frozen-lockfile[Disallow changes to lockfile]' \
'--latest[Updates dependencies to latest version, regardless of compatibility]' \
'-f[Always request the latest versions from the registry & reinstall all dependencies]' \
'--force[Always request the latest versions from the registry & reinstall all dependencies]' \
'--cache-dir[Store & load cached data from a specific directory path]:cache-dir' \
@@ -608,7 +573,7 @@ _bun_outdated_completion() {
'--no-progress[Disable the progress bar]' \
'--help[Print this help menu]' &&
ret=0
case $state in
config)
_bun_list_bunfig_toml

View File

@@ -522,7 +522,7 @@ for await (const chunk of stream) {
}
```
For a more complete discussion of streams in Bun, see [API > Streams](https://bun.com/docs/api/streams).
For a more complete discussion of streams in Bun, see [API > Streams](https://bun.sh/docs/api/streams).
## Conversion

View File

@@ -2,7 +2,7 @@
## Usage (cc in `bun:ffi`)
See the [introduction blog post](https://bun.com/blog/compile-and-run-c-in-js) for more information.
See the [introduction blog post](https://bun.sh/blog/compile-and-run-c-in-js) for more information.
JavaScript:

View File

@@ -2,25 +2,6 @@
**Note** — Bun provides a browser- and Node.js-compatible [console](https://developer.mozilla.org/en-US/docs/Web/API/console) global. This page only documents Bun-native APIs.
{% /callout %}
## Object inspection depth
Bun allows you to configure how deeply nested objects are displayed in `console.log()` output:
- **CLI flag**: Use `--console-depth <number>` to set the depth for a single run
- **Configuration**: Set `console.depth` in your `bunfig.toml` for persistent configuration
- **Default**: Objects are inspected to a depth of `2` levels
```js
const nested = { a: { b: { c: { d: "deep" } } } };
console.log(nested);
// Default (depth 2): { a: { b: [Object] } }
// With depth 4: { a: { b: { c: { d: 'deep' } } } }
```
The CLI flag takes precedence over the configuration file setting.
## Reading from stdin
In Bun, the `console` object can be used as an `AsyncIterable` to sequentially read lines from `process.stdin`.
```ts

View File

@@ -3,7 +3,7 @@ Bun implements the `node:dns` module.
```ts
import * as dns from "node:dns";
const addrs = await dns.promises.resolve4("bun.com", { ttl: true });
const addrs = await dns.promises.resolve4("bun.sh", { ttl: true });
console.log(addrs);
// => [{ address: "172.67.161.226", family: 4, ttl: 0 }, ...]
```
@@ -54,10 +54,10 @@ Here's an example:
```ts
import { dns } from "bun";
dns.prefetch("bun.com", 443);
dns.prefetch("bun.sh", 443);
//
// ... sometime later ...
await fetch("https://bun.com");
await fetch("https://bun.sh");
```
### `dns.getCacheStats()`

View File

@@ -267,7 +267,7 @@ const response = await fetch("s3://my-bucket/path/to/object", {
Note: Only PUT and POST methods support request bodies when using S3. For uploads, Bun automatically uses multipart upload for streaming bodies.
You can read more about Bun's S3 support in the [S3](https://bun.com/docs/api/s3) documentation.
You can read more about Bun's S3 support in the [S3](https://bun.sh/docs/api/s3) documentation.
#### File URLs - `file://`
@@ -376,14 +376,14 @@ To prefetch a DNS entry, you can use the `dns.prefetch` API. This API is useful
```ts
import { dns } from "bun";
dns.prefetch("bun.com");
dns.prefetch("bun.sh");
```
#### DNS caching
By default, Bun caches and deduplicates DNS queries in-memory for up to 30 seconds. You can see the cache stats by calling `dns.getCacheStats()`:
To learn more about DNS caching in Bun, see the [DNS caching](https://bun.com/docs/api/dns) documentation.
To learn more about DNS caching in Bun, see the [DNS caching](https://bun.sh/docs/api/dns) documentation.
### Preconnect to a host
@@ -392,7 +392,7 @@ To preconnect to a host, you can use the `fetch.preconnect` API. This API is use
```ts
import { fetch } from "bun";
fetch.preconnect("https://bun.com");
fetch.preconnect("https://bun.sh");
```
Note: calling `fetch` immediately after `fetch.preconnect` will not make your request faster. Preconnecting only helps if you know you'll need to connect to a host soon, but you're not ready to make the request yet.
@@ -402,7 +402,7 @@ Note: calling `fetch` immediately after `fetch.preconnect` will not make your re
To preconnect to a host at startup, you can pass `--fetch-preconnect`:
```sh
$ bun --fetch-preconnect https://bun.com ./my-script.ts
$ bun --fetch-preconnect https://bun.sh ./my-script.ts
```
This is sort of like `<link rel="preconnect">` in HTML.

View File

@@ -1,8 +1,8 @@
{% callout %}
<!-- **Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. Existing Node.js projects may use Bun's [nearly complete](https://bun.com/docs/runtime/nodejs-apis#node-fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module. -->
<!-- **Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. Existing Node.js projects may use Bun's [nearly complete](https://bun.sh/docs/runtime/nodejs-apis#node-fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module. -->
**Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. For operations that are not yet available with `Bun.file`, such as `mkdir` or `readdir`, you can use Bun's [nearly complete](https://bun.com/docs/runtime/nodejs-apis#node-fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module.
**Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. For operations that are not yet available with `Bun.file`, such as `mkdir` or `readdir`, you can use Bun's [nearly complete](https://bun.sh/docs/runtime/nodejs-apis#node-fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module.
{% /callout %}
@@ -208,7 +208,7 @@ await Bun.write(Bun.stdout, input);
To write the body of an HTTP response to disk:
```ts
const response = await fetch("https://bun.com");
const response = await fetch("https://bun.sh");
await Bun.write("index.html", response);
```

View File

@@ -34,7 +34,7 @@ Bun implements the following globals.
- [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer)
- Node.js
- See [Node.js > `Buffer`](https://bun.com/docs/runtime/nodejs-apis#node-buffer)
- See [Node.js > `Buffer`](https://bun.sh/docs/runtime/nodejs-apis#node-buffer)
---
@@ -172,7 +172,7 @@ Bun implements the following globals.
- [`global`](https://nodejs.org/api/globals.html#global)
- Node.js
- See [Node.js > `global`](https://bun.com/docs/runtime/nodejs-apis#global).
- See [Node.js > `global`](https://bun.sh/docs/runtime/nodejs-apis#global).
---
@@ -188,7 +188,7 @@ Bun implements the following globals.
---
- [`HTMLRewriter`](https://bun.com/docs/api/html-rewriter)
- [`HTMLRewriter`](https://bun.sh/docs/api/html-rewriter)
- Cloudflare
- &nbsp;
@@ -220,7 +220,7 @@ Bun implements the following globals.
- [`process`](https://nodejs.org/api/process.html)
- Node.js
- See [Node.js > `process`](https://bun.com/docs/runtime/nodejs-apis#node-process)
- See [Node.js > `process`](https://bun.sh/docs/runtime/nodejs-apis#node-process)
---

View File

@@ -175,7 +175,6 @@ Bun.hash.xxHash3("data", 1234);
Bun.hash.murmur32v3("data", 1234);
Bun.hash.murmur32v2("data", 1234);
Bun.hash.murmur64v2("data", 1234);
Bun.hash.rapidhash("data", 1234);
```
## `Bun.CryptoHasher`

View File

@@ -1,7 +1,7 @@
The page primarily documents the Bun-native `Bun.serve` API. Bun also implements [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and the Node.js [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html) modules.
{% callout %}
These modules have been re-implemented to use Bun's fast internal HTTP infrastructure. Feel free to use these modules directly; frameworks like [Express](https://expressjs.com/) that depend on these modules should work out of the box. For granular compatibility information, see [Runtime > Node.js APIs](https://bun.com/docs/runtime/nodejs-apis).
These modules have been re-implemented to use Bun's fast internal HTTP infrastructure. Feel free to use these modules directly; frameworks like [Express](https://expressjs.com/) that depend on these modules should work out of the box. For granular compatibility information, see [Runtime > Node.js APIs](https://bun.sh/docs/runtime/nodejs-apis).
{% /callout %}
To start a high-performance HTTP server with a clean API, the recommended approach is [`Bun.serve`](#start-a-server-bun-serve).
@@ -149,7 +149,7 @@ Bun.serve({
}),
// Redirects
"/blog": Response.redirect("https://bun.com/blog"),
"/blog": Response.redirect("https://bun.sh/blog"),
// API responses
"/api/config": Response.json({
@@ -326,11 +326,7 @@ Bun.serve({
### HTML imports
Bun supports importing HTML files directly into your server code, enabling full-stack applications with both server-side and client-side code. HTML imports work in two modes:
**Development (`bun --hot`):** Assets are bundled on-demand at runtime, enabling hot module replacement (HMR) for a fast, iterative development experience. When you change your frontend code, the browser automatically updates without a full page reload.
**Production (`bun build`):** When building with `bun build --target=bun`, the `import index from "./index.html"` statement resolves to a pre-built manifest object containing all bundled client assets. `Bun.serve` consumes this manifest to serve optimized assets with zero runtime bundling overhead. This is ideal for deploying to production.
To add a client-side single-page app, you can use an HTML import:
```ts
import myReactSinglePageApp from "./index.html";
@@ -342,9 +338,9 @@ Bun.serve({
});
```
HTML imports don't just serve HTML — it's a full-featured frontend bundler, transpiler, and toolkit built using Bun's [bundler](https://bun.com/docs/bundler), JavaScript transpiler and CSS parser. You can use this to build full-featured frontends with React, TypeScript, Tailwind CSS, and more.
HTML imports don't just serve HTML. It's a full-featured frontend bundler, transpiler, and toolkit built using Bun's [bundler](https://bun.sh/docs/bundler), JavaScript transpiler and CSS parser.
For a complete guide on building full-stack applications with HTML imports, including detailed examples and best practices, see [/docs/bundler/fullstack](https://bun.com/docs/bundler/fullstack).
You can use this to build a full-featured frontend with React, TypeScript, Tailwind CSS, and more. Check out [/docs/bundler/fullstack](https://bun.sh/docs/bundler/fullstack) to learn more.
### Practical example: REST API
@@ -605,7 +601,7 @@ Bun.serve({
```
{% callout %}
[Learn more about debugging in Bun](https://bun.com/docs/runtime/debugger)
[Learn more about debugging in Bun](https://bun.sh/docs/runtime/debugger)
{% /callout %}
The call to `Bun.serve` returns a `Server` object. To stop the server, call the `.stop()` method.
@@ -772,7 +768,7 @@ Instead of passing the server options into `Bun.serve`, `export default` it. Thi
$ bun --hot server.ts
``` -->
<!-- It's possible to configure hot reloading while using the explicit `Bun.serve` API; for details refer to [Runtime > Hot reloading](https://bun.com/docs/runtime/hot). -->
<!-- It's possible to configure hot reloading while using the explicit `Bun.serve` API; for details refer to [Runtime > Hot reloading](https://bun.sh/docs/runtime/hot). -->
## Streaming files

View File

@@ -4,7 +4,7 @@ Production servers often read, upload, and write files to S3-compatible object s
### Bun's S3 API is fast
{% image src="https://bun.com/bun-s3-node.gif" alt="Bun's S3 API is fast" caption="Left: Bun v1.1.44. Right: Node.js v23.6.0" /%}
{% image src="https://bun.sh/bun-s3-node.gif" alt="Bun's S3 API is fast" caption="Left: Bun v1.1.44. Right: Node.js v23.6.0" /%}
{% /callout %}
@@ -160,8 +160,7 @@ const writer = s3file.writer({
partSize: 5 * 1024 * 1024,
});
for (let i = 0; i < 10; i++) {
writer.write(bigFile);
await writer.flush();
await writer.write(bigFile);
}
await writer.end();
```

View File

@@ -34,7 +34,7 @@ const proc = Bun.spawn(["cat"], {
),
});
const text = await proc.stdout.text();
const text = await new Response(proc.stdout).text();
console.log(text); // "const input = "hello world".repeat(400); ..."
```
@@ -113,34 +113,14 @@ proc.stdin.flush();
proc.stdin.end();
```
Passing a `ReadableStream` to `stdin` lets you pipe data from a JavaScript `ReadableStream` directly to the subprocess's input:
```ts
const stream = new ReadableStream({
start(controller) {
controller.enqueue("Hello from ");
controller.enqueue("ReadableStream!");
controller.close();
},
});
const proc = Bun.spawn(["cat"], {
stdin: stream,
stdout: "pipe",
});
const output = await new Response(proc.stdout).text();
console.log(output); // "Hello from ReadableStream!"
```
## Output streams
You can read results from the subprocess via the `stdout` and `stderr` properties. By default these are instances of `ReadableStream`.
```ts
const proc = Bun.spawn(["bun", "--version"]);
const text = await proc.stdout.text();
console.log(text); // => "$BUN_LATEST_VERSION\n"
const text = await new Response(proc.stdout).text();
console.log(text); // => "$BUN_LATEST_VERSION"
```
Configure the output stream by passing one of the following values to `stdout/stderr`:

View File

@@ -274,23 +274,6 @@ If no connection URL is provided, the system checks for the following individual
| `PGPASSWORD` | - | (empty) | Database password |
| `PGDATABASE` | - | username | Database name |
## Runtime Preconnection
Bun can preconnect to PostgreSQL at startup to improve performance by establishing database connections before your application code runs. This is useful for reducing connection latency on the first database query.
```bash
# Enable PostgreSQL preconnection
bun --sql-preconnect index.js
# Works with DATABASE_URL environment variable
DATABASE_URL=postgres://user:pass@localhost:5432/db bun --sql-preconnect index.js
# Can be combined with other runtime flags
bun --sql-preconnect --hot index.js
```
The `--sql-preconnect` flag will automatically establish a PostgreSQL connection using your configured environment variables at startup. If the connection fails, it won't crash your application - the error will be handled gracefully.
## Connection Options
You can configure your database connection manually by passing options to the SQL constructor:

View File

@@ -234,7 +234,7 @@ const currentFile = import.meta.url;
Bun.openInEditor(currentFile);
```
You can override this via the `debug.editor` setting in your [`bunfig.toml`](https://bun.com/docs/runtime/bunfig).
You can override this via the `debug.editor` setting in your [`bunfig.toml`](https://bun.sh/docs/runtime/bunfig).
```toml-diff#bunfig.toml
+ [debug]
@@ -582,11 +582,11 @@ Compresses a `Uint8Array` using zlib's DEFLATE algorithm.
const buf = Buffer.from("hello".repeat(100));
const compressed = Bun.deflateSync(buf);
buf; // => Buffer(500)
compressed; // => Uint8Array(12)
buf; // => Uint8Array(25)
compressed; // => Uint8Array(10)
```
The second argument supports the same set of configuration options as [`Bun.gzipSync`](#bun-gzipsync).
The second argument supports the same set of configuration options as [`Bun.gzipSync`](#bungzipsync).
## `Bun.inflateSync()`
@@ -704,7 +704,7 @@ Bun.nanoseconds();
Bun implements a set of convenience functions for asynchronously consuming the body of a `ReadableStream` and converting it to various binary formats.
```ts
const stream = (await fetch("https://bun.com")).body;
const stream = (await fetch("https://bun.sh")).body;
stream; // => ReadableStream
await Bun.readableStreamToArrayBuffer(stream);
@@ -787,7 +787,7 @@ const buffer = Buffer.alloc(1024 * 1024);
estimateShallowMemoryUsageOf(buffer);
// => 1048624
const req = new Request("https://bun.com");
const req = new Request("https://bun.sh");
estimateShallowMemoryUsageOf(req);
// => 167

View File

@@ -88,20 +88,6 @@ The order of the `--target` flag does not matter, as long as they're delimited b
On x64 platforms, Bun uses SIMD optimizations which require a modern CPU supporting AVX2 instructions. The `-baseline` build of Bun is for older CPUs that don't support these optimizations. Normally, when you install Bun we automatically detect which version to use but this can be harder to do when cross-compiling since you might not know the target CPU. You usually don't need to worry about it on Darwin x64, but it is relevant for Windows x64 and Linux x64. If you or your users see `"Illegal instruction"` errors, you might need to use the baseline version.
## Build-time constants
Use the `--define` flag to inject build-time constants into your executable, such as version numbers, build timestamps, or configuration values:
```bash
$ bun build --compile --define BUILD_VERSION='"1.2.3"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/cli.ts --outfile mycli
```
These constants are embedded directly into your compiled binary at build time, providing zero runtime overhead and enabling dead code elimination optimizations.
{% callout type="info" %}
For comprehensive examples and advanced patterns, see the [Build-time constants guide](/guides/runtime/build-time-constants).
{% /callout %}
## Deploying to production
Compiled executables reduce memory usage and improve Bun's start time.
@@ -140,117 +126,6 @@ The `--sourcemap` argument embeds a sourcemap compressed with zstd, so that erro
The `--bytecode` argument enables bytecode compilation. Every time you run JavaScript code in Bun, JavaScriptCore (the engine) will compile your source code into bytecode. We can move this parsing work from runtime to bundle time, saving you startup time.
## Act as the Bun CLI
{% note %}
New in Bun v1.2.16
{% /note %}
You can run a standalone executable as if it were the `bun` CLI itself by setting the `BUN_BE_BUN=1` environment variable. When this variable is set, the executable will ignore its bundled entrypoint and instead expose all the features of Bun's CLI.
For example, consider an executable compiled from a simple script:
```sh
$ cat such-bun.js
console.log("you shouldn't see this");
$ bun build --compile ./such-bun.js
[3ms] bundle 1 modules
[89ms] compile such-bun
```
Normally, running `./such-bun` with arguments would execute the script. However, with the `BUN_BE_BUN=1` environment variable, it acts just like the `bun` binary:
```sh
# Executable runs its own entrypoint by default
$ ./such-bun install
you shouldn't see this
# With the env var, the executable acts like the `bun` CLI
$ BUN_BE_BUN=1 ./such-bun install
bun install v1.2.16-canary.1 (1d1db811)
Checked 63 installs across 64 packages (no changes) [5.00ms]
```
This is useful for building CLI tools on top of Bun that may need to install packages, bundle dependencies, run different or local files and more without needing to download a separate binary or install bun.
## Full-stack executables
{% note %}
New in Bun v1.2.17
{% /note %}
Bun's `--compile` flag can create standalone executables that contain both server and client code, making it ideal for full-stack applications. When you import an HTML file in your server code, Bun automatically bundles all frontend assets (JavaScript, CSS, etc.) and embeds them into the executable. When Bun sees the HTML import on the server, it kicks off a frontend build process to bundle JavaScript, CSS, and other assets.
{% codetabs %}
```ts#server.ts
import { serve } from "bun";
import index from "./index.html";
const server = serve({
routes: {
"/": index,
"/api/hello": { GET: () => Response.json({ message: "Hello from API" }) },
},
});
console.log(`Server running at http://localhost:${server.port}`);
```
```html#index.html
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<h1>Hello World</h1>
<script src="./app.js"></script>
</body>
</html>
```
```js#app.js
console.log("Hello from the client!");
```
```css#styles.css
body {
background-color: #f0f0f0;
}
```
{% /codetabs %}
To build this into a single executable:
```sh
bun build --compile ./server.ts --outfile myapp
```
This creates a self-contained binary that includes:
- Your server code
- The Bun runtime
- All frontend assets (HTML, CSS, JavaScript)
- Any npm packages used by your server
The result is a single file that can be deployed anywhere without needing Node.js, Bun, or any dependencies installed. Just run:
```sh
./myapp
```
Bun automatically handles serving the frontend assets with proper MIME types and cache headers. The HTML import is replaced with a manifest object that `Bun.serve` uses to efficiently serve pre-bundled assets.
For more details on building full-stack applications with Bun, see the [full-stack guide](/docs/bundler/fullstack).
## Worker
To use workers in a standalone executable, add the worker's entrypoint to the CLI arguments:
@@ -299,7 +174,7 @@ $ ./hello
Standalone executables support embedding files.
To embed files into an executable with `bun build --compile`, import the file in your code.
To embed files into an executable with `bun build --compile`, import the file in your code
```ts
// this becomes an internal file path
@@ -478,4 +353,5 @@ Currently, the `--compile` flag can only accept a single entrypoint at a time an
- `--splitting`
- `--public-path`
- `--target=node` or `--target=browser`
- `--format` - always outputs a binary executable. Internally, it's almost esm.
- `--no-bundle` - we always bundle everything into the executable.

View File

@@ -1,3 +1,5 @@
Using `Bun.serve()`'s `routes` option, you can run your frontend and backend in the same app with no extra steps.
To get started, import HTML files and pass them to the `routes` option in `Bun.serve()`.
```ts
@@ -232,92 +234,7 @@ When `console: true` is set, Bun will stream console logs from the browser to th
#### Production mode
Hot reloading and `development: true` helps you iterate quickly, but in production, your server should be as fast as possible and have as few external dependencies as possible.
##### Ahead of time bundling (recommended)
As of Bun v1.2.17, you can use `Bun.build` or `bun build` to bundle your full-stack application ahead of time.
```sh
$ bun build --target=bun --production --outdir=dist ./src/index.ts
```
When Bun's bundler sees an HTML import from server-side code, it will bundle the referenced JavaScript/TypeScript/TSX/JSX and CSS files into a manifest object that Bun.serve() can use to serve the assets.
```ts
import { serve } from "bun";
import index from "./index.html";
serve({
routes: { "/": index },
});
```
{% details summary="Internally, the `index` variable is a manifest object that looks something like this" %}
```json
{
"index": "./index.html",
"files": [
{
"input": "index.html",
"path": "./index-f2me3qnf.js",
"loader": "js",
"isEntry": true,
"headers": {
"etag": "eet6gn75",
"content-type": "text/javascript;charset=utf-8"
}
},
{
"input": "index.html",
"path": "./index.html",
"loader": "html",
"isEntry": true,
"headers": {
"etag": "r9njjakd",
"content-type": "text/html;charset=utf-8"
}
},
{
"input": "index.html",
"path": "./index-gysa5fmk.css",
"loader": "css",
"isEntry": true,
"headers": {
"etag": "50zb7x61",
"content-type": "text/css;charset=utf-8"
}
},
{
"input": "logo.svg",
"path": "./logo-kygw735p.svg",
"loader": "file",
"isEntry": false,
"headers": {
"etag": "kygw735p",
"content-type": "application/octet-stream"
}
},
{
"input": "react.svg",
"path": "./react-ck11dneg.svg",
"loader": "file",
"isEntry": false,
"headers": {
"etag": "ck11dneg",
"content-type": "application/octet-stream"
}
}
]
}
```
{% /details %}
##### Runtime bundling
When adding a build step is too complicated, you can set `development: false` in `Bun.serve()`.
When serving your app in production, set `development: false` in `Bun.serve()`.
- Enable in-memory caching of bundled assets. Bun will bundle assets lazily on the first request to an `.html` file, and cache the result in memory until the server restarts.
- Enables `Cache-Control` headers and `ETag` headers
@@ -325,7 +242,7 @@ When adding a build step is too complicated, you can set `development: false` in
## Plugins
Bun's [bundler plugins](https://bun.com/docs/bundler/plugins) are also supported when bundling static routes.
Bun's [bundler plugins](https://bun.sh/docs/bundler/plugins) are also supported when bundling static routes.
To configure plugins for `Bun.serve`, add a `plugins` array in the `[serve.static]` section of your `bunfig.toml`.
@@ -365,7 +282,7 @@ Or in your CSS:
### Custom plugins
Any JS file or module which exports a [valid bundler plugin object](https://bun.com/docs/bundler/plugins#usage) (essentially an object with a `name` and `setup` field) can be placed inside the `plugins` array:
Any JS file or module which exports a [valid bundler plugin object](https://bun.sh/docs/bundler/plugins#usage) (essentially an object with a `name` and `setup` field) can be placed inside the `plugins` array:
```toml#bunfig.toml
[serve.static]
@@ -381,6 +298,7 @@ Note: this is currently in `bunfig.toml` to make it possible to know statically
Bun uses [`HTMLRewriter`](/docs/api/html-rewriter) to scan for `<script>` and `<link>` tags in HTML files, uses them as entrypoints for [Bun's bundler](/docs/bundler), generates an optimized bundle for the JavaScript/TypeScript/TSX/JSX and CSS files, and serves the result.
1. **`<script>` processing**
- Transpiles TypeScript, JSX, and TSX in `<script>` tags
- Bundles imported dependencies
- Generates sourcemaps for debugging
@@ -391,6 +309,7 @@ Bun uses [`HTMLRewriter`](/docs/api/html-rewriter) to scan for `<script>` and `<
```
2. **`<link>` processing**
- Processes CSS imports and `<link>` tags
- Concatenates CSS files
- Rewrites `url` and asset paths to include content-addressable hashes in URLs
@@ -400,15 +319,18 @@ Bun uses [`HTMLRewriter`](/docs/api/html-rewriter) to scan for `<script>` and `<
```
3. **`<img>` & asset processing**
- Links to assets are rewritten to include content-addressable hashes in URLs
- Small assets in CSS files are inlined into `data:` URLs, reducing the total number of HTTP requests sent over the wire
4. **Rewrite HTML**
- Combines all `<script>` tags into a single `<script>` tag with a content-addressable hash in the URL
- Combines all `<link>` tags into a single `<link>` tag with a content-addressable hash in the URL
- Outputs a new HTML file
5. **Serve**
- All the output files from the bundler are exposed as static routes, using the same mechanism internally as when you pass a `Response` object to [`static` in `Bun.serve()`](/docs/api/http#static-routes).
This works similarly to how [`Bun.build` processes HTML files](/docs/bundler/html).

View File

@@ -26,7 +26,6 @@ The bundler is a key piece of infrastructure in the JavaScript ecosystem. As a b
- **Reducing HTTP requests.** A single package in `node_modules` may consist of hundreds of files, and large applications may have dozens of such dependencies. Loading each of these files with a separate HTTP request becomes untenable very quickly, so bundlers are used to convert our application source code into a smaller number of self-contained "bundles" that can be loaded with a single request.
- **Code transforms.** Modern apps are commonly built with languages or tools like TypeScript, JSX, and CSS modules, all of which must be converted into plain JavaScript and CSS before they can be consumed by a browser. The bundler is the natural place to configure these transformations.
- **Framework features.** Frameworks rely on bundler plugins & code transformations to implement common patterns like file-system routing, client-server code co-location (think `getServerSideProps` or Remix loaders), and server components.
- **Full-stack Applications.** Bun's bundler can handle both server and client code in a single command, enabling optimized production builds and single-file executables. With build-time HTML imports, you can bundle your entire application — frontend assets and backend server — into a single deployable unit.
Let's jump into the bundler API.
@@ -147,7 +146,7 @@ $ bun build ./index.tsx --outdir ./out --watch
## Content types
Like the Bun runtime, the bundler supports an array of file types out of the box. The following table breaks down the bundler's set of standard "loaders". Refer to [Bundler > File types](https://bun.com/docs/runtime/loaders) for full documentation.
Like the Bun runtime, the bundler supports an array of file types out of the box. The following table breaks down the bundler's set of standard "loaders". Refer to [Bundler > File types](https://bun.sh/docs/runtime/loaders) for full documentation.
{% table %}
@@ -220,11 +219,11 @@ console.log(logo);
The exact behavior of the file loader is also impacted by [`naming`](#naming) and [`publicPath`](#publicpath).
{% /callout %}
Refer to the [Bundler > Loaders](https://bun.com/docs/bundler/loaders#file) page for more complete documentation on the file loader.
Refer to the [Bundler > Loaders](https://bun.sh/docs/bundler/loaders#file) page for more complete documentation on the file loader.
### Plugins
The behavior described in this table can be overridden or extended with [plugins](https://bun.com/docs/bundler/plugins). Refer to the [Bundler > Loaders](https://bun.com/docs/bundler/plugins) page for complete documentation.
The behavior described in this table can be overridden or extended with [plugins](https://bun.sh/docs/bundler/plugins). Refer to the [Bundler > Loaders](https://bun.sh/docs/bundler/plugins) page for complete documentation.
## API
@@ -325,7 +324,7 @@ Depending on the target, Bun will apply different module resolution rules and op
---
- `bun`
- For generating bundles that are intended to be run by the Bun runtime. In many cases, it isn't necessary to bundle server-side code; you can directly execute the source code without modification. However, bundling your server code can reduce startup times and improve running performance. This is the target to use for building full-stack applications with build-time HTML imports, where both server and client code are bundled together.
- For generating bundles that are intended to be run by the Bun runtime. In many cases, it isn't necessary to bundle server-side code; you can directly execute the source code without modification. However, bundling your server code can reduce startup times and improve running performance.
All bundles generated with `target: "bun"` are marked with a special `// @bun` pragma, which indicates to the Bun runtime that there's no need to re-transpile the file before execution.
@@ -484,7 +483,7 @@ n/a
{% /codetabs %}
Bun implements a universal plugin system for both Bun's runtime and bundler. Refer to the [plugin documentation](https://bun.com/docs/bundler/plugins) for complete documentation.
Bun implements a universal plugin system for both Bun's runtime and bundler. Refer to the [plugin documentation](https://bun.sh/docs/bundler/plugins) for complete documentation.
<!-- ### `manifest`
@@ -1102,7 +1101,7 @@ A prefix to be appended to any import paths in bundled code.
In many cases, generated bundles will contain no `import` statements. After all, the goal of bundling is to combine all of the code into a single file. However there are a number of cases with the generated bundles will contain `import` statements.
- **Asset imports** — When importing an unrecognized file type like `*.svg`, the bundler defers to the [`file` loader](https://bun.com/docs/bundler/loaders#file), which copies the file into `outdir` as is. The import is converted into a variable
- **Asset imports** — When importing an unrecognized file type like `*.svg`, the bundler defers to the [`file` loader](https://bun.sh/docs/bundler/loaders#file), which copies the file into `outdir` as is. The import is converted into a variable
- **External modules** — Files and modules can be marked as [`external`](#external), in which case they will not be included in the bundle. Instead, the `import` statement will be left in the final bundle.
- **Chunking**. When [`splitting`](#splitting) is enabled, the bundler may generate separate "chunk" files that represent code that is shared among multiple entrypoints.
@@ -1178,7 +1177,7 @@ $ bun build ./index.tsx --outdir ./out --define 'STRING="value"' --define "neste
### `loader`
A map of file extensions to [built-in loader names](https://bun.com/docs/bundler/loaders#built-in-loaders). This can be used to quickly customize how certain files are loaded.
A map of file extensions to [built-in loader names](https://bun.sh/docs/bundler/loaders#built-in-loaders). This can be used to quickly customize how certain files are loaded.
{% codetabs %}
@@ -1310,7 +1309,7 @@ Each artifact also contains the following properties:
---
- `loader`
- The loader was used to interpret the file. See [Bundler > Loaders](https://bun.com/docs/bundler/loaders) to see how Bun maps file extensions to the appropriate built-in loader.
- The loader was used to interpret the file. See [Bundler > Loaders](https://bun.sh/docs/bundler/loaders) to see how Bun maps file extensions to the appropriate built-in loader.
---
@@ -1394,7 +1393,7 @@ $ bun build ./cli.tsx --outfile mycli --compile
$ ./mycli
```
Refer to [Bundler > Executables](https://bun.com/docs/bundler/executables) for complete documentation.
Refer to [Bundler > Executables](https://bun.sh/docs/bundler/executables) for complete documentation.
## Logs and errors

View File

@@ -2,7 +2,7 @@ The Bun bundler implements a set of default loaders out of the box. As a rule of
`.js` `.cjs` `.mjs` `.mts` `.cts` `.ts` `.tsx` `.jsx` `.toml` `.json` `.txt` `.wasm` `.node` `.html`
Bun uses the file extension to determine which built-in _loader_ should be used to parse the file. Every loader has a name, such as `js`, `tsx`, or `json`. These names are used when building [plugins](https://bun.com/docs/bundler/plugins) that extend Bun with custom loaders.
Bun uses the file extension to determine which built-in _loader_ should be used to parse the file. Every loader has a name, such as `js`, `tsx`, or `json`. These names are used when building [plugins](https://bun.sh/docs/bundler/plugins) that extend Bun with custom loaders.
You can explicitly specify which loader to use using the 'loader' import attribute.
@@ -137,7 +137,7 @@ console.log(contents); // => "Hello, world!"
import html from "./index.html" with { type: "text" };
```
When referenced during a build, the contents are inlined into the bundle as a string.
When referenced during a build, the contents are into the bundle as a string.
```ts
var contents = `Hello, world!`;
@@ -175,7 +175,7 @@ In the bundler, `.node` files are handled using the [`file`](#file) loader.
**SQLite loader**. `with { "type": "sqlite" }` import attribute
In the runtime and bundler, SQLite databases can be directly imported. This will load the database using [`bun:sqlite`](https://bun.com/docs/api/sqlite).
In the runtime and bundler, SQLite databases can be directly imported. This will load the database using [`bun:sqlite`](https://bun.sh/docs/api/sqlite).
```ts
import db from "./my.db" with { type: "sqlite" };
@@ -192,7 +192,7 @@ You can change this behavior with the `"embed"` attribute:
import db from "./my.db" with { type: "sqlite", embed: "true" };
```
When using a [standalone executable](https://bun.com/docs/bundler/executables), the database is embedded into the single-file executable.
When using a [standalone executable](https://bun.sh/docs/bundler/executables), the database is embedded into the single-file executable.
Otherwise, the database to embed is copied into the `outdir` with a hashed filename.
@@ -262,25 +262,11 @@ Currently, the list of selectors is:
- `video[poster]`
- `video[src]`
{% callout %}
**HTML Loader Behavior in Different Contexts**
The `html` loader behaves differently depending on how it's used:
1. **Static Build:** When you run `bun build ./index.html`, Bun produces a static site with all assets bundled and hashed.
2. **Runtime:** When you run `bun run server.ts` (where `server.ts` imports an HTML file), Bun bundles assets on-the-fly during development, enabling features like hot module replacement.
3. **Full-stack Build:** When you run `bun build --target=bun server.ts` (where `server.ts` imports an HTML file), the import resolves to a manifest object that `Bun.serve` uses to efficiently serve pre-bundled assets in production.
{% /callout %}
### `sh` loader
**Bun Shell loader**. Default for `.sh` files
This loader is used to parse [Bun Shell](https://bun.com/docs/runtime/shell) scripts. It's only supported when starting Bun itself, so it's not available in the bundler or in the runtime.
This loader is used to parse [Bun Shell](https://bun.sh/docs/runtime/shell) scripts. It's only supported when starting Bun itself, so it's not available in the bundler or in the runtime.
```sh
$ bun run ./script.sh
@@ -336,7 +322,7 @@ If a value is specified for `publicPath`, the import will use value as a prefix
{% /table %}
{% callout %}
The location and file name of the copied file is determined by the value of [`naming.asset`](https://bun.com/docs/bundler#naming).
The location and file name of the copied file is determined by the value of [`naming.asset`](https://bun.sh/docs/bundler#naming).
{% /callout %}
This loader is copied into the `outdir` as-is. The name of the copied file is determined using the value of `naming.asset`.

View File

@@ -161,7 +161,7 @@ The result of `fetch` is `Promise<Response>`, so it can be directly returned.
```ts#macro.ts
export function getObject() {
return fetch("https://bun.com")
return fetch("https://bun.sh")
}
```

View File

@@ -291,7 +291,7 @@ One of the reasons why Bun's bundler is so fast is that it is written in native
However, one limitation of plugins written in JavaScript is that JavaScript itself is single-threaded.
Native plugins are written as [NAPI](https://bun.com/docs/api/node-api) modules and can be run on multiple threads. This allows native plugins to run much faster than JavaScript plugins.
Native plugins are written as [NAPI](https://bun.sh/docs/api/node-api) modules and can be run on multiple threads. This allows native plugins to run much faster than JavaScript plugins.
In addition, native plugins can skip unnecessary work such as the UTF-8 -> UTF-16 conversion needed to pass strings to JavaScript.

View File

@@ -2,7 +2,7 @@ Bun's bundler API is inspired heavily by [esbuild](https://esbuild.github.io/).
There are a few behavioral differences to note.
- **Bundling by default**. Unlike esbuild, Bun _always bundles by default_. This is why the `--bundle` flag isn't necessary in the Bun example. To transpile each file individually, use [`Bun.Transpiler`](https://bun.com/docs/api/transpiler).
- **Bundling by default**. Unlike esbuild, Bun _always bundles by default_. This is why the `--bundle` flag isn't necessary in the Bun example. To transpile each file individually, use [`Bun.Transpiler`](https://bun.sh/docs/api/transpiler).
- **It's just a bundler**. Unlike esbuild, Bun's bundler does not include a built-in development server or file watcher. It's just a bundler. The bundler is intended for use in conjunction with `Bun.serve` and other runtime APIs to achieve the same effect. As such, all options relating to HTTP/file watching are not applicable.
## Performance
@@ -65,7 +65,7 @@ In Bun's CLI, simple boolean flags like `--minify` do not accept an argument. Ot
- `--loader:.ext=loader`
- `--loader .ext:loader`
- Bun supports a different set of built-in loaders than esbuild; see [Bundler > Loaders](https://bun.com/docs/bundler/loaders) for a complete reference. The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not yet implemented.
- Bun supports a different set of built-in loaders than esbuild; see [Bundler > Loaders](https://bun.sh/docs/bundler/loaders) for a complete reference. The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not yet implemented.
The syntax for `--loader` is slightly different.
@@ -125,7 +125,7 @@ In Bun's CLI, simple boolean flags like `--minify` do not accept an argument. Ot
- `--target`
- n/a
- Not supported. Bun's bundler performs no syntactic down-leveling at this time.
- No supported. Bun's bundler performs no syntactic down-leveling at this time.
---
@@ -474,7 +474,7 @@ In Bun's CLI, simple boolean flags like `--minify` do not accept an argument. Ot
- `bundle`
- n/a
- Always `true`. Use [`Bun.Transpiler`](https://bun.com/docs/api/transpiler) to transpile without bundling.
- Always `true`. Use [`Bun.Transpiler`](https://bun.sh/docs/api/transpiler) to transpile without bundling.
---
@@ -635,7 +635,7 @@ In Bun's CLI, simple boolean flags like `--minify` do not accept an argument. Ot
- `loader`
- `loader`
- Bun supports a different set of built-in loaders than esbuild; see [Bundler > Loaders](https://bun.com/docs/bundler/loaders) for a complete reference. The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not yet implemented.
- Bun supports a different set of built-in loaders than esbuild; see [Bundler > Loaders](https://bun.sh/docs/bundler/loaders) for a complete reference. The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not yet implemented.
---
@@ -891,7 +891,7 @@ const myPlugin: BunPlugin = {
};
```
The `builder` object provides some methods for hooking into parts of the bundling process. Bun implements `onResolve` and `onLoad`; it does not yet implement the esbuild hooks `onStart`, `onEnd`, and `onDispose`, and `resolve` utilities. `initialOptions` is partially implemented, being read-only and only having a subset of esbuild's options; use [`config`](https://bun.com/docs/bundler/plugins) (same thing but with Bun's `BuildConfig` format) instead.
The `builder` object provides some methods for hooking into parts of the bundling process. Bun implements `onResolve` and `onLoad`; it does not yet implement the esbuild hooks `onStart`, `onEnd`, and `onDispose`, and `resolve` utilities. `initialOptions` is partially implemented, being read-only and only having a subset of esbuild's options; use [`config`](https://bun.sh/docs/bundler/plugins) (same thing but with Bun's `BuildConfig` format) instead.
```ts
import type { BunPlugin } from "bun";

View File

@@ -4,7 +4,7 @@
Template a new Bun project with `bun create`. This is a flexible command that can be used to create a new project from a React component, a `create-<template>` npm package, a GitHub repo, or a local template.
If you're looking to create a brand new empty project, use [`bun init`](https://bun.com/docs/cli/init).
If you're looking to create a brand new empty project, use [`bun init`](https://bun.sh/docs/cli/init).
## From a React component
@@ -30,11 +30,11 @@ $ bun create ./MyComponent.jsx # .tsx also supported
When you run `bun create <component>`, Bun:
1. Uses [Bun's JavaScript bundler](https://bun.com/docs/bundler) to analyze your module graph.
1. Uses [Bun's JavaScript bundler](https://bun.sh/docs/bundler) to analyze your module graph.
2. Collects all the dependencies needed to run the component.
3. Scans the exports of the entry point for a React component.
4. Generates a `package.json` file with the dependencies and scripts needed to run the component.
5. Installs any missing dependencies using [`bun install --only-missing`](https://bun.com/docs/cli/install).
5. Installs any missing dependencies using [`bun install --only-missing`](https://bun.sh/docs/cli/install).
6. Generates the following files:
- `${component}.html`
- `${component}.client.tsx` (entry point for the frontend)
@@ -308,12 +308,14 @@ IF remote template
1. GET `registry.npmjs.org/@bun-examples/${template}/latest` and parse it
2. GET `registry.npmjs.org/@bun-examples/${template}/-/${template}-${latestVersion}.tgz`
3. Decompress & extract `${template}-${latestVersion}.tgz` into `${destination}`
- If there are files that would overwrite, warn and exit unless `--force` is passed
IF GitHub repo
1. Download the tarball from GitHubs API
2. Decompress & extract into `${destination}`
- If there are files that would overwrite, warn and exit unless `--force` is passed
ELSE IF local template
@@ -331,6 +333,7 @@ ELSE IF local template
7. Run `${npmClient} install` unless `--no-install` is passed OR no dependencies are in package.json
8. Run any tasks defined in `"bun-create": { "postinstall" }` with the npm client
9. Run `git init; git add -A .; git commit -am "Initial Commit";`
- Rename `gitignore` to `.gitignore`. NPM automatically removes `.gitignore` files from appearing in packages.
- If there are dependencies, this runs in a separate thread concurrently while node_modules are being installed
- Using libgit2 if available was tested and performed 3x slower in microbenchmarks

View File

@@ -184,7 +184,7 @@ Peer dependencies are handled similarly to yarn. `bun install` will automaticall
## Lockfile
`bun.lock` is Buns lockfile format. See [our blogpost about the text lockfile](https://bun.com/blog/bun-lock-text-lockfile).
`bun.lock` is Buns lockfile format. See [our blogpost about the text lockfile](https://bun.sh/blog/bun-lock-text-lockfile).
Prior to Bun 1.2, the lockfile was binary and called `bun.lockb`. Old lockfiles can be upgraded to the new format by running `bun install --save-text-lockfile --frozen-lockfile --lockfile-only`, and then deleting `bun.lockb`.

View File

@@ -7,7 +7,7 @@ This works by checking the latest version of Bun in [bun-releases-for-updater](h
If for any reason you run into issues, you can also use the curl install script:
```bash
$ curl https://bun.com/install | bash
$ curl https://bun.sh/install | bash
```
It will still work when Bun is already installed.

View File

@@ -28,7 +28,7 @@ $ bun install --filter '!pkg-c'
$ bun install --filter './packages/*'
# Save as above, but exclude the root package.json
$ bun install --filter '!./' --filter './packages/*'
$ bun install --filter --filter '!./' --filter './packages/*'
```
Similarly, `bun outdated` will display outdated dependencies for all packages in the monorepo, and `--filter` can be used to restrict the command to a subset of the packages:
@@ -41,7 +41,7 @@ $ bun outdated --filter 'pkg-*'
$ bun outdated --filter './'
```
For more information on both these commands, see [`bun install`](https://bun.com/docs/cli/install) and [`bun outdated`](https://bun.com/docs/cli/outdated).
For more information on both these commands, see [`bun install`](https://bun.sh/docs/cli/install) and [`bun outdated`](https://bun.sh/docs/cli/outdated).
## Running scripts with `--filter`
@@ -73,7 +73,7 @@ Both commands will be run in parallel, and you will see a nice terminal UI showi
### Running scripts in workspaces
Filters respect your [workspace configuration](https://bun.com/docs/install/workspaces): If you have a `package.json` file that specifies which packages are part of the workspace,
Filters respect your [workspace configuration](https://bun.sh/docs/install/workspaces): If you have a `package.json` file that specifies which packages are part of the workspace,
`--filter` will be restricted to only these packages. Also, in a workspace you can use `--filter` to run scripts in packages that are located anywhere in the workspace:
```bash

View File

@@ -1,65 +0,0 @@
`bun info` displays package metadata from the npm registry.
## Usage
```bash
$ bun info react
```
This will display information about the `react` package, including its latest version, description, homepage, dependencies, and more.
## Viewing specific versions
To view information about a specific version:
```bash
$ bun info react@18.0.0
```
## Viewing specific properties
You can also query specific properties from the package metadata:
```bash
$ bun info react version
$ bun info react dependencies
$ bun info react repository.url
```
## JSON output
To get the output in JSON format, use the `--json` flag:
```bash
$ bun info react --json
```
## Alias
`bun pm view` is an alias for `bun info`:
```bash
$ bun pm view react # equivalent to: bun info react
```
## Examples
```bash
# View basic package information
$ bun info is-number
# View a specific version
$ bun info is-number@7.0.0
# View all available versions
$ bun info is-number versions
# View package dependencies
$ bun info express dependencies
# View package homepage
$ bun info lodash homepage
# Get JSON output
$ bun info react --json
```

View File

@@ -68,7 +68,7 @@ $ bun install --concurrent-scripts 5
## Workspaces
Bun supports `"workspaces"` in package.json. For complete documentation refer to [Package manager > Workspaces](https://bun.com/docs/install/workspaces).
Bun supports `"workspaces"` in package.json. For complete documentation refer to [Package manager > Workspaces](https://bun.sh/docs/install/workspaces).
```json#package.json
{
@@ -93,11 +93,11 @@ $ bun install --filter '!pkg-c'
$ bun install --filter './packages/pkg-a'
```
For more information on filtering with `bun install`, refer to [Package Manager > Filtering](https://bun.com/docs/cli/filter#bun-install-and-bun-outdated)
For more information on filtering with `bun install`, refer to [Package Manager > Filtering](https://bun.sh/docs/cli/filter#bun-install-and-bun-outdated)
## Overrides and resolutions
Bun supports npm's `"overrides"` and Yarn's `"resolutions"` in `package.json`. These are mechanisms for specifying a version range for _metadependencies_—the dependencies of your dependencies. Refer to [Package manager > Overrides and resolutions](https://bun.com/docs/install/overrides) for complete documentation.
Bun supports npm's `"overrides"` and Yarn's `"resolutions"` in `package.json`. These are mechanisms for specifying a version range for _metadependencies_—the dependencies of your dependencies. Refer to [Package manager > Overrides and resolutions](https://bun.sh/docs/install/overrides) for complete documentation.
```json-diff#package.json
{
@@ -142,7 +142,7 @@ For reproducible installs, use `--frozen-lockfile`. This will install the exact
$ bun install --frozen-lockfile
```
For more information on Bun's lockfile `bun.lock`, refer to [Package manager > Lockfile](https://bun.com/docs/install/lockfile).
For more information on Bun's lockfile `bun.lock`, refer to [Package manager > Lockfile](https://bun.sh/docs/install/lockfile).
## Omitting dependencies
@@ -168,7 +168,7 @@ $ bun install --dry-run
## Non-npm dependencies
Bun supports installing dependencies from Git, GitHub, and local or remotely-hosted tarballs. For complete documentation refer to [Package manager > Git, GitHub, and tarball dependencies](https://bun.com/docs/cli/add).
Bun supports installing dependencies from Git, GitHub, and local or remotely-hosted tarballs. For complete documentation refer to [Package manager > Git, GitHub, and tarball dependencies](https://bun.sh/docs/cli/add).
```json#package.json
{
@@ -183,30 +183,6 @@ Bun supports installing dependencies from Git, GitHub, and local or remotely-hos
}
```
## Installation strategies
Bun supports two package installation strategies that determine how dependencies are organized in `node_modules`:
### Hoisted installs (default for single projects)
The traditional npm/Yarn approach that flattens dependencies into a shared `node_modules` directory:
```bash
$ bun install --linker hoisted
```
### Isolated installs
A pnpm-like approach that creates strict dependency isolation to prevent phantom dependencies:
```bash
$ bun install --linker isolated
```
Isolated installs create a central package store in `node_modules/.bun/` with symlinks in the top-level `node_modules`. This ensures packages can only access their declared dependencies.
For complete documentation on isolated installs, refer to [Package manager > Isolated installs](https://bun.com/docs/install/isolated).
## Configuration
The default behavior of `bun install` can be configured in `bunfig.toml`. The default values are shown below.
@@ -237,15 +213,11 @@ dryRun = false
# equivalent to `--concurrent-scripts` flag
concurrentScripts = 16 # (cpu count or GOMAXPROCS) x2
# installation strategy: "hoisted" or "isolated"
# default: "hoisted"
linker = "hoisted"
```
## CI/CD
Use the official [`oven-sh/setup-bun`](https://github.com/oven-sh/setup-bun) action to install `bun` in a GitHub Actions pipeline:
Looking to speed up your CI? Use the official [`oven-sh/setup-bun`](https://github.com/oven-sh/setup-bun) action to install `bun` in a GitHub Actions pipeline.
```yaml#.github/workflows/release.yml
name: bun-types
@@ -264,31 +236,4 @@ jobs:
run: bun run build
```
For CI/CD environments that want to enforce reproducible builds, use `bun ci` to fail the build if the package.json is out of sync with the lockfile:
```bash
$ bun ci
```
This is equivalent to `bun install --frozen-lockfile`. It installs exact versions from `bun.lock` and fails if `package.json` doesn't match the lockfile. To use `bun ci` or `bun install --frozen-lockfile`, you must commit `bun.lock` to version control.
And instead of running `bun install`, run `bun ci`.
```yaml#.github/workflows/release.yml
name: bun-types
jobs:
build:
name: build-app
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Install bun
uses: oven-sh/setup-bun@v2
- name: Install dependencies
run: bun ci
- name: Build app
run: bun run build
```
{% bunCLIUsage command="install" /%}

View File

@@ -1,6 +1,6 @@
An alias for `bun patch --commit` to maintain compatibility with pnpm.
To get started with patch, first prepare the package for patching with [`bun patch <pkg>`](https://bun.com/docs/install/patch).
To get started with patch, first prepare the package for patching with [`bun patch <pkg>`](https://bun.sh/docs/install/patch).
### `--patches-dir`

View File

@@ -8,70 +8,15 @@ To create a tarball of the current workspace:
$ bun pm pack
```
This command creates a `.tgz` file containing all files that would be published to npm, following the same rules as `npm pack`.
Options for the `pack` command:
## Examples
Basic usage:
```bash
$ bun pm pack
# Creates my-package-1.0.0.tgz in current directory
```
Quiet mode for scripting:
```bash
$ TARBALL=$(bun pm pack --quiet)
$ echo "Created: $TARBALL"
# Output: Created: my-package-1.0.0.tgz
```
Custom destination:
```bash
$ bun pm pack --destination ./dist
# Saves tarball in ./dist/ directory
```
## Options
- `--dry-run`: Perform all tasks except writing the tarball to disk. Shows what would be included.
- `--destination <dir>`: Specify the directory where the tarball will be saved.
- `--filename <name>`: Specify an exact file name for the tarball to be saved at.
- `--dry-run`: Perform all tasks except writing the tarball to disk.
- `--destination`: Specify the directory where the tarball will be saved.
- `--filename`: Specify an exact file name for the tarball to be saved at.
- `--ignore-scripts`: Skip running pre/postpack and prepare scripts.
- `--gzip-level <0-9>`: Set a custom compression level for gzip, ranging from 0 to 9 (default is 9).
- `--quiet`: Only output the tarball filename, suppressing verbose output. Ideal for scripts and automation.
- `--gzip-level`: Set a custom compression level for gzip, ranging from 0 to 9 (default is 9).
> **Note:** `--filename` and `--destination` cannot be used at the same time.
## Output Modes
**Default output:**
```bash
$ bun pm pack
bun pack v1.2.19
packed 131B package.json
packed 40B index.js
my-package-1.0.0.tgz
Total files: 2
Shasum: f2451d6eb1e818f500a791d9aace80b394258a90
Unpacked size: 171B
Packed size: 249B
```
**Quiet output:**
```bash
$ bun pm pack --quiet
my-package-1.0.0.tgz
```
The `--quiet` flag is particularly useful for automation workflows where you need to capture the generated tarball filename for further processing.
> Note `--filename` and `--destination` cannot be used at the same time
## bin
@@ -206,80 +151,3 @@ $ bun pm default-trusted
```
see the current list on GitHub [here](https://github.com/oven-sh/bun/blob/main/src/install/default-trusted-dependencies.txt)
## version
To display current package version and help:
```bash
$ bun pm version
bun pm version v$BUN_LATEST_VERSION (ca7428e9)
Current package version: v1.0.0
Increment:
patch 1.0.0 → 1.0.1
minor 1.0.0 → 1.1.0
major 1.0.0 → 2.0.0
prerelease 1.0.0 → 1.0.1-0
prepatch 1.0.0 → 1.0.1-0
preminor 1.0.0 → 1.1.0-0
premajor 1.0.0 → 2.0.0-0
from-git Use version from latest git tag
1.2.3 Set specific version
Options:
--no-git-tag-version Skip git operations
--allow-same-version Prevents throwing error if version is the same
--message=<val>, -m Custom commit message, use %s for version substitution
--preid=<val> Prerelease identifier (i.e beta → 1.0.1-beta.0)
--force, -f Bypass dirty git history check
Examples:
$ bun pm version patch
$ bun pm version 1.2.3 --no-git-tag-version
$ bun pm version prerelease --preid beta --message "Release beta: %s"
```
To bump the version in `package.json`:
```bash
$ bun pm version patch
v1.0.1
```
Supports `patch`, `minor`, `major`, `premajor`, `preminor`, `prepatch`, `prerelease`, `from-git`, or specific versions like `1.2.3`. By default creates git commit and tag unless `--no-git-tag-version` was used to skip.
## pkg
Manage `package.json` data with get, set, delete, and fix operations.
All commands support dot and bracket notation:
```bash
scripts.build # dot notation
contributors[0] # array access
workspaces.0 # dot with numeric index
scripts[test:watch] # bracket for special chars
```
Examples:
```bash
# set
$ bun pm pkg get name # single property
$ bun pm pkg get name version # multiple properties
$ bun pm pkg get # entire package.json
$ bun pm pkg get scripts.build # nested property
# set
$ bun pm pkg set name="my-package" # simple property
$ bun pm pkg set scripts.test="jest" version=2.0.0 # multiple properties
$ bun pm pkg set {"private":"true"} --json # JSON values with --json flag
# delete
$ bun pm pkg delete description # single property
$ bun pm pkg delete scripts.test contributors[0] # multiple/nested
# fix
$ bun pm pkg fix # auto-fix common issues
```

View File

@@ -106,7 +106,7 @@ $ bun run clean
Done.
```
Bun executes the script command in a subshell. On Linux & macOS, it checks for the following shells in order, using the first one it finds: `bash`, `sh`, `zsh`. On windows, it uses [bun shell](https://bun.com/docs/runtime/shell) to support bash-like syntax and many common commands.
Bun executes the script command in a subshell. On Linux & macOS, it checks for the following shells in order, using the first one it finds: `bash`, `sh`, `zsh`. On windows, it uses [bun shell](https://bun.sh/docs/runtime/shell) to support bash-like syntax and many common commands.
{% callout %}
⚡️ The startup time for `npm run` on Linux is roughly 170ms; with Bun it is `6ms`.
@@ -164,7 +164,7 @@ bun run --filter 'ba*' <script>
will execute `<script>` in both `bar` and `baz`, but not in `foo`.
Find more details in the docs page for [filter](https://bun.com/docs/cli/filter#running-scripts-with-filter).
Find more details in the docs page for [filter](https://bun.sh/docs/cli/filter#running-scripts-with-filter).
## `bun run -` to pipe code from stdin
@@ -185,23 +185,6 @@ This is TypeScript!
For convenience, all code is treated as TypeScript with JSX support when using `bun run -`.
## `bun run --console-depth`
Control the depth of object inspection in console output with the `--console-depth` flag.
```bash
$ bun --console-depth 5 run index.tsx
```
This sets how deeply nested objects are displayed in `console.log()` output. The default depth is `2`. Higher values show more nested properties but may produce verbose output for complex objects.
```js
const nested = { a: { b: { c: { d: "deep" } } } };
console.log(nested);
// With --console-depth 2 (default): { a: { b: [Object] } }
// With --console-depth 4: { a: { b: { c: { d: 'deep' } } } }
```
## `bun run --smol`
In memory-constrained environments, use the `--smol` flag to reduce memory usage at a cost to performance.

View File

@@ -17,7 +17,7 @@ Bun aims for compatibility with Jest, but not everything is implemented. To trac
$ bun test
```
Tests are written in JavaScript or TypeScript with a Jest-like API. Refer to [Writing tests](https://bun.com/docs/test/writing) for full documentation.
Tests are written in JavaScript or TypeScript with a Jest-like API. Refer to [Writing tests](https://bun.sh/docs/test/writing) for full documentation.
```ts#math.test.ts
import { expect, test } from "bun:test";
@@ -53,7 +53,7 @@ To run a specific file in the test runner, make sure the path starts with `./` o
$ bun test ./test/specific-file.test.ts
```
The test runner runs all tests in a single process. It loads all `--preload` scripts (see [Lifecycle](https://bun.com/docs/test/lifecycle) for details), then runs all tests. If a test fails, the test runner will exit with a non-zero exit code.
The test runner runs all tests in a single process. It loads all `--preload` scripts (see [Lifecycle](https://bun.sh/docs/test/lifecycle) for details), then runs all tests. If a test fails, the test runner will exit with a non-zero exit code.
## CI/CD integration
@@ -154,7 +154,7 @@ These hooks can be defined inside test files, or in a separate file that is prel
$ bun test --preload ./setup.ts
```
See [Test > Lifecycle](https://bun.com/docs/test/lifecycle) for complete documentation.
See [Test > Lifecycle](https://bun.sh/docs/test/lifecycle) for complete documentation.
## Mocks
@@ -182,7 +182,7 @@ Alternatively, you can use `jest.fn()`, it behaves identically.
+ const random = jest.fn(() => Math.random());
```
See [Test > Mocks](https://bun.com/docs/test/mocks) for complete documentation.
See [Test > Mocks](https://bun.sh/docs/test/mocks) for complete documentation.
## Snapshot testing
@@ -203,7 +203,7 @@ To update snapshots, use the `--update-snapshots` flag.
$ bun test --update-snapshots
```
See [Test > Snapshots](https://bun.com/docs/test/snapshots) for complete documentation.
See [Test > Snapshots](https://bun.sh/docs/test/snapshots) for complete documentation.
## UI & DOM testing
@@ -213,7 +213,7 @@ Bun is compatible with popular UI testing libraries:
- [DOM Testing Library](https://testing-library.com/docs/dom-testing-library/intro/)
- [React Testing Library](https://testing-library.com/docs/react-testing-library/intro)
See [Test > DOM Testing](https://bun.com/docs/test/dom) for complete documentation.
See [Test > DOM Testing](https://bun.sh/docs/test/dom) for complete documentation.
## Performance
@@ -248,33 +248,4 @@ $ bun test foo
Any test file in the directory with an _absolute path_ that contains one of the targets will run. Glob patterns are not yet supported. -->
## AI Agent Integration
When using Bun's test runner with AI coding assistants, you can enable quieter output to improve readability and reduce context noise. This feature minimizes test output verbosity while preserving essential failure information.
### Environment Variables
Set any of the following environment variables to enable AI-friendly output:
- `CLAUDECODE=1` - For Claude Code
- `REPL_ID=1` - For Replit
- `AGENT=1` - Generic AI agent flag
### Behavior
When an AI agent environment is detected:
- Only test failures are displayed in detail
- Passing, skipped, and todo test indicators are hidden
- Summary statistics remain intact
```bash
# Example: Enable quiet output for Claude Code
$ CLAUDECODE=1 bun test
# Still shows failures and summary, but hides verbose passing test output
```
This feature is particularly useful in AI-assisted development workflows where reduced output verbosity improves context efficiency while maintaining visibility into test failures.
{% bunCLIUsage command="test" /%}

View File

@@ -10,86 +10,6 @@ To update a specific dependency to the latest version:
$ bun update [package]
```
## `--interactive`
For a more controlled update experience, use the `--interactive` flag to select which packages to update:
```sh
$ bun update --interactive
$ bun update -i
```
This launches an interactive terminal interface that shows all outdated packages with their current and target versions. You can then select which packages to update.
### Interactive Interface
The interface displays packages grouped by dependency type:
```
? Select packages to update - Space to toggle, Enter to confirm, a to select all, n to select none, i to invert, l to toggle latest
dependencies Current Target Latest
□ react 17.0.2 18.2.0 18.3.1
□ lodash 4.17.20 4.17.21 4.17.21
devDependencies Current Target Latest
□ typescript 4.8.0 5.0.0 5.3.3
□ @types/node 16.11.7 18.0.0 20.11.5
optionalDependencies Current Target Latest
□ some-optional-package 1.0.0 1.1.0 1.2.0
```
**Sections:**
- Packages are grouped under section headers: `dependencies`, `devDependencies`, `peerDependencies`, `optionalDependencies`
- Each section shows column headers aligned with the package data
**Columns:**
- **Package**: Package name (may have suffix like ` dev`, ` peer`, ` optional` for clarity)
- **Current**: Currently installed version
- **Target**: Version that would be installed (respects semver constraints)
- **Latest**: Latest available version
### Keyboard Controls
**Selection:**
- **Space**: Toggle package selection
- **Enter**: Confirm selections and update
- **a/A**: Select all packages
- **n/N**: Select none
- **i/I**: Invert selection
**Navigation:**
- **↑/↓ Arrow keys** or **j/k**: Move cursor
- **l/L**: Toggle between target and latest version for current package
**Exit:**
- **Ctrl+C** or **Ctrl+D**: Cancel without updating
### Visual Indicators
- **☑** Selected packages (will be updated)
- **□** Unselected packages
- **>** Current cursor position
- **Colors**: Red (major), yellow (minor), green (patch) version changes
- **Underlined**: Currently selected update target
### Package Grouping
Packages are organized in sections by dependency type:
- **dependencies** - Regular runtime dependencies
- **devDependencies** - Development dependencies
- **peerDependencies** - Peer dependencies
- **optionalDependencies** - Optional dependencies
Within each section, individual packages may have additional suffixes (` dev`, ` peer`, ` optional`) for extra clarity.
## `--latest`
By default, `bun update` will update to the latest version of a dependency that satisfies the version range specified in your `package.json`.
@@ -100,8 +20,6 @@ To update to the latest version, regardless of if it's compatible with the curre
$ bun update --latest
```
In interactive mode, you can toggle individual packages between their target version (respecting semver) and latest version using the **l** key.
For example, with the following `package.json`:
```json

View File

@@ -1,67 +0,0 @@
The `bun why` command explains why a package is installed in your project by showing the dependency chain that led to its installation.
## Usage
```bash
$ bun why <package>
```
## Arguments
- `<package>`: The name of the package to explain. Supports glob patterns like `@org/*` or `*-lodash`.
## Options
- `--top`: Show only the top-level dependencies instead of the complete dependency tree.
- `--depth <number>`: Maximum depth of the dependency tree to display.
## Examples
Check why a specific package is installed:
```bash
$ bun why react
react@18.2.0
└─ my-app@1.0.0 (requires ^18.0.0)
```
Check why all packages with a specific pattern are installed:
```bash
$ bun why "@types/*"
@types/react@18.2.15
└─ dev my-app@1.0.0 (requires ^18.0.0)
@types/react-dom@18.2.7
└─ dev my-app@1.0.0 (requires ^18.0.0)
```
Show only top-level dependencies:
```bash
$ bun why express --top
express@4.18.2
└─ my-app@1.0.0 (requires ^4.18.2)
```
Limit the dependency tree depth:
```bash
$ bun why express --depth 2
express@4.18.2
└─ express-pollyfill@1.20.1 (requires ^4.18.2)
└─ body-parser@1.20.1 (requires ^1.20.1)
└─ accepts@1.3.8 (requires ^1.3.8)
└─ (deeper dependencies hidden)
```
## Understanding the Output
The output shows:
- The package name and version being queried
- The dependency chain that led to its installation
- The type of dependency (dev, peer, optional, or production)
- The version requirement specified in each package's dependencies
For nested dependencies, the command shows the complete dependency tree by default, with indentation indicating the relationship hierarchy.

Some files were not shown because too many files have changed in this diff Show More