This PR addresses several issues opened for the docs:
- Add callout for SQLite caching behavior between prepare() and query()
- Fix SQLite types and fix deprecated exec to run
- Fix Secrets API example
- Update SolidStart guide
- Add bun upgrade guide
- Prefer `process.versions.bun` over `typeof Bun` for detection
- Document complete `bunx` flags
- Improve Nitro preset documentation for Nuxt
Fixes#23165, #24424, #24294, #25175, #18433, #16804, #22967, #22527,
#10560, #14744
## Summary
- Added null check for `sourceOrigin` before accessing its URL in
`jest.mock()`
- When `callerSourceOrigin()` returns null (e.g., when called with
invalid arguments), the code now safely returns early instead of
crashing
## Test plan
- [x] Added regression test `test/regression/issue/ENG-24434.test.ts`
- [x] `bun bd test test/regression/issue/ENG-24434.test.ts` passes
Fixes ENG-24434
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Fix typo where `GetConsoleOutputCP()` was called twice instead of
calling `GetConsoleCP()` for the input codepage
- Add missing `GetConsoleCP()` extern declaration in windows.zig
The code was saving the output codepage twice, meaning the input
codepage was never properly saved and thus couldn't be correctly
restored.
## Note
This fix corrects a bug in the codepage save/restore logic, but **may
not fully resolve the garbled text issue** in #25151. The garbled text
problem occurs when `bunx` (without `--bun`) runs a package via Node.js,
and that package tries to spawn `bun`. The error message from cmd.exe
gets garbled on non-English Windows systems.
Further investigation may be needed to determine if additional codepage
handling is required when spawning processes.
Related to #25151🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
Fixes `TLSSocket.isSessionReused()` to use BoringSSL's
`SSL_session_reused()` API instead of incorrectly checking if a session
was set.
The previous implementation returned `!!this[ksession]` which would
return `true` if `setSession()` was called, even if the session wasn't
actually reused by the SSL layer. This fix correctly uses the native SSL
API like Node.js does.
## Changes
- Added native `isSessionReused` function in Zig that calls
`SSL_session_reused()`
- Updated `TLSSocket.prototype.isSessionReused` to use the native
implementation
- Added regression tests
## Test plan
- [x] `bun bd test test/regression/issue/25190.test.ts` passes
- [x] `bun bd test test/js/node/tls/node-tls-connect.test.ts` passes
Fixes#25190🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Fixes `assert.deepStrictEqual()` to properly compare Number and
Boolean wrapper objects
- Previously, `new Number(1)` and `new Number(2)` were incorrectly
considered equal because they have no enumerable properties
- Now correctly extracts and compares internal values using
`JSC::sameValue()`, then falls through to check own properties
## Test plan
- [x] Run `bun bd test test/regression/issue/24045.test.ts` - all 6
tests pass
- [x] Verify tests fail with system Bun (`USE_SYSTEM_BUN=1`) to confirm
fix validity
- [x] Verified behavior matches Node.js exactly (see table below)
## Node.js Compatibility
| Test Case | Node.js | Bun |
|-----------|---------|-----|
| Different Number values (`new Number(1)` vs `new Number(2)`) | throws
| throws |
| Same Number values (`new Number(1)` vs `new Number(1)`) | equal |
equal |
| 0 vs -0 (`new Number(0)` vs `new Number(-0)`) | throws | throws |
| NaN equals NaN (`new Number(NaN)` vs `new Number(NaN)`) | equal |
equal |
| Different Boolean values (`new Boolean(true)` vs `new Boolean(false)`)
| throws | throws |
| Same Boolean values | equal | equal |
| Number wrapper vs primitive (`new Number(1)` vs `1`) | throws | throws
|
| Number vs Boolean wrapper | throws | throws |
| Same value, different own properties | throws | throws |
| Same value, same own properties | equal | equal |
| Different own property values | throws | throws |
## Example
Before (bug):
```javascript
assert.deepStrictEqual(new Number(1), new Number(2)); // passes incorrectly
```
After (fixed):
```javascript
assert.deepStrictEqual(new Number(1), new Number(2)); // throws AssertionError
```
Closes#24045🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
Ensures `ptr` is either a number or heap big int before converting to a
number.
also fixes ENG-24039
### How did you verify your code works?
Added a test
### What does this PR do?
Fixes checking for exceptions when creating empty or used readable
streams
also fixes ENG-24038
### How did you verify your code works?
Added a test for creating empty streams
## Summary
- Implements the `%j` format specifier for `console.log` and related
console methods
- `%j` outputs the JSON stringified representation of the value
- Previously, `%j` was not recognized and was left as literal text in
the output
## Test plan
- [x] Run `bun bd test test/regression/issue/24234.test.ts` - all 5
tests pass
- [x] Verify tests fail with system Bun (`USE_SYSTEM_BUN=1`) to confirm
fix validity
- [x] Manual verification: `console.log('%j', {foo: 'bar'})` outputs
`{"foo":"bar"}`
## Example
Before (bug):
```
$ bun -e "console.log('%j %s', {foo: 'bar'}, 'hello')"
%j [object Object] hello
```
After (fixed):
```
$ bun -e "console.log('%j %s', {foo: 'bar'}, 'hello')"
{"foo":"bar"} hello
```
Closes#24234🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Add proper bounds checking for encoding operations that produce larger
output than input
- Handle allocation failures gracefully by returning appropriate errors
- Add defensive checks in string initialization functions
## Test plan
- Added test case for encoding operations with large buffers
- Verified existing buffer tests still pass
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Implements the [URLPattern Web
API](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern) based
on WebKit's implementation. URLPattern provides declarative pattern
matching for URLs, similar to how regular expressions work for strings.
### Features
- **Constructor**: Create patterns from strings or `URLPatternInit`
dictionaries
- **`test()`**: Check if a URL matches the pattern (returns boolean)
- **`exec()`**: Extract matched groups from a URL (returns
`URLPatternResult` or null)
- **Pattern properties**: `protocol`, `username`, `password`,
`hostname`, `port`, `pathname`, `search`, `hash`
- **`hasRegExpGroups`**: Detect if the pattern uses custom regular
expressions
### Example Usage
```js
// Match URLs with a user ID parameter
const pattern = new URLPattern({ pathname: '/users/:id' });
pattern.test('https://example.com/users/123'); // true
pattern.test('https://example.com/posts/456'); // false
const result = pattern.exec('https://example.com/users/123');
console.log(result.pathname.groups.id); // "123"
// Wildcard matching
const filesPattern = new URLPattern({ pathname: '/files/*' });
const match = filesPattern.exec('https://example.com/files/image.png');
console.log(match.pathname.groups[0]); // "image.png"
```
## Implementation Notes
- Adapted from WebKit's URLPattern implementation
- Modified JS bindings to work with Bun's infrastructure (simpler
`convertDictionary` patterns, WTF::Variant handling)
- Added IsoSubspaces for proper GC integration
## Test Plan
- [x] 408 tests from Web Platform Tests pass
- [x] Tests fail with system Bun (URLPattern not defined), pass with
debug build
- [x] Manual testing of basic functionality
Fixes https://github.com/oven-sh/bun/issues/2286🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
# What does this PR do?
Nyaa~ This PR fixes a small mistake in the documentation where the code
block for a React component test example was using the wrong filename!
(;ω;)💦
It was previously labeled as `matchers.d.ts`, but it should be something
like `myComponent.test.tsx` to properly reflect a test file for a React
component using `@testing-library/react`. 🧁✨
This makes the example clearer and more accurate for developers using
Bun to test their React components~! 💻🌸💕
# How did you verify your code works?
It's just docs, one single line 🥺
Pwease review and merge it when you can, senpai~~! UwU 🌈🫧
## Summary
- Add documentation for the `env` option that inlines `process.env.*`
values in frontend code when bundling HTML files
- Document runtime configuration via `bunfig.toml` `[serve.static]`
section for `bun ./index.html`
- Document production build configuration via CLI (`--env=PUBLIC_*`) and
`Bun.build` API (`env: "PUBLIC_*"`)
- Explain prefix filtering to avoid exposing sensitive environment
variables
## Test plan
- [x] Verify documentation renders correctly in local preview
- [x] Cross-reference with existing `env` documentation in
bundler/index.mdx
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Michael H <git@riskymh.dev>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
- Fix `bun publish --help` showing incorrect `--dry-run` description
("Don't install anything" → "Perform a dry run without making changes")
- The `--dry-run` flag is in a shared params array used by multiple
commands, so the new generic message works for all of them
Fixes#24806
## Test plan
- [x] Verify `bun publish --help` shows "Perform a dry run without
making changes" for --dry-run
- [x] Regression test added that validates the correct help text is
shown
- [x] Test passes with debug build, fails with system bun (validating it
tests the right thing)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
- Make `Http2Server.setTimeout()` and `Http2SecureServer.setTimeout()`
return `this` to enable method chaining
- Matches Node.js behavior where `server.setTimeout(1000).listen()`
works
Fixes#24924
## Test plan
- [x] Test that `Http2Server.setTimeout()` returns server instance
- [x] Test that `Http2SecureServer.setTimeout()` returns server instance
- [x] Test method chaining works (e.g.,
`server.setTimeout(1000).close()`)
- [x] Tests pass with debug build, fail with system bun
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
- Adds stricter validation for chunk boundaries in the HTTP chunked
transfer encoding parser
- Ensures conformance with RFC 9112 requirements for chunk formatting
- Adds additional test coverage for chunked encoding edge cases
## Test plan
- Added new tests in `test/js/bun/http/request-smuggling.test.ts`
- All existing HTTP tests pass
- `bun bd test test/js/bun/http/request-smuggling.test.ts` passes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Extends `fetch()` proxy option to accept an object format: `proxy: {
url: string, headers?: Headers }`
- Allows sending custom headers to the proxy server (useful for proxy
authentication, custom routing headers, etc.)
- Headers are sent in CONNECT requests (for HTTPS targets) and direct
proxy requests (for HTTP targets)
- User-provided `Proxy-Authorization` header overrides auto-generated
credentials from URL
## Usage
```typescript
// Old format (still works)
fetch(url, { proxy: "http://proxy.example.com:8080" });
// New object format with headers
fetch(url, {
proxy: {
url: "http://proxy.example.com:8080",
headers: {
"Proxy-Authorization": "Bearer token",
"X-Custom-Proxy-Header": "value"
}
}
});
```
## Test plan
- [x] Test proxy object with url string works same as string proxy
- [x] Test proxy object with headers sends headers to proxy (HTTP
target)
- [x] Test proxy object with headers sends headers in CONNECT request
(HTTPS target)
- [x] Test proxy object with Headers instance
- [x] Test proxy object with empty headers
- [x] Test proxy object with undefined headers
- [x] Test user-provided Proxy-Authorization overrides URL credentials
- [x] All existing proxy tests pass (25 total)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Fix crash in `FormData.from()` when called with very large ArrayBuffer
input
- Add length check in C++ `toString` function against both Bun's
synthetic limit and WebKit's `String::MaxLength`
- For UTF-8 tagged strings, use simdutf to calculate actual UTF-16
length only when byte length exceeds the limit
## Root Cause
When `FormData.from()` was called with a very large ArrayBuffer (e.g.,
`new Uint32Array(913148244)` = ~3.6GB), the code would crash with:
```
ASSERTION FAILED: data.size() <= MaxLength
vendor/WebKit/Source/WTF/wtf/text/StringImpl.h(886)
```
The `toString()` function in `helpers.h` was only checking against
`Bun__stringSyntheticAllocationLimit` (which defaults to ~4GB), but not
against WebKit's `String::MaxLength` (INT32_MAX, ~2GB). When the input
exceeded `String::MaxLength`, `createWithoutCopying()` would fail with
an assertion.
## Changes
1. **helpers.h**: Added `|| str.len > WTF::String::MaxLength` checks to
all three code paths in `toString()`:
- UTF-8 tagged pointer path (with simdutf length calculation only when
needed)
- External pointer path
- Non-copying creation path
2. **url.zig**: Reverted the incorrect Zig-side check (UTF-8 byte length
!= UTF-16 character length)
## Test plan
- [x] Added test that verifies FormData.from with oversized input
doesn't crash
- [x] Verified original crash case now returns empty FormData instead of
crashing:
```js
const v3 = new Uint32Array(913148244);
FormData.from(v3); // No longer crashes
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
- Fix assertion failure in `Bun.mmap` when `offset` or `size` options
are non-numeric values
- Add validation to reject negative `offset`/`size` with clear error
messages
Minimal reproduction: `Bun.mmap("", { offset: null });`
## Root Cause
`Bun.mmap` was calling `toInt64()` directly on the `offset` and `size`
options without validating they are numbers first. `toInt64()` has an
assertion that the value must be a number or BigInt, which fails when
non-numeric values like `null` or functions are passed.
## Test plan
- [x] Added tests for negative offset/size rejection
- [x] Added tests for non-number inputs (null, undefined)
- [x] `bun bd test test/js/bun/util/mmap.test.js` passes
Closes ENG-22413
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Fix debug assertion failure in `JSWrappingFunction` when
`expect.extend()` is called with objects containing non-`JSFunction`
callables
- The crash occurred because `jsCast<JSFunction*>` was used, which
asserts the value inherits from `JSFunction`, but callable class
constructors (like `Expect`) inherit from `InternalFunction` instead
## Changes
- Change `JSWrappingFunction` to store `JSObject*` instead of
`JSFunction*`
- Use `jsDynamicCast` instead of `jsCast` in `getWrappedFunction`
- Use `getObject()` instead of `jsCast` in `create()`
## Reproduction
```js
const jest = Bun.jest();
jest.expect.extend(jest);
```
Before fix (debug build):
```
ASSERTION FAILED: !from || from->JSCell::inherits(std::remove_pointer<To>::type::info())
JSCast.h(40) : To JSC::jsCast(From *) [To = JSC::JSFunction *, From = JSC::JSCell]
```
After fix: Properly throws `TypeError: expect.extend: 'jest' is not a
valid matcher`
## Test plan
- [x] Added regression test
`test/regression/issue/fuzzer-ENG-22942.test.ts`
- [x] Existing `expect-extend.test.js` tests pass (27 tests)
- [x] Build succeeds
Fixes ENG-22942
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Fixes#23292
`fs.access()` and `fs.accessSync()` threw EUNKNOWN (-134) when checking
named pipes on Windows (paths like `\.\pipe\name`), but Node.js worked
fine.
**Repro:**
```ts
// Server creates pipe at \.\pipe\bun-test
import net from 'net';
const server = net.createServer();
server.listen('\\.\pipe\bun-test');
// Client tries to check if pipe exists
import fs from 'fs';
fs.accessSync('\\.\pipe\bun-test', fs.constants.F_OK);
// Error: EUNKNOWN: unknown error, access '\.\pipe\bun-test'
```
## Root Cause
The `osPathKernel32` function normalizes paths before passing to Windows
APIs. The normalization logic treats a single `.` as a "current
directory" component and removes it, so `\.\pipe\name` incorrectly
became `\pipe\name` - an invalid path.
## Solution
Detect Windows device paths (starting with `\.\` or `\?\`) and skip
normalization for these special paths, preserving the device prefix.
## Test Plan
- [x] Added regression test `test/regression/issue/23292.test.ts`
- [x] Test fails with system bun (v1.3.3): 3 failures (EUNKNOWN)
- [x] Test passes with fix: 4 pass
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
- Add `cpu_profile` and `heap_snapshot` counters to `Analytics.Features`
- Export `heap_snapshot` to C++ as `Bun__Feature__heap_snapshot`
- Increment `cpu_profile` when `--cpu-prof` flag is used
- Increment `heap_snapshot` in all heap snapshot creation locations:
- `Bun.generateHeapSnapshot()`
- `bun:jsc` `generateHeapSnapshotForDebugging()`
- `console.takeHeapSnapshot()`
- Internal `JSC__JSGlobalObject__generateHeapSnapshot()`
## Test plan
- [x] Build succeeds
- [x] Heap snapshot generation works
- [x] CPU profiling works with `--cpu-prof`
- [x] Existing tests pass: `test/js/bun/util/v8-heap-snapshot.test.ts`
- [x] Existing tests pass: `test/cli/run/cpu-prof.test.ts`
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Added `http_client_proxy` counter to `analytics.Features` struct
- Incremented counter in `ProxyTunnel.onOpen()` when proxy tunnel
connection opens successfully
This allows tracking HTTP client proxy usage in analytics/crash reports
alongside other features like `fetch`, `WebSocket`, `http_server`, etc.
## Test plan
- [x] Build completes successfully (`bun bd`)
- [x] Existing proxy tests pass (`bun bd test
test/js/bun/http/proxy.test.ts`)
- [x] Counter is properly integrated into the analytics framework
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Fixes a crash (ENG-22243) where calling class constructors marked with
`call: false` would create invalid instances instead of throwing an
error.
## Root Cause
When a class definition has `call: false` (like `Bun.RedisClient`), the
code generator was still allowing the constructor to be invoked without
`new`. This created invalid instances that caused a buffer overflow
during garbage collection.
## The Fix
Modified `src/codegen/generate-classes.ts` to properly check the `call`
property:
- When `call: false`: throws `TypeError: Class constructor X cannot be
invoked without 'new'`
- When `call: true`: behaves as before, allowing construction without
`new`
## Test Plan
- [x] Added regression test in `test/regression/issue/22243.test.ts`
- [x] Test fails with system bun (has the bug)
- [x] Test passes with fixed build
- [x] Verified `Bun.RedisClient()` now throws proper error
- [x] Verified `new Bun.RedisClient()` still works
## Before
```bash
$ bun -e "Bun.RedisClient()"
# Creates invalid instance, no error
```
## After
```bash
$ bun -e "Bun.RedisClient()"
TypeError: Class constructor RedisClient cannot be invoked without 'new'
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
- Bumps some packages
- Does some _best practices_ in certain areas to minimize Aikido noise.
### How did you verify your code works?
CI.
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
- Fix `spyOn` crash when using indexed property keys (e.g., `spyOn(arr,
0)`)
## Test plan
- [x] Added tests for `spyOn` with numeric indexed properties
- [x] Added tests for `spyOn` with string indexed properties (e.g.,
`"0"`)
- [x] All existing `spyOn` tests pass
- [x] Full `mock-fn.test.js` test suite passes
Fixes ENG-21973
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Fix assertion failure when `Bun.indexOfLine` is called with a
non-number offset argument
- Changed from `.to(u32)` to `.coerce(i32, globalThis)` for proper
JavaScript type coercion
## Test plan
- [x] Added regression test in `test/js/bun/util/index-of-line.test.ts`
- [x] `bun bd test test/js/bun/util/index-of-line.test.ts` passes
Closes ENG-21997
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
- Fix off-by-one error in `preprocessUpdateRequests` where the bounds
check used `>` instead of `>=` when validating package IDs from the
resolution buffer
- When `old_resolution == packages.len`, the check `> packages.len`
passes but `resolutions_of_yore[old_resolution]` is out of bounds since
valid indices are `0` to `packages.len-1`
- This causes an internal assertion failure during `bun install` with
update requests
## The Bug
```zig
// BEFORE (buggy) - at lockfile.zig:484 and :522
if (old_resolution > old.packages.len) continue;
const res = resolutions_of_yore[old_resolution]; // OOB when old_resolution == packages.len
// AFTER (fixed)
if (old_resolution >= old.packages.len) continue;
const res = resolutions_of_yore[old_resolution]; // Now safe
```
## Crash Report
From
[bun.report](https://bun.report/1.3.3/wi1274e01cAggkggB+rt/F+pvBiw3rDqul/Doyi4Emzi5Ewj44FuvbgjMog00yDCYKERNEL32.DLLut0LCSntdll.dll4zijBA0eNrzzCtJLcpLzFFILC5OLSrJzM9TSEvMzCktSgUAiSkKPg/view):
```
panic: Internal assertion failure
- lockfile.zig:523: preprocessUpdateRequests
- install_with_manager.zig:605: installWithManager
- updatePackageJSONAndInstall.zig:340
Features: extracted_packages, text_lockfile
```
## Test plan
- [x] `bun run zig:check` passes
- [ ] CI passes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Skip 2 tests that use `grpctest.kleinsch.com` (domain no longer
exists)
- Fix flaky "should not keep repeating failed resolutions" test
These tests were originally skipped when added in #14286, but were
accidentally un-skipped in #20051. This restores them to match upstream
grpc-node.
## To re-enable these tests in the future
Bun could set up its own DNS TXT record at `*.bun.sh`. According to the
[gRPC A2
spec](https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md):
**DNS Setup needed:**
1. A record: `grpctest.bun.sh` → any valid IP (e.g., `127.0.0.1`)
2. TXT record: `_grpc_config.grpctest.bun.sh` with value:
```
grpc_config=[{"serviceConfig":{"loadBalancingPolicy":"round_robin","methodConfig":[{"name":[{"service":"MyService","method":"Foo"}],"waitForReady":true}]}}]
```
Then update the tests to use `grpctest.bun.sh` instead.
## Test plan
- [x] `bun bd test test/js/third_party/grpc-js/test-resolver.test.ts`
passes (20 pass, 3 skip, 1 todo, 0 fail)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
We can't use globalThis.takeException() because it throws out of memory
error when we instead need to take the exception.
### How did you verify your code works?
## Summary
- Fixed boundary check in `String.zig` to use `>=` instead of `>` for
`max_length()` comparisons
- Strings fail when the length is exactly equal to `max_length()`, not
just when exceeding it
- This affects both `createExternal` and
`createExternalGloballyAllocated` functions
## Test plan
- Existing tests should continue to pass
- Strings with length exactly equal to `max_length()` will now be
properly rejected
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Fixed a typo in `makeComponent` that incorrectly identified
2-character patterns starting with `.` (like `.*`) as `..` (DotBack)
patterns
- The condition checked `pattern[component.start] == '.'` twice instead
of checking both characters at positions 0 and 1
- This caused patterns like `.*/*` to be parsed as `../` + `*`, making
the glob walker traverse into parent directories
Fixes#24936
## Test plan
- [x] Added tests in `test/js/bun/glob/scan.test.ts` that verify
patterns like `.*/*` and `.*/**/*.ts` don't escape the cwd boundary
- [x] Tests fail with system bun (bug reproduced) and pass with the fix
- [x] All existing glob tests pass (169 tests)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
Removes a TODO
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## What does this PR do?
Adds missing documentation for features introduced in Bun v1.3.2 and
v1.3.3:
- **Standalone executable config flags**
(`docs/bundler/executables.mdx`): Document
`--no-compile-autoload-dotenv` and `--no-compile-autoload-bunfig` flags
that control automatic config file loading in compiled binaries
- **Test retry/repeats** (`docs/test/writing-tests.mdx`): Document the
`retry` and `repeats` test options for handling flaky tests
- **Disable env file loading**
(`docs/runtime/environment-variables.mdx`): Document `--no-env-file`
flag and `env = false` bunfig option
## How did you verify your code works?
- [x] Verified documentation is accurate against source code
implementation in `src/cli/Arguments.zig`
- [x] Verified features are not already documented elsewhere
- [x] Cross-referenced with v1.3.2 and v1.3.3 release notes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Adds [@mschwarzl's Fuzzilli Support
PR](https://github.com/oven-sh/bun/pull/23862) with the changes
necessary to be able to:
- Run it in CI
- Make no impact on `debug` and `release` mode.
### How did you verify your code works?
---------
Co-authored-by: Martin Schwarzl <mschwarzl@cloudflare.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
### What does this PR do?
This was creating `Zig::FFIFunction` when we could instead use a plain
`JSC::JSFunction`
### How did you verify your code works?
Added a test
### What does this PR do?
`blob.stream(undefined)`
### How did you verify your code works?
Added a test
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Fixes ENG-21490
### How did you verify your code works?
Added a test that would previously fail due to timeout. It also confirms
the parsed result is correct.
---------
Co-authored-by: taylor.fish <contact@taylor.fish>
### What does this PR do?
Makes sure we are creating error messages with an allocator that will
not `deinit` at the end of function scope on error.
fixes ENG-21528
### How did you verify your code works?
Added a test
### What does this PR do?
We need to call `uv_loop_close` in order to remove the threadlocal loop
from a list in libuv so it won't be used later. This explains the crash
reports because they have `workers_terminated` in features.
Fixes#24804
Closes BUN-3NV
Closes ENG-21523
### How did you verify your code works?
Manually. I'm not sure how to write a test yet other than manually
clicking sleep
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Zack Radisic <zack@theradisic.com>
### What does this PR do?
We must use the right number of properties or we should set it to 0
### How did you verify your code works?
Read the code to check the amount of properties + CI
## Summary
Implements `--no-env-file` CLI flag and bunfig configuration options to
disable automatic `.env` file loading at runtime and in the bundler.
## Motivation
Users may want to disable automatic `.env` file loading for:
- Production environments where env vars are managed externally
- CI/CD pipelines where .env files should be ignored
- Testing scenarios where explicit env control is needed
- Security contexts where .env files should not be trusted
## Changes
### CLI Flag
- Added `--no-env-file` flag that disables loading of default .env files
- Still respects explicit `--env-file` arguments for intentional env
loading
### Bunfig Configuration
Added support for disabling .env loading via `bunfig.toml`:
- `env = false` - disables default .env file loading
- `env = null` - disables default .env file loading
- `env.file = false` - disables default .env file loading
- `env.file = null` - disables default .env file loading
### Implementation
- Added `disable_default_env_files` field to `api.TransformOptions` with
serialization support
- Added `disable_default_env_files` field to `options.Env` struct
- Implemented `loadEnvConfig` in bunfig parser to handle env
configuration
- Wired up flag throughout runtime and bundler code paths
- Preserved package.json script runner behavior (always skips default
.env files)
## Tests
Added comprehensive test suite (`test/cli/run/no-envfile.test.ts`) with
9 tests covering:
- `--no-env-file` flag with `.env`, `.env.local`,
`.env.development.local`
- Bunfig configurations: `env = false`, `env.file = false`, `env = true`
- `--no-env-file` with `-e` eval flag
- `--no-env-file` combined with `--env-file` (explicit files still load)
- Production mode behavior
All tests pass with debug bun and fail with system bun (as expected).
## Example Usage
```bash
# Disable all default .env files
bun --no-env-file index.js
# Disable defaults but load explicit file
bun --no-env-file --env-file .env.production index.js
# Disable via bunfig.toml
cat > bunfig.toml << 'CONFIG'
env = false
CONFIG
bun index.js
```
## Files Changed
- `src/cli/Arguments.zig` - CLI flag parsing
- `src/api/schema.zig` - API schema field with encode/decode
- `src/options.zig` - Env struct field and wiring
- `src/bunfig.zig` - Config parsing with loadEnvConfig
- `src/transpiler.zig` - Runtime wiring
- `src/bun.js.zig` - Runtime wiring
- `src/cli/exec_command.zig` - Runtime wiring
- `src/cli/run_command.zig` - Preserved package.json script runner
behavior
- `test/cli/run/no-envfile.test.ts` - Comprehensive test suite
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Fixes a regression introduced in Bun v1.3.2 with #24283.
We are not able to skip `sharp` lifecycle scripts before v0.33.0 because
previous versions did not use optional dependencies with prebuilds.
Fixes#24550
Fixes ENG-21519
### How did you verify your code works?
Manually
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Ensures strings that would parse as a number with leading zeroes aren't
emitted without quotes.
fixes#23691
### How did you verify your code works?
Added a test
### What does this PR do?
The assertion was too strict.
This pr changes to assertion to allow multiple of the same dependency id
to be present. Also changes all the assertions to debug assertions.
fixes#24510
### How did you verify your code works?
Manually, and added a new test
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Marko Vejnovic <marko@bun.com>
This updates the documentation for `fs.watch()` to use `relativePath`
instead of `filename` in the recursive example, following the same
convention from PR #23990.
When `recursive: true` is set on `fs.watch()`, the callback receives a
relative path to the changed file rather than just a simple filename.
Using `relativePath` as the parameter name makes this distinction
clearer to users.
**Related to:** https://github.com/oven-sh/bun/pull/23990
Co-authored-by: Michael H <git@riskymh.dev>
### What does this PR do?
We must use the right number of properties (not more or less) or we
should set it to 0
### How did you verify your code works?
Read the code, this will avoid potencial crashs and improve stability
### What does this PR do?
Fixes
https://linear.app/oven/issue/ENG-21505/panic-attempt-to-use-null-value-at-incrementalgraph-by-misusing-jscode
When calling `takeJSBundleToList/takeJSBundle` the desired behavior is
to get only JS chunks from the graph, and we can contain CSS chunks in
the graph we can just continue and ignore in this case keeping the
desired behavior in a safe way instead of unconditional unwrapping
something that is not guaranteed to have a jsCode.
### How did you verify your code works?
CI
## Summary
Remove outdated version mentions (1.0.x and 1.1.x) from documentation
for better consistency. These versions are over a year old - you should
be using a recent version of bun :).
## What changed
**Removed version mentions from:**
- `docs/pm/lifecycle.mdx` - v1.0.16 (trusted dependencies)
- `docs/bundler/executables.mdx` - v1.0.23, v1.1.25, v1.1.30 (various
features)
- `docs/guides/install/jfrog-artifactory.mdx` - v1.0.3+ (env var
comment)
- `docs/guides/install/azure-artifacts.mdx` - v1.0.3+ (env var comment)
- `docs/runtime/workers.mdx` - v1.1.13, v1.1.35 (blob URLs, preload)
- `docs/runtime/networking/dns.mdx` - v1.1.9 (DNS caching)
- `docs/guides/runtime/import-html.mdx` - v1.1.5
- `docs/guides/runtime/define-constant.mdx` - v1.1.5
- `docs/runtime/sqlite.mdx` - v1.1.31
**Kept version mentions in:**
- All 1.2.x versions (still recent, less than a year old)
- Benchmark version numbers (e.g., S3 performance comparison with
v1.1.44)
- `docs/guides/install/yarnlock.mdx` (bun.lock introduction context)
- `docs/project/building-windows.mdx` (build requirements)
- `docs/runtime/http/websockets.mdx` (performance benchmarks)
## Why
The docs lack consistency around version mentions - we don't document
every feature's version, so keeping scattered old version numbers looks
inconsistent. These changes represent a small percentage of features
added recently, and users on ancient versions have bigger problems than
needing to know exactly when a feature landed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: RiskyMH <git@riskymh.dev>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
- Use `std.fmt.fmtIntSizeBin` to format progress indicators with byte
sizes
- Improves readability during operations like `bun upgrade`
- Changes display from raw bytes (e.g., "23982378/2398284") to
human-readable format (e.g., "23.2MiB/100MiB")
## Changes
Modified `src/Progress.zig`:
- Updated progress formatting to use `std.fmt.fmtIntSizeBin` for both
current and total sizes
- Applied to both progress with total (`[current/total unit]`) and
without total (`[current unit]`)
## Test plan
- [x] Build succeeds with `bun bd`
- [ ] Manual verification with `bun upgrade` shows human-readable sizes
Fixes#24226fixes#7826🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: pfg <pfg@pfg.pw>
Fixes ENG-21481
Updates ci_info to include more CIs. It makes it codegen the ci
detection based on the json from the ci-info package. Also it supports
setting CI=true to force ci detected.
---------
Co-authored-by: pfg <pfg@pfg.pw>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Updates documentation for all major features and changes introduced in
Bun v1.3.2 blog post.
## Changes
### Package Manager
- ✅ Document `configVersion` system for controlling default linker
behavior
- ✅ Clarify that "existing projects (made pre-v1.3.2)" use hoisted
installs for backward compatibility
- ✅ Add smart postinstall script optimization with environment variable
flags
- ✅ Document improved Git dependency resolution with HTTP tarball
optimization
- ✅ Add `bun list` alias for `bun pm ls`
### Testing
- ✅ Document new `onTestFinished` lifecycle hook with simple example
- ✅ Add to lifecycle hooks table in test documentation
### Runtime & Performance
- ✅ Add CPU profiling with `--cpu-prof` flag documentation
- ✅ Place after memory usage section for better flow
### WebSockets
- ✅ Add `subscriptions` getter to existing pub/sub example
- ✅ Add TypeScript reference for the subscriptions property
## Documentation Improvements
All documentation now consistently:
- Uses "made pre-v1.3.2" to clarify existing project behavior
- Simplifies default linker explanations with clear references to
`/docs/pm/isolated-installs`
- Uses `/docs/pm/isolated-installs` for all internal references
- Avoids confusing technical details in favor of user-friendly summaries
## Files Modified
- `docs/guides/install/add-git.mdx` - Added GitHub tarball optimization
note
- `docs/pm/cli/install.mdx` - Added installation strategies and smart
postinstall docs
- `docs/pm/cli/pm.mdx` - Added bun list alias
- `docs/pm/isolated-installs.mdx` - Updated default behavior section
with configVersion table
- `docs/project/benchmarking.mdx` - Added CPU profiling section
- `docs/runtime/bunfig.mdx` - Clarified install.linker defaults
- `docs/runtime/http/websockets.mdx` - Added subscriptions to example
and TypeScript interface
- `docs/test/lifecycle.mdx` - Added onTestFinished hook documentation
## Diff
````diff
diff --git a/docs/guides/install/add-git.mdx b/docs/guides/install/add-git.mdx
index 70950e1a63..7f8f3c8d81 100644
--- a/docs/guides/install/add-git.mdx
+++ b/docs/guides/install/add-git.mdx
@@ -33,6 +33,8 @@ bun add git@github.com:lodash/lodash.git
bun add github:colinhacks/zod
```
+**Note:** GitHub dependencies download via HTTP tarball when possible for faster installation.
+
---
See [Docs > Package manager](https://bun.com/docs/cli/install) for complete documentation of Bun's package manager.
diff --git a/docs/pm/cli/install.mdx b/docs/pm/cli/install.mdx
index 7affb62646..dde268b7e5 100644
--- a/docs/pm/cli/install.mdx
+++ b/docs/pm/cli/install.mdx
@@ -88,6 +88,13 @@ Lifecycle scripts will run in parallel during installation. To adjust the maximu
bun install --concurrent-scripts 5
```
+Bun automatically optimizes postinstall scripts for popular packages (like `esbuild`, `sharp`, etc.) by determining which scripts need to run. To disable these optimizations:
+
+```bash terminal icon="terminal"
+BUN_FEATURE_FLAG_DISABLE_NATIVE_DEPENDENCY_LINKER=1 bun install
+BUN_FEATURE_FLAG_DISABLE_IGNORE_SCRIPTS=1 bun install
+```
+
---
## Workspaces
@@ -231,7 +238,7 @@ Bun supports installing dependencies from Git, GitHub, and local or remotely-hos
Bun supports two package installation strategies that determine how dependencies are organized in `node_modules`:
-### Hoisted installs (default for single projects)
+### Hoisted installs
The traditional npm/Yarn approach that flattens dependencies into a shared `node_modules` directory:
@@ -249,7 +256,15 @@ 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](/pm/isolated-installs).
+### Default strategy
+
+The default linker strategy depends on whether you're starting fresh or have an existing project:
+
+- **New workspaces/monorepos**: `isolated` (prevents phantom dependencies)
+- **New single-package projects**: `hoisted` (traditional npm behavior)
+- **Existing projects (made pre-v1.3.2)**: `hoisted` (preserves backward compatibility)
+
+The default is controlled by a `configVersion` field in your lockfile. For a detailed explanation, see [Package manager > Isolated installs](/docs/pm/isolated-installs).
---
@@ -319,8 +334,7 @@ dryRun = false
concurrentScripts = 16 # (cpu count or GOMAXPROCS) x2
# installation strategy: "hoisted" or "isolated"
-# default: "hoisted" (for single-project projects)
-# default: "isolated" (for monorepo projects)
+# default varies by project type - see /docs/pm/isolated-installs
linker = "hoisted"
diff --git a/docs/pm/cli/pm.mdx b/docs/pm/cli/pm.mdx
index fc297753d3..9c8faa7da1 100644
--- a/docs/pm/cli/pm.mdx
+++ b/docs/pm/cli/pm.mdx
@@ -115,6 +115,8 @@ To print a list of installed dependencies in the current project and their resol
```bash terminal icon="terminal"
bun pm ls
+# or
+bun list
```
```txt
@@ -130,6 +132,8 @@ To print all installed dependencies, including nth-order dependencies.
```bash terminal icon="terminal"
bun pm ls --all
+# or
+bun list --all
```
```txt
diff --git a/docs/pm/isolated-installs.mdx b/docs/pm/isolated-installs.mdx
index 73c6748b15..17afe02fe1 100644
--- a/docs/pm/isolated-installs.mdx
+++ b/docs/pm/isolated-installs.mdx
@@ -5,7 +5,7 @@ description: "Strict dependency isolation similar to pnpm's approach"
Bun provides an alternative package installation strategy called **isolated installs** that creates strict dependency isolation similar to pnpm's approach. This mode prevents phantom dependencies and ensures reproducible, deterministic builds.
-This is the default installation strategy for monorepo projects.
+This is the default installation strategy for **new** workspace/monorepo projects (with `configVersion = 1` in the lockfile). Existing projects continue using hoisted installs unless explicitly configured.
## What are isolated installs?
@@ -43,8 +43,23 @@ linker = "isolated"
### Default behavior
-- For monorepo projects, Bun uses the **isolated** installation strategy by default.
-- For single-project projects, Bun uses the **hoisted** installation strategy by default.
+The default linker strategy depends on your project's lockfile `configVersion`:
+
+| `configVersion` | Using workspaces? | Default Linker |
+| --------------- | ----------------- | -------------- |
+| `1` | ✅ | `isolated` |
+| `1` | ❌ | `hoisted` |
+| `0` | ✅ | `hoisted` |
+| `0` | ❌ | `hoisted` |
+
+**New projects**: Default to `configVersion = 1`. In workspaces, v1 uses the isolated linker by default; otherwise it uses hoisted linking.
+
+**Existing Bun projects (made pre-v1.3.2)**: If your existing lockfile doesn't have a version yet, Bun sets `configVersion = 0` when you run `bun install`, preserving the previous hoisted linker default.
+
+**Migrations from other package managers**:
+
+- From pnpm: `configVersion = 1` (using isolated installs in workspaces)
+- From npm or yarn: `configVersion = 0` (using hoisted installs)
You can override the default behavior by explicitly specifying the `--linker` flag or setting it in your configuration file.
diff --git a/docs/project/benchmarking.mdx b/docs/project/benchmarking.mdx
index 1263a06729..2ab8bcafc8 100644
--- a/docs/project/benchmarking.mdx
+++ b/docs/project/benchmarking.mdx
@@ -216,3 +216,26 @@ numa nodes: 1
elapsed: 0.068 s
process: user: 0.061 s, system: 0.014 s, faults: 0, rss: 57.4 MiB, commit: 64.0 MiB
```
+
+## CPU profiling
+
+Profile JavaScript execution to identify performance bottlenecks with the `--cpu-prof` flag.
+
+```sh terminal icon="terminal"
+bun --cpu-prof script.js
+```
+
+This generates a `.cpuprofile` file you can open in Chrome DevTools (Performance tab → Load profile) or VS Code's CPU profiler.
+
+### Options
+
+```sh terminal icon="terminal"
+bun --cpu-prof --cpu-prof-name my-profile.cpuprofile script.js
+bun --cpu-prof --cpu-prof-dir ./profiles script.js
+```
+
+| Flag | Description |
+| ---------------------------- | -------------------- |
+| `--cpu-prof` | Enable profiling |
+| `--cpu-prof-name <filename>` | Set output filename |
+| `--cpu-prof-dir <dir>` | Set output directory |
diff --git a/docs/runtime/bunfig.mdx b/docs/runtime/bunfig.mdx
index 91005c1607..5b7fe49823 100644
--- a/docs/runtime/bunfig.mdx
+++ b/docs/runtime/bunfig.mdx
@@ -497,9 +497,9 @@ print = "yarn"
### `install.linker`
-Configure the default linker strategy. Default `"hoisted"` for single-project projects, `"isolated"` for monorepo projects.
+Configure the linker strategy for installing dependencies. Defaults to `"isolated"` for new workspaces, `"hoisted"` for new single-package projects and existing projects (made pre-v1.3.2).
-For complete documentation refer to [Package manager > Isolated installs](/pm/isolated-installs).
+For complete documentation refer to [Package manager > Isolated installs](/docs/pm/isolated-installs).
```toml title="bunfig.toml" icon="settings"
[install]
diff --git a/docs/runtime/http/websockets.mdx b/docs/runtime/http/websockets.mdx
index b33f37c29f..174043200d 100644
--- a/docs/runtime/http/websockets.mdx
+++ b/docs/runtime/http/websockets.mdx
@@ -212,6 +212,9 @@ const server = Bun.serve({
// this is a group chat
// so the server re-broadcasts incoming message to everyone
server.publish("the-group-chat", `${ws.data.username}: ${message}`);
+
+ // inspect current subscriptions
+ console.log(ws.subscriptions); // ["the-group-chat"]
},
close(ws) {
const msg = `${ws.data.username} has left the chat`;
@@ -393,6 +396,7 @@ interface ServerWebSocket {
readonly data: any;
readonly readyState: number;
readonly remoteAddress: string;
+ readonly subscriptions: string[];
send(message: string | ArrayBuffer | Uint8Array, compress?: boolean): number;
close(code?: number, reason?: string): void;
subscribe(topic: string): void;
diff --git a/docs/test/lifecycle.mdx b/docs/test/lifecycle.mdx
index 6427175df6..3837f0e948 100644
--- a/docs/test/lifecycle.mdx
+++ b/docs/test/lifecycle.mdx
@@ -6,11 +6,12 @@ description: "Learn how to use beforeAll, beforeEach, afterEach, and afterAll li
The test runner supports the following lifecycle hooks. This is useful for loading test fixtures, mocking data, and configuring the test environment.
| Hook | Description |
-| ------------ | --------------------------- |
+| ---------------- | ---------------------------------------------------------- |
| `beforeAll` | Runs once before all tests. |
| `beforeEach` | Runs before each test. |
| `afterEach` | Runs after each test. |
| `afterAll` | Runs once after all tests. |
+| `onTestFinished` | Runs after a single test finishes (after all `afterEach`). |
## Per-Test Setup and Teardown
@@ -90,6 +91,23 @@ describe("test group", () => {
});
```
+### `onTestFinished`
+
+Use `onTestFinished` to run a callback after a single test completes. It runs after all `afterEach` hooks.
+
+```ts title="test.ts" icon="/icons/typescript.svg"
+import { test, onTestFinished } from "bun:test";
+
+test("cleanup after test", () => {
+ onTestFinished(() => {
+ // runs after all afterEach hooks
+ console.log("test finished");
+ });
+});
+```
+
+Not supported in concurrent tests; use `test.serial` instead.
+
## Global Setup and Teardown
To scope the hooks to an entire multi-file test run, define the hooks in a separate file.
````
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Michael H <git@riskymh.dev>
Co-authored-by: Lydia Hallie <lydiajuliettehallie@gmail.com>
### What does this PR do?
Fixes `bun pm ls --all` crash with unresolved optional peer
dependencies.
Fixes `bun pm ls` crash with empty lockfiles.
Fixes#24502
### How did you verify your code works?
Added a test for both crashes
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Updated all example version placeholders in documentation from 1.3.1 and
1.2.20 to 1.3.2.
## Changes
Updated version examples in:
- Installation examples (Linux/macOS and Windows install commands)
- Package manager output examples (`bun install`, `bun publish`, `bun
pm` commands)
- Test runner output examples
- Spawn/child process output examples
- Fetch User-Agent header examples in debugging docs
- `Bun.version` API example
## Notes
- Historical version references (e.g., "As of Bun v1.x.x..." or "Bun
v1.x.x+ required") were intentionally **preserved** as they document
when features were introduced
- Generic package.json version examples (non-Bun package versions) were
**preserved**
- Only example outputs and code snippets showing current Bun version
were updated
## Files Changed (13 total)
- `docs/installation.mdx`
- `docs/guides/install/from-npm-install-to-bun-install.mdx`
- `docs/guides/install/add-peer.mdx`
- `docs/bundler/html-static.mdx` (6 occurrences)
- `docs/test/dom.mdx`
- `docs/pm/cli/publish.mdx`
- `docs/pm/cli/pm.mdx`
- `docs/guides/test/snapshot.mdx` (2 occurrences)
- `docs/guides/ecosystem/nuxt.mdx`
- `docs/guides/util/version.mdx`
- `docs/runtime/debugger.mdx` (3 occurrences)
- `docs/runtime/networking/fetch.mdx`
- `docs/runtime/child-process.mdx`
**Total:** 23 version references updated
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Michael H <git@riskymh.dev>
### What does this PR do?
Fixes https://github.com/oven-sh/bun/issues/24385
### How did you verify your code works?
Confirmed that the test added in the first commit fails on mainline
`bun` and is fixed in this PR.
---------
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
This PR is the fix-only version of
https://github.com/oven-sh/bun/pull/24486. Unfortunately due to
complexity setting up all CI agents to ping private git repos, I was
unable to get CI passing there.
### How did you verify your code works?
I ran this:
```
marko@fedora:~/Desktop/bun-4$ bun add git+ssh://git@github.com:oven-sh/private-install-test-repo.git#5b37e644a2ef23fad0da4027042f01b194b179e8
bun add v1.3.2-canary.108 (44402ad2)
🔍 Resolving [1/1] error: "git clone" for "git+ssh://git@github.com:oven-sh/private-install-test-repo.git#5b37e644a2ef23fad0da4027042f01b194b179e8" failed
error: InstallFailed cloning repository for git+ssh://git@github.com:oven-sh/private-install-test-repo.git#5b37e644a2ef23fad0da4027042f01b194b179e8
error: git+ssh://git@github.com:oven-sh/private-install-test-repo.git#5b37e644a2ef23fad0da4027042f01b194b179e8 failed to resolve
```
followed by
```
marko@fedora:~/Desktop/bun-4$ BUN_DEBUG_QUIET_LOGS=1 ./build/debug/bun-debug add git+ssh://git@github.com:oven-sh/private-install-test-repo.git#5b37e644a2ef23fad0da4027042f01b194b179e8
bun add v1.3.2 (0db90b25)
installed private-install-test-repo@git+ssh://git@github.com:oven-sh/private-install-test-repo.git#5b37e644a2ef23fad0da4027042f01b194b179e8
[1.61s] done
```
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
Adds deployment guides for Bun apps on AWS Lambda, Google Cloud Run, and
DigitalOcean using a custom `Dockerfile`
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
In the crash reporter, we currently use glibc's `backtrace()` function
on glibc Linux targets. However, this has resulted in poor stack traces
in many scenarios, particularly when a JSC signal handlers is involved,
in which case the stack trace tends to have only one frame—the signal
handler itself. Considering that JSC installs a signal handler for SEGV,
this is particularly bad.
Zig's `std.debug.captureStackTrace` generates considerably more complete
stack traces, but it has an issue where the top frame is missing when a
signal handler is involved. This is unfortunate, but it's still the
better option for now. Note that our stack traces on macOS also have
this missing frame issue.
In the future, we will investigate backporting the changes to stack
trace capturing that were recently made in Zig's `master` branch, since
that seems to have fixed the missing frame issue.
This PR still uses the stack trace provided by `backtrace()` if it
returns more frames than `captureStackTrace`. In particular, ARM may
need this behavior.
(For internal tracking: fixes ENG-21406)
Fixes#23865, Fixes ENG-21446
Previously, a termination exception would be thrown. We didn't handle it
properly and eventually it got caught by a `catch @panic()` handler.
Now, no termination exception is thrown.
```
drainMicrotasksWithGlobal calls JSC__JSGlobalObject__drainMicrotasks
JSC__JSGlobalObject__drainMicrotasks returns m_terminationException
-> drainMicrotasksWithGlobal
-> event_loop.zig:exit, which catches the error and discards it
-> ...
```
For workers, we will need to handle termination exceptions in this
codepath.
~~Previously, it would see the exception, call
reportUncaughtExceptoinAtEventLoop, but the exception would still
survive and return out from the catch scope. You're not supposed to
still have an exception signaled at the exit of a catch scope. Exception
checker may not have caught it because maybe the branch wasn't taken.~~
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
pulled out of https://github.com/oven-sh/bun/pull/21809
- brings the ASAN behavior on linux closer in sync with macos
- fixes some tests to also pass in node
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
### What does this PR do?
Fixes#24387
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Marko Vejnovic <marko@bun.com>
## Summary
Fixes a segfault that occurred when calling `process.dlopen` with
`null`, `undefined`, or primitive values for `exports`.
Previously, this would cause a crash at address `0x00000000` in
`node_module_register` due to dereferencing an uninitialized
`strongExportsObject`.
## Changes
- Modified `src/bun.js/bindings/v8/node.cpp` to use JSC's `toObject()`
instead of manual type checking
- This matches Node.js `ToObject()` behavior:
- Throws `TypeError` for `null`/`undefined`
- Creates wrapper objects for primitives
- Preserves existing objects
## Test Plan
Added `test/js/node/process/dlopen-non-object-exports.test.ts` with
three test cases:
- Null exports (should throw)
- Undefined exports (should throw)
- Primitive exports (should create wrapper)
All tests pass with the fix.
## Related Issue
Fixes the first bug discovered in the segfault investigation.
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Fixes incorrect JWK "d" field length for exported elliptic curve private
keys. The "d" field is now correctly padded to ensure RFC 7518
compliance.
## Problem
When exporting EC private keys to JWK format, the "d" field would
sometimes be shorter than required by RFC 7518 because
`convertToBytes()` doesn't pad the result when the BIGNUM has leading
zeros. This caused incompatibility with Chrome's strict validation,
though Node.js and Firefox would accept the malformed keys.
Expected lengths per RFC 7518:
- P-256: 32 bytes → 43 base64url characters
- P-384: 48 bytes → 64 base64url characters
- P-521: 66 bytes → 88 base64url characters
## Solution
Changed `src/bun.js/bindings/webcrypto/CryptoKeyECOpenSSL.cpp:420` to
use `convertToBytesExpand(privateKey, keySizeInBytes)` instead of
`convertToBytes(privateKey)`, ensuring the private key is padded with
leading zeros when necessary. This matches the behavior already used for
the x and y public key coordinates.
## Test plan
- ✅ Added regression test in `test/regression/issue/24399.test.ts` that
generates multiple keys for each curve and verifies correct "d" field
length
- ✅ Test fails with `USE_SYSTEM_BUN=1 bun test` (reproduces the bug)
- ✅ Test passes with `bun bd test` (verifies the fix)
- ✅ Existing crypto tests pass
Fixes#24399🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Refactored NAPI property and element access to use inline methods and
improved error handling. Added comprehensive tests for default value
behavior and numeric string key operations in NAPI, ensuring correct
handling of missing properties, integer keys, and property deletion.
Updated TypeScript tests to cover new scenarios.
### How did you verify your code works?
Tests
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
## Summary
Fixes 100% CPU usage on idle WebSocket servers between bun-v1.2.23 and
bun-v1.3.0.
Many users reported WebSocket server CPU usage jumping to 100% on idle
connections after upgrading to v1.3.0. Investigation revealed a missing
`poll_ref.unref()` call in the WebSocket upgrade path.
## Root Cause
In commit 625e537f5d (#23348), the `OnBeforeOpen` callback mechanism was
removed as part of refactoring the WebSocket upgrade process. However,
this callback contained a critical cleanup step:
```zig
defer ctx.this.poll_ref.unref(ctx.globalObject.bunVM());
```
When a `NodeHTTPResponse` is created, `poll_ref.ref()` is called (line
314) to keep the event loop alive while handling the HTTP request. After
a WebSocket upgrade, the HTTP response object is no longer relevant and
its `poll_ref` must be unref'd to indicate the request processing is
complete.
Without this unref, the event loop maintains an active reference even
after the upgrade completes, causing the CPU to spin at 100% waiting for
events on what should be an idle connection.
## Changes
- Added `poll_ref.unref()` call in `NodeHTTPResponse.upgrade()` after
setting the `upgraded` flag
- Added regression test to verify event loop properly exits after
WebSocket upgrade
## Test Plan
- [x] Code compiles successfully
- [x] Existing WebSocket tests pass
- [x] Manual testing confirms CPU usage returns to normal on idle
WebSocket connections
## Related Issues
Fixes issue reported by users between bun-v1.2.23 and bun-v1.3.0
regarding 100% CPU usage on idle WebSocket servers.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Restore call to us_get_default_ca_certificates, and
X509_STORE_set_default_paths
Fixes https://github.com/oven-sh/bun/issues/23735
### How did you verify your code works?
Manually test running:
```bash
bun -e "await fetch('https://secure-api.eloview.com').then(res => res.t
ext()).then(console.log);"
```
should not result in:
```js
error: unable to get local issuer certificate
path: "https://secure-api.eloview.com/",
errno: 0,
code: "UNABLE_TO_GET_ISSUER_CERT_LOCALLY"
```
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Bug Fixes**
* Enhanced system root certificate handling to ensure consistent
validation across all secure connections.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
### What does this PR do?
Adds `"configVersion"` to bun.lock(b). The version will be used to keep
default settings the same if they would be breaking across bun versions.
fixes ENG-21389
fixes ENG-21388
### How did you verify your code works?
TODO:
- [ ] new project
- [ ] existing project without configVersion
- [ ] existing project with configVersion
- [ ] same as above but with bun.lockb
- [ ] configVersion@0 defaults to hoisted linker
- [ ] new projects use isolated linker
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
This PR introduces a new postinstall optimization system that
significantly reduces the need to run lifecycle scripts for certain
packages by intelligently handling their requirements at install time.
## Key Features
### 1. Native Binlink Optimization
When packages like `esbuild` ship platform-specific binaries as optional
dependencies, we now:
- Detect the native binlink pattern (enabled by default for `esbuild`)
- Find the matching platform-specific dependency based on target CPU/OS
- Link binaries directly from the platform-specific package (e.g.,
`@esbuild/darwin-arm64`)
- Fall back gracefully if the platform-specific package isn't found
**Result**: No postinstall scripts needed for esbuild and similar
packages.
### 2. Lifecycle Script Skipping
For packages like `sharp` that run heavy postinstall scripts:
- Skip lifecycle scripts entirely (enabled by default for `sharp`)
- Prevents downloading large binaries or compiling native code
unnecessarily
- Reduces install time and potential failures in restricted environments
## Configuration
Both features can be configured via `package.json`:
```json
{
"nativeDependencies": ["esbuild", "my-custom-package"],
"ignoreScripts": ["sharp", "another-package"]
}
```
Set to empty arrays to disable defaults:
```json
{
"nativeDependencies": [],
"ignoreScripts": []
}
```
Environment variable overrides:
- `BUN_FEATURE_FLAG_DISABLE_NATIVE_DEPENDENCY_LINKER=1` - disable native
binlink
- `BUN_FEATURE_FLAG_DISABLE_IGNORE_SCRIPTS=1` - disable script ignoring
## Implementation Details
### Core Components
- **`postinstall_optimizer.zig`**: New file containing the optimizer
logic
- `PostinstallOptimizer` enum with `native_binlink` and `ignore`
variants
- `List` type to track optimization strategies per package hash
- Defaults for `esbuild` (native binlink) and `sharp` (ignore)
- **`Bin.Linker` changes**: Extended to support separate target paths
- `target_node_modules_path`: Where to find the actual binary
- `target_package_name`: Name of the package containing the binary
- Fallback logic when native binlink optimization fails
### Modified Components
- **PackageInstaller.zig**: Checks optimizer before:
- Enqueueing lifecycle scripts
- Linking binaries (with platform-specific package resolution)
- **isolated_install/Installer.zig**: Similar checks for isolated linker
mode
- `maybeReplaceNodeModulesPath()` resolves platform-specific packages
- Retry logic without optimization on failure
- **Lockfile**: Added `postinstall_optimizer` field to persist
configuration
## Changes Included
- Updated `esbuild` from 0.21.5 to 0.25.11 (testing with latest)
- VS Code launch config updates for debugging install with new flags
- New feature flags in `env_var.zig`
## Test Plan
- [x] Existing install tests pass
- [ ] Test esbuild install without postinstall scripts running
- [ ] Test sharp install with scripts skipped
- [ ] Test custom package.json configuration
- [ ] Test fallback when platform-specific package not found
- [ ] Test feature flag overrides
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **New Features**
* Native binlink optimization: installs platform-specific binaries when
available, with a safe retry fallback and verbose logging option.
* Per-package postinstall controls to optionally skip lifecycle scripts.
* New feature flags to disable native binlink optimization and to
disable lifecycle-script ignoring.
* **Tests**
* End-to-end tests and test packages added to validate native binlink
behavior across install scenarios and linker modes.
* **Documentation**
* Bench README and sample app migrated to a Next.js-based setup.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
Fixes Next.js 16 + React Compiler build failure when using Bun runtime.
## Issue
When `Module._resolveFilename` was overridden (e.g., by Next.js's
require-hook), Bun was not passing the `options` parameter (which
contains `paths`) to the override function. This caused resolution
failures when the override tried to use custom resolution paths.
Additionally, when `Module._resolveFilename` was called directly with
`options.paths`, Bun was ignoring the paths parameter and using default
resolution.
## Root Causes
1. In `ImportMetaObject.cpp`, when calling an overridden
`_resolveFilename` function, the options object with paths was not being
passed as the 4th argument.
2. In `NodeModuleModule.cpp`, `jsFunctionResolveFileName` was calling
`Bun__resolveSync` without extracting and using the `options.paths`
parameter.
## Solution
1. In `ImportMetaObject.cpp`: When `userPathList` is provided, construct
an options object with `{paths: userPathList}` and pass it as the 4th
argument to the overridden `_resolveFilename` function.
2. In `NodeModuleModule.cpp`: Extract `options.paths` from the 4th
argument and call `Bun__resolveSyncWithPaths` when paths are provided,
instead of always using `Bun__resolveSync`.
## Reproduction
Before this fix, running:
```bash
bun --bun next build --turbopack
```
on a Next.js 16 app with React Compiler enabled would fail with:
```
Cannot find module './node_modules/babel-plugin-react-compiler'
```
## Testing
- Added comprehensive tests for `Module._resolveFilename` with
`options.paths`
- Verified Next.js 16 + React Compiler + Turbopack builds successfully
with Bun
- All 5 new tests pass with the fix, 3 fail without it
- All existing tests continue to pass
## Files Changed
- `src/bun.js/bindings/ImportMetaObject.cpp` - Pass options to override
- `src/bun.js/modules/NodeModuleModule.cpp` - Handle options.paths in
_resolveFilename
- `test/js/node/module/module-resolve-filename-paths.test.js` - New test
suite
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Extract `FetchTasklet` struct from `src/bun.js/webcore/fetch.zig` into
its own file at `src/bun.js/webcore/fetch/FetchTasklet.zig` to improve
code organization and modularity.
## Changes
- Moved `FetchTasklet` struct definition (1336 lines) to new file
`src/bun.js/webcore/fetch/FetchTasklet.zig`
- Added all necessary imports to the new file
- Updated `fetch.zig` line 61 to import `FetchTasklet` from the new
location: `pub const FetchTasklet =
@import("./fetch/FetchTasklet.zig").FetchTasklet;`
- Verified compilation succeeds with `bun bd`
## Impact
- No functional changes - this is a pure refactoring
- Improves code organization by separating the large `FetchTasklet`
implementation
- Makes the codebase more maintainable and easier to navigate
- Reduces `fetch.zig` from 2768 lines to 1433 lines
## Test plan
- [x] Built successfully with `bun bd`
- [x] No changes to functionality - pure code organization refactor
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
fixes#23901
### How did you verify your code works?
with a test
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Fixes a bug where `bun update --interactive` only updated `package.json`
but didn't actually install the updated packages. Users had to manually
run `bun install` afterwards.
## Root Cause
The bug was in `savePackageJson()` in
`src/cli/update_interactive_command.zig`:
1. The function wrote the updated `package.json` to disk
2. But it **didn't update the in-memory cache**
(`WorkspacePackageJSONCache`)
3. When `installWithManager()` ran, it called `getWithPath()` which
returned the **stale cached version**
4. So the installation proceeded with the old dependencies
## The Fix
Update the cache entry after writing to disk (line 116):
```zig
package_json.*.source.contents = new_package_json_source;
```
This matches the behavior in `updatePackageJSONAndInstall.zig` line 269.
## Test Plan
Added comprehensive regression tests in
`test/cli/update_interactive_install.test.ts`:
- ✅ Verifies that `package.json` is updated
- ✅ Verifies that `node_modules` is updated (this was failing before the
fix)
- ✅ Tests both normal update and `--latest` flag
- ✅ Compares installed version to confirm packages were actually
installed
Run tests with:
```bash
bun bd test test/cli/update_interactive_install.test.ts
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
Adds a `subscriptions` getter to `ServerWebSocket` that returns an array
of all topics the WebSocket is currently subscribed to.
## Implementation
- Added `getTopicsCount()` and `iterateTopics()` helpers to uWS
WebSocket
- Implemented C++ function `uws_ws_get_topics_as_js_array` that:
- Uses `JSC::MarkedArgumentBuffer` to protect values from GC
- Constructs JSArray directly in C++ for efficiency
- Uses template pattern for SSL/TCP variants
- Properly handles iterator locks with explicit scopes
- Exposed as `subscriptions` getter property on ServerWebSocket
- Returns empty array when WebSocket is closed (not null)
## API
```typescript
const server = Bun.serve({
websocket: {
open(ws) {
ws.subscribe("chat");
ws.subscribe("notifications");
console.log(ws.subscriptions); // ["chat", "notifications"]
ws.unsubscribe("chat");
console.log(ws.subscriptions); // ["notifications"]
}
}
});
```
## Test Coverage
Added 5 comprehensive test cases covering:
- Basic subscription/unsubscription flow
- All subscriptions removed
- Behavior after WebSocket close
- Duplicate subscriptions (should only appear once)
- Multiple subscribe/unsubscribe cycles
All tests pass with 24 assertions.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Allows optional peers to resolve to package if possible.
Optional peers aren't auto-installed, but they should still be given a
chance to resolve. If they're always left unresolved it's possible for
multiple dependencies on the same package to result in different peer
resolutions when they should be the same. For example, this bug this
could cause monorepos using elysia to have corrupt node_modules because
there might be more than one copy of elysia in `node_modules/.bun` (or
more than the expected number of copies).
fixes#23725
most likely fixes#23895
fixes ENG-21411
### How did you verify your code works?
Added a test for optional peers and non-optional peers that would
previously trigger this bug.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **New Features**
* Improved resolution of optional peer dependencies during isolated
installations, with better propagation across package hierarchies.
* **Tests**
* Added comprehensive test suite covering optional peer dependency
scenarios in isolated workspaces.
* Added test fixtures for packages with peer and optional peer
dependencies.
* Enhanced lockfile migration test verification using snapshot-based
assertions.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
When `napi_create_external_buffer` receives empty input, the returned
buffer should be detached.
This fixes the remaining tests in `ref-napi` other than three that use a
few uv symbols
<img width="329" height="159" alt="Screenshot 2025-11-01 at 8 38 01 PM"
src="https://github.com/user-attachments/assets/2c75f937-79c5-467a-bde3-44e45e05d9a0"
/>
### How did you verify your code works?
Added tests for correct values from `napi_get_buffer_info`,
`napi_get_arraybuffer_info`, and `napi_is_detached_arraybuffer` when
given an empty buffer from `napi_create_external_buffer`
---------
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
Adds comprehensive documentation explaining how Bun's event loop works,
including task draining, microtasks, process.nextTick, and I/O polling
integration.
## What does this document?
- **Task draining algorithm**: Shows the exact flow for processing each
task (run → release weak refs → drain microtasks → deferred tasks)
- **Process.nextTick ordering**: Explains batching behavior - all
nextTick callbacks in current batch run, then microtasks drain
- **Microtask integration**: How JavaScriptCore's microtask queue and
Bun's nextTick queue interact
- **I/O polling**: How uSockets epoll/kqueue events integrate with the
event loop
- **Timer ordering**: Why setImmediate runs before setTimeout
- **Enter/Exit mechanism**: How the counter prevents excessive microtask
draining
## Visual aids
Includes ASCII flowcharts showing:
- Main tick flow
- autoTick flow (with I/O polling)
- Per-task draining sequence
## Code references
All explanations include specific file paths and line numbers for
verification:
- `src/bun.js/event_loop/Task.zig`
- `src/bun.js/event_loop.zig`
- `src/bun.js/bindings/ZigGlobalObject.cpp`
- `src/js/builtins/ProcessObjectInternals.ts`
- `packages/bun-usockets/src/eventing/epoll_kqueue.c`
## Examples
Includes JavaScript examples demonstrating:
- nextTick vs Promise ordering
- Batching behavior when nextTick callbacks schedule more nextTicks
- setImmediate vs setTimeout ordering
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
### How did you verify your code works?
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Bug Fixes**
* Improved HTTP connection handling during write failures to ensure more
reliable timeout behavior and connection state management.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
### What does this PR do?
If the input was empty `ArrayBuffer::createFromBytes` would create a
buffer that `JSUint8Array::create` would see as detached, so it would
throw an exception. This would likely cause crashes in `node-addon-api`
because finalize data is freed if `napi_create_external_buffer` fails,
and we already setup the finalizer.
Example of creating empty buffer:
a7f62a4caa/src/binding.cc (L687)fixes#6737fixes#10965fixes#12331fixes#12937fixes#13622
most likely fixes#14822
### How did you verify your code works?
Manually and added tests.
## Summary
Removes the `MemoryReportingAllocator` wrapper and simplifies
`fetch.zig` to use `bun.default_allocator` directly. The
`MemoryReportingAllocator` was wrapping `bun.default_allocator` to track
memory usage for reporting to the VM, but this added unnecessary
complexity and indirection without meaningful benefit.
## Changes
**Deleted:**
- `src/allocators/MemoryReportingAllocator.zig` (96 lines)
**Modified `src/bun.js/webcore/fetch.zig`:**
- Removed `memory_reporter: *bun.MemoryReportingAllocator` field from
`FetchTasklet` struct
- Removed `memory_reporter: *bun.MemoryReportingAllocator` field from
`FetchOptions` struct
- Replaced all `this.memory_reporter.allocator()` calls with
`bun.default_allocator`
- Removed all `this.memory_reporter.discard()` calls (no longer needed)
- Simplified `fetch()` function by removing memory reporter
allocation/wrapping/cleanup code
- Updated `deinit()` and `clearData()` to use `bun.default_allocator`
directly
**Cleanup:**
- Removed `MemoryReportingAllocator` export from `src/allocators.zig`
- Removed `MemoryReportingAllocator` export from `src/bun.zig`
- Removed `bun.MemoryReportingAllocator.isInstance()` check from
`src/safety/alloc.zig`
## Testing
- ✅ Builds successfully with `bun bd`
- All fetch operations now use `bun.default_allocator` directly
## Impact
- **Net -116 lines** of code
- Eliminates allocator wrapper overhead in fetch operations
- Simplifies memory management code
- No functional changes to fetch behavior
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
calling `loadConfigPath` could allow loading bunfig more than once.
### How did you verify your code works?
manually
---------
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
This PR makes `bun list` an alias for `bun pm ls`, allowing users to
list their dependency tree with a shorter command.
## Changes
- Updated `src/cli.zig` to route `list` command to
`PackageManagerCommand` instead of `ReservedCommand`
- Modified `src/cli/package_manager_command.zig` to detect when `bun
list` is invoked directly and treat it as `ls`
- Updated help text in `bun pm --help` to show both `bun list` and `bun
pm ls` as valid options
## Implementation Details
The implementation follows the same pattern used for `bun whoami`, which
is also a direct alias to a pm subcommand. When `bun list` is detected,
it's internally converted to the `ls` subcommand.
## Testing
Tested locally:
- ✅ `bun list` shows the dependency tree
- ✅ `bun list --all` works correctly with the `--all` flag
- ✅ `bun pm ls` continues to work (backward compatible)
## Test Output
```bash
$ bun list
/tmp/test-bun-list node_modules (3)
└── react@18.3.1
$ bun list --all
/tmp/test-bun-list node_modules
├── js-tokens@4.0.0
├── loose-envify@1.4.0
└── react@18.3.1
$ bun pm ls
/tmp/test-bun-list node_modules (3)
└── react@18.3.1
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Fixes CPU profiler generating invalid timestamps that Chrome DevTools
couldn't parse (though VSCode's profiler viewer accepted them).
## The Problem
CPU profiles generated by `--cpu-prof` had timestamps that were either:
1. Negative (in the original broken profile from the gist)
2. Truncated/corrupted (after initial timestamp calculation fix)
Example from the broken profile:
```json
{
"startTime": -822663297,
"endTime": -804820609
}
```
After initial fix, timestamps were positive but still wrong:
```json
{
"startTime": 1573519100, // Should be ~1761784720948727
"endTime": 1573849434
}
```
## Root Cause
**Primary Issue**: `WTF::JSON::Object::setInteger()` has precision
issues with large values (> 2^31). When setting timestamps like
`1761784720948727` (microseconds since Unix epoch - 16 digits), the
method was truncating/corrupting them.
**Secondary Issue**: The timestamp calculation logic needed
clarification - now explicitly uses the earliest sample's wall clock
time as startTime and calculates a consistent wallClockOffset.
## The Fix
### src/bun.js/bindings/BunCPUProfiler.cpp
Changed from `setInteger()` to `setDouble()` for timestamp
serialization:
```cpp
// Before (broken):
json->setInteger("startTime"_s, static_cast<long long>(startTime));
json->setInteger("endTime"_s, static_cast<long long>(endTime));
// After (fixed):
json->setDouble("startTime"_s, startTime);
json->setDouble("endTime"_s, endTime);
```
JSON `Number` type can precisely represent integers up to 2^53 (~9
quadrillion), which is far more than needed for microsecond timestamps
(~10^15 for current dates).
Also clarified the timestamp calculation to use `wallClockStart`
directly as the profile's `startTime` and calculate a `wallClockOffset`
for converting stopwatch times to wall clock times.
### test/cli/run/cpu-prof.test.ts
Added validation that timestamps are:
- Positive
- In microseconds (> 1000000000000000, < 3000000000000000)
- Within valid Unix epoch range
## Testing
```bash
bun bd test test/cli/run/cpu-prof.test.ts
```
All tests pass ✅
Generated profile now has correct timestamps:
```json
{
"startTime": 1761784720948727.2,
"endTime": 1761784721305814
}
```
## Why VSCode Worked But Chrome DevTools Didn't
- **VSCode**: Only cares about relative timing (duration = endTime -
startTime), doesn't validate absolute timestamp ranges
- **Chrome DevTools**: Expects timestamps in microseconds since Unix
epoch (positive, ~16 digits), fails validation when timestamps are
negative, too small, or out of valid range
## References
- Gist with CPU profile format documentation:
https://gist.github.com/Jarred-Sumner/2c12da481845e20ce6a6175ee8b05a3e
- Chrome DevTools Protocol - Profiler:
https://chromedevtools.github.io/devtools-protocol/tot/Profiler/🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Implements the `--cpu-prof` CLI flag for Bun to profile CPU usage and
save results in Chrome CPU Profiler JSON format, compatible with Chrome
DevTools and VSCode.
## Implementation Details
- Uses JSC's `SamplingProfiler` to collect CPU samples during execution
- Converts samples to Chrome CPU Profiler JSON format on exit
- Supports `--cpu-prof-name` to customize output filename
- Supports `--cpu-prof-dir` to specify output directory
- Default filename: `CPU.YYYYMMDD.HHMMSS.PID.0.001.cpuprofile`
## Key Features
✅ **Chrome DevTools Compatible** - 100% compatible with Node.js CPU
profile format
✅ **Absolute Timestamps** - Uses wall clock time (microseconds since
epoch)
✅ **1ms Sampling** - Matches Node.js sampling frequency for comparable
granularity
✅ **Thread-Safe** - Properly shuts down background sampling thread
before processing
✅ **Memory-Safe** - Uses HeapIterationScope and DeferGC for safe heap
access
✅ **Cross-Platform** - Compiles on Windows, macOS, and Linux with proper
path handling
## Technical Challenges Solved
1. **Heap Corruption** - Fixed by calling `profiler->shutdown()` before
processing traces
2. **Memory Safety** - Added `HeapIterationScope` and `DeferGC` when
accessing JSCells
3. **Timestamp Accuracy** - Explicitly start stopwatch and convert to
absolute wall clock time
4. **Path Handling** - Used `bun.path.joinAbsStringBufZ` with proper cwd
resolution
5. **Windows Support** - UTF-16 path conversion for Windows
compatibility
6. **Atomic Writes** - Used `bun.sys.File.writeFile` with ENOENT retry
## Testing
All tests pass (4/4):
- ✅ Generates profile with default name
- ✅ `--cpu-prof-name` sets custom filename
- ✅ `--cpu-prof-dir` sets custom directory
- ✅ Profile captures function names
Verified format compatibility:
- JSON structure matches Node.js exactly
- All samples reference valid nodes
- Timestamps use absolute microseconds since epoch
- Cross-platform compilation verified with `bun run zig:check-all`
## Example Usage
```bash
# Basic usage
bun --cpu-prof script.js
# Custom filename
bun --cpu-prof --cpu-prof-name my-profile.cpuprofile script.js
# Custom directory
bun --cpu-prof --cpu-prof-dir ./profiles script.js
```
Output can be opened in Chrome DevTools (Performance → Load Profile) or
VSCode's CPU profiling viewer.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
This PR improves snapshot error messages when running tests in CI
environments to make debugging easier by showing exactly what snapshot
was being created and what value was attempted.
## Changes
### 1. Inline Snapshot Errors
**Before:**
```
Updating inline snapshots is disabled in CI environments unless --update-snapshots is used.
```
**After:**
```
Inline snapshot creation is not allowed in CI environments unless --update-snapshots is used.
If this is not a CI environment, set the environment variable CI=false to force allow.
Received: this is new
```
- Changed message to say "creation" instead of "updating" (more
accurate)
- Shows the received value that was attempted using Jest's pretty
printer
### 2. Snapshot File Errors
**Before:**
```
Snapshot creation is not allowed in CI environments unless --update-snapshots is used
If this is not a CI environment, set the environment variable CI=false to force allow.
Received: this is new
```
**After:**
```
Snapshot creation is not allowed in CI environments unless --update-snapshots is used
If this is not a CI environment, set the environment variable CI=false to force allow.
Snapshot name: "new snapshot 1"
Received: this is new
```
- Now shows the snapshot name that was being looked for
- Shows the received value using Jest's pretty printer
## Implementation Details
- Added `last_error_snapshot_name` field to `Snapshots` struct to pass
snapshot name from `getOrPut()` to error handler
- Removed unreachable code path for inline snapshot updates (mismatches
error earlier with diff)
- Updated test expectations in `ci-restrictions.test.ts`
## Test Plan
```bash
# Test inline snapshot creation in CI
cd /tmp/snapshot-test
echo 'import { test, expect } from "bun:test";
test("new inline snapshot", () => {
expect("this is new").toMatchInlineSnapshot();
});' > test.js
GITHUB_ACTIONS=1 bun test test.js
# Test snapshot file creation in CI
echo 'import { test, expect } from "bun:test";
test("new snapshot", () => {
expect("this is new").toMatchSnapshot();
});' > test2.js
GITHUB_ACTIONS=1 bun test test2.js
```
Both should show improved error messages with the received values and
snapshot name.
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: pfg <pfg@pfg.pw>
## Summary
Fixed two bugs in the auto-close-duplicates bot:
- **Respect 👎 reactions from ANY user**: Previously only the issue
author's thumbs down would prevent auto-closing. Now any user can
indicate disagreement with the duplicate detection.
- **Don't re-close reopened issues**: The bot now checks if an issue was
previously reopened and skips auto-closing to respect user intent.
## Changes
1. Modified `fetchAllReactions` call to check all reactions, not just
the author's
2. Changed `authorThumbsDown` logic to `hasThumbsDown` (checks any
user's reaction)
3. Added `wasIssueReopened()` function to query issue events timeline
4. Added check to skip issues with "reopened" events in their history
## Test plan
- [ ] Manually test the script doesn't close issues with 👎 reactions
from non-authors
- [ ] Verify reopened issues are not auto-closed again
- [ ] Check that legitimate duplicates without objections still get
closed properly
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Fix the source index bounds check in `src/sourcemap/Mapping.zig` to
correctly validate indices against the range `[0, sources_count)`.
## Changes
- Changed the bounds check condition from `source_index > sources_count`
to `source_index >= sources_count` on line 452
- This prevents accepting `source_index == sources_count`, which would
be out of bounds when indexing into the sources array
## Test plan
- [x] Built successfully with `bun bd`
- The existing test suite should continue to pass
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Fixes#24147
- Fixed EventEmitter crash when `removeAllListeners()` is called from
within an event handler while a `removeListener` meta-listener is
registered
- Added undefined check before iterating over listeners array to match
Node.js behavior
- Added comprehensive regression tests
## Bug Description
When `removeAllListeners(type)` was called:
1. From within an event handler
2. While a `removeListener` meta-listener was registered
3. For an event type with no listeners
It would crash with: `TypeError: undefined is not an object (evaluating
'this._events')`
## Root Cause
The `removeAllListeners` function tried to access `listeners.length`
without checking if `listeners` was defined first. When called with an
event type that had no listeners, `events[type]` returned `undefined`,
causing the crash.
## Fix
Added a check `if (listeners !== undefined)` before iterating, matching
the behavior in Node.js core:
https://github.com/nodejs/node/blob/main/lib/events.js#L768
## Test plan
- ✅ Created regression test in `test/regression/issue/24147.test.ts`
- ✅ Verified test fails with `USE_SYSTEM_BUN=1 bun test` (reproduces
bug)
- ✅ Verified test passes with `bun bd test` (confirms fix)
- ✅ Test covers the exact reproduction case from the issue
- ✅ Additional tests for edge cases (actual listeners, nested calls)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Fixes the comparator function in `src/sourcemap/Mapping.zig` to use
strict weak ordering as required by sort algorithms.
## Changes
- Changed `<=` to `<` in the column comparison to ensure strict ordering
- Refactored the comparator to use clearer if-statement structure
- Added index comparison as a tiebreaker for stable sorting when both
line and column positions are equal
## Problem
The original comparator used `<=` which would return true for equal
elements, violating the strict weak ordering requirement. This could
lead to undefined behavior in sorting.
**Before:**
```zig
return a.lines.zeroBased() < b.lines.zeroBased() or (a.lines.zeroBased() == b.lines.zeroBased() and a.columns.zeroBased() <= b.columns.zeroBased());
```
**After:**
```zig
if (a.lines.zeroBased() != b.lines.zeroBased()) {
return a.lines.zeroBased() < b.lines.zeroBased();
}
if (a.columns.zeroBased() != b.columns.zeroBased()) {
return a.columns.zeroBased() < b.columns.zeroBased();
}
return a_index < b_index;
```
## Test plan
- [x] Verified compilation with `bun bd`
- The sort now properly follows strict weak ordering semantics
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
This PR refactors the sourcemap module by extracting large structs from
`src/sourcemap/sourcemap.zig` into their own dedicated files, improving
code organization and maintainability.
## Changes
- **Extracted `ParsedSourceMap` struct** to
`src/sourcemap/ParsedSourceMap.zig`
- Made `SourceContentPtr` and related methods public
- Made `standaloneModuleGraphData` public for external access
- **Extracted `Chunk` struct** to `src/sourcemap/Chunk.zig`
- Added import for `appendMappingToBuffer` from parent module
- Includes all nested types: `VLQSourceMap`, `NewBuilder`, `Builder`
- **Extracted `Mapping` struct** to `src/sourcemap/Mapping.zig`
- Added necessary imports: `assert`, `ParseResult`, `debug`
- Includes nested types: `MappingWithoutName`, `List`, `Lookup`
- **Updated `src/sourcemap/sourcemap.zig`**
- Replaced struct definitions with imports:
`@import("./StructName.zig")`
- Maintained all public APIs
All structs now follow the `const StructName = @This()` pattern for
top-level declarations.
## Testing
- ✅ Compiled successfully with `bun bd`
- ✅ All existing functionality preserved
- ✅ No API changes - fully backwards compatible
## Before
- Single 2000+ line file with multiple large structs
- Difficult to navigate and maintain
## After
- Modular structure with separate files for each major struct
- Easier to find and modify specific functionality
- Better code organization
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Should fix https://github.com/oven-sh/bun/issues/24104
### What does this PR do?
This PR is changing `ERR_BODY_ALREADY_USED` to be TypeError instead of
Error.
### How did you verify your code works?
A test case added to verify that request call correctly throws a
TypeError after another request call on the same Request, confirming the
fix addresses the issue.
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Fixes#19111
This PR fixes a bug where `fs.createReadStream().pipe(ServerResponse)`
would fail to transfer data when ServerResponse had no handle
(standalone usage). This affected Vite's static file serving and other
middleware adapters using the connect-to-web pattern.
## Root Cause
The bug was in the `ServerResponse.writableNeedDrain` getter at line
1529 of `_http_server.ts`:
```typescript
return !this.destroyed && !this.finished && (this[kHandle]?.bufferedAmount ?? 1) !== 0;
```
When `ServerResponse` had no handle (which is common in middleware
scenarios), the nullish coalescing operator defaulted `bufferedAmount`
to **1** instead of **0**. This caused `writableNeedDrain` to always
return `true`.
## Impact
When `pipe()` checks `dest.writableNeedDrain === true`, it immediately
pauses the source stream to handle backpressure. With the bug,
standalone ServerResponse instances always appeared to need draining,
causing piped streams to pause and never resume.
## Fix
Changed the default value from `1` to `0`:
```typescript
return !this.destroyed && !this.finished && (this[kHandle]?.bufferedAmount ?? 0) !== 0;
```
## Test Plan
- ✅ Added regression test in `test/regression/issue/19111.test.ts`
- ✅ Verified fix with actual Vite middleware reproduction
- ✅ Confirmed behavior matches Node.js
Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Refactors `Subprocess` to use explicit strong/weak reference management
via `JSRef` instead of the `hasPendingActivity` mechanism that relies on
JSC's internal `WeakHandleOwner`.
## Changes
### Core Refactoring
- **JSRef.zig**: Added `update()` method to update references in-place
- **subprocess.zig**: Changed `this_jsvalue: JSValue` to `this_value:
JSRef`
- **subprocess.zig**: Renamed `hasPendingActivityNonThreadsafe()` to
`computeHasPendingActivity()`
- **subprocess.zig**: Updated `updateHasPendingActivity()` to
upgrade/downgrade `JSRef` based on pending activity
- **subprocess.zig**: Removed `hasPendingActivity()` C callback function
- **subprocess.zig**: Updated `finalize()` to call
`this_value.finalize()`
- **BunObject.classes.ts**: Set `hasPendingActivity: false` for
Subprocess
- **Writable.zig**: Updated references from `this_jsvalue` to
`this_value.tryGet()`
- **ipc.zig**: Updated references from `this_jsvalue` to
`this_value.tryGet()`
## How It Works
**Before**: Used `hasPendingActivity: true` which created a `JSC::Weak`
reference with a `JSC::WeakHandleOwner` that kept the object alive as
long as the C callback returned true.
**After**: Uses `JSRef` with explicit lifecycle management:
1. Starts with a **weak** reference when subprocess is created
2. Immediately calls `updateHasPendingActivity()` after creation
3. **Upgrades to strong** reference when `computeHasPendingActivity()`
returns true:
- Subprocess hasn't exited
- Has active stdio streams
- Has active IPC connection
4. **Downgrades to weak** reference when all activity completes
5. GC can collect the subprocess once it's weak and no other references
exist
## Benefits
- Explicit control over subprocess lifecycle instead of relying on JSC's
internal mechanisms
- Clearer semantics: strong reference = "keep alive", weak reference =
"can be GC'd"
- Removes dependency on `WeakHandleOwner` callback overhead
## Testing
- ✅ `test/js/bun/spawn/spawn.ipc.test.ts` - All 4 tests pass
- ✅ `test/js/bun/spawn/spawn-stress.test.ts` - All tests pass (100
iterations)
- ⚠️ `test/js/bun/spawn/spawnSync.test.ts` - 3/6 pass (3 pre-existing
timing-based failures unrelated to this change)
Manual testing confirms:
- Subprocess is kept alive without user reference while running
- Subprocess can be GC'd after completion
- IPC keeps subprocess alive correctly
- No crashes or memory leaks
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
exploratory look into https://github.com/oven-sh/bun/issues/1524
this still leaves that far off from being closed but an important first
step
this is important because this script is used to spawn our base images
for CI and will provide boxes for local testing
not sure how far i'll get but a rough "road to freebsd" map for anyone
reading:
- [x] this
- [ ] ensure `bootstrap.sh` can run successfully
- [ ] ensure WebKit can build from source
- [ ] ensure other dependencies can build from source
- [ ] add freebsd to our WebKit fork releases
- [ ] add freebsd to our Zig fork releases
- [ ] ensure bun can build from source
- [ ] run `[build images]` and add freebsd to CI
- [ ] fix runtime test failures
<img width="2072" height="956" alt="image"
src="https://github.com/user-attachments/assets/ea1acf45-b746-4ffa-8043-be674b87bb60"
/>
## Summary
- Adds detailed documentation explaining JSRef's intended usage
- Includes a complete example showing common patterns
- Explains the three states (weak, strong, finalized)
- Provides guidelines on when to use strong vs weak references
- References real examples from the codebase (ServerWebSocket,
UDPSocket, MySQLConnection, ValkeyClient)
## Motivation
JSRef is a critical type for managing JavaScript object references from
native code, but it lacked comprehensive documentation explaining its
usage patterns and lifecycle management. This makes it clearer how to
properly use JSRef to:
- Safely maintain references to JS objects from native code
- Control whether references prevent garbage collection
- Manage the upgrade/downgrade pattern based on object activity
## Test plan
Documentation-only change, no functional changes.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Previously, `JSC__JSPromise__wrap` would call
`JSC::JSPromise::resolvedPromise(globalObject, result)` without checking
if an exception was thrown during promise resolution. This
could happen in certain edge cases, such as when the result value is a
thenable that triggers stack overflow, or when the promise resolution
mechanism itself encounters an error.
When such exceptions occurred, they would escape back to the Zig code,
causing the CatchScope assertion to fail with "ASSERTION FAILED:
Unexpected exception observed on thread"
instead of being properly handled.
This PR adds an exception check immediately after calling
`JSC::JSPromise::resolvedPromise()` and before the `RELEASE_AND_RETURN`
macro. If an exception is detected, the function
now clears it and returns a rejected promise with the exception value,
ensuring consistent error handling behavior. This matches the pattern
already used earlier in the function
for the initial function call exception handling.
### How did you verify your code works?
new and existing tests
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Fixes#23133
This PR fixes a bug where lifecycle hooks (`beforeAll`, `beforeEach`,
`afterAll`, `afterEach`) would throw an error when called with a
function and options object:
```typescript
beforeAll(() => {
console.log("beforeAll")
}, { timeout: 10_000 })
```
Previously, this would throw: `error: beforeAll() expects a function as
the second argument`
## Root Cause
The issue was in `ScopeFunctions.parseArguments()` at
`src/bun.js/test/ScopeFunctions.zig:342`. When parsing two arguments, it
always treated them as `(description, callback)` instead of checking if
they could be `(callback, options)`.
## Solution
Updated the two-argument parsing logic to check if the first argument is
a function and the second is not a function. In that case, treat them as
`(callback, options)` instead of `(description, callback)`.
## Changes
- Modified `src/bun.js/test/ScopeFunctions.zig` to handle `(callback,
options)` case
- Added regression test at `test/regression/issue/23133.test.ts`
## Testing
✅ Verified the fix works with the reproduction case from the issue
✅ Added comprehensive regression test covering all lifecycle hooks with
both object and numeric timeout options
✅ All existing jest-hooks tests still pass
✅ Test fails with `USE_SYSTEM_BUN=1` and passes with the fixed build
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: pfg <pfg@pfg.pw>
## Summary
Fixes#20689
Previously, `@layer` blocks were not being processed through the CSS
minifier, which meant that `color-scheme` properties inside `@layer`
blocks would not get the required `--buncss-light`/`--buncss-dark`
variable injections needed for browsers that don't support the
`light-dark()` function.
## Changes
- Implemented proper minification for `LayerBlockRule` in
`src/css/rules/rules.zig:218-221`
- Added recursive call to `minify()` on nested rules, matching the
behavior of other at-rules like `@media` and `@supports`
- Added comprehensive tests for `color-scheme` inside `@layer` blocks
## Test Plan
Added three new test cases in `test/js/bun/css/css.test.ts`:
1. Simple `@layer` with `color-scheme: dark`
2. Named layers (`@layer shm.colors`) with multiple rules
3. Anonymous `@layer` with `color-scheme: light dark` (generates media
query)
All tests pass:
```bash
bun bd test test/js/bun/css/css.test.ts -t "color-scheme"
```
## Before
```css
/* Input */
@layer shm.colors {
body.theme-dark {
color-scheme: dark;
}
}
/* Output (broken - no variables) */
@layer shm.colors {
body.theme-dark {
color-scheme: dark;
}
}
```
## After
```css
/* Input */
@layer shm.colors {
body.theme-dark {
color-scheme: dark;
}
}
/* Output (fixed - variables injected) */
@layer shm.colors {
body.theme-dark {
--buncss-light: ;
--buncss-dark: initial;
color-scheme: dark;
}
}
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Implements `onTestFinished()` for `bun:test`, which runs after all
`afterEach` hooks have completed.
## Implementation
- Added `onTestFinished` export to the test module in `jest.zig`
- Modified `genericHook` in `bun_test.zig` to handle `onTestFinished` as
a special case that:
- Can only be called inside a test (not in describe blocks or preload)
- Appends hooks at the very end of the execution sequence
- Added comprehensive tests covering basic ordering, multiple callbacks,
async callbacks, and interaction with other hooks
## Execution Order
When called inside a test:
1. Test body executes
2. `afterAll` hooks (if added inside the test)
3. `afterEach` hooks
4. `onTestFinished` hooks ✨
## Test Plan
- ✅ All new tests pass with `bun bd test`
- ✅ Tests correctly fail with `USE_SYSTEM_BUN=1` (feature not in
released version)
- ✅ Verifies correct ordering with `afterEach`, `afterAll`, and multiple
`onTestFinished` calls
- ✅ Tests async `onTestFinished` callbacks
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: pfg <pfg@pfg.pw>
### What does this PR do?
This PR adds documentation comments to `src/env_var.zig` that explain
the silent error handling behavior for environment variable
deserialization, based on the documentation from the closed PR #24036.
The comments clarify:
1. **Module-level documentation**: Environment variables may fail to
parse silently. When they do, the default behavior is to show a debug
warning and treat them as not set. This is intentional to avoid panics
from environment variable pollution.
2. **Inline documentation**: Deserialization errors cannot panic. Users
needing more robust configuration mechanisms should consider
alternatives to environment variables.
This documentation complements the behavior change introduced in commit
0dd6aa47ea which replaced panic with debug_warn.
### How did you verify your code works?
Ran `bun bd` successfully - the build completed without errors.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
When `process.nextTick` is overwritten, segv will be occured via
internal `processTick` call.
This patch fixes it.
### How did you verify your code works?
Tests.
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
When using `fs.watch()` with `recursive: true`, the callback receives a
relative path from the watched directory (e.g., `'subdir/file.txt'`),
not just a filename.
Renaming the parameter from `filename` to `relativePath` makes this
behavior immediately clear to developers.
**Before:**
```ts
(event, filename) => {
console.log(`Detected ${event} in ${filename}`);
}
```
**After:**
```ts
(event, relativePath) => {
console.log(`Detected ${event} in ${relativePath}`);
}
```
This is a documentation-only change that improves clarity without
altering any functionality.
Co-authored-by: Braden Wong <git@bradenwong.com>
### Description
This PR fixes a crash caused by integer underflow in
`OKPacket.decodeInternal`.
Previously, when `read_size` exceeded `packet_size`, the subtraction
`packet_size - read_size` wrapped around, producing a huge `count` value
passed into `reader.read()`. This led to an integer overflow panic at
runtime.
### What does this PR do
- Added a safe subtraction guard in `decodeInternal` to clamp
`remaining` to `0`
when `read_size >= packet_size`.
- Ensures empty or truncated OK packets no longer cause crashes.
- Behavior for valid packets remains unchanged.
### Impact
Prevents integer overflow panics in MySQL OK packet parsing, improving
stability when handling short or empty responses (e.g., queries that
return no rows or minimal metadata).
### How did you verify your code works?
Tested with proof of concept:
https://github.com/Lillious/Bun-MySql-Integer-Overflow-PoC
---------
Co-authored-by: Ciro Spaciari <ciro.spaciari@gmail.com>
`ZigString.Slice.cloneIfNeeded` does *not* guarantee that the returned
slice will have been allocated by the provided allocator, which makes it
very easy to use this method incorrectly.
(For internal tracking: fixes ENG-21284)
### What does this PR do?
Adds missing null checking for `Bun.CookieMap#delete`.
### How did you verify your code works?
Tests
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
fixes: oven-sh/bun#23717
### What does this PR do?
- Align ProxyTunnel.onClose with
[HTTPClient.onClose](https://github.com/oven-sh/bun/blob/bun-v1.3.0/src/http.zig#L223-L241):
when a tunneled HTTPS response is in-progress and either
- parsing chunked trailers (trailer-line states), or
- transfer-encoding is identity with content_length == null while in
.body,
treat EOF as end-of-message and complete the request, rather than
ECONNRESET.
- Schedule proxy deref instead of deref inside callbacks to avoid
lifetime hazards.
### How did you verify your code works?
- `test/js/bun/http/proxy.test.ts`: raw TLS origin returns
close-delimited 200 OK; verified no ECONNRESET and body delivered.
- Test suite passes under bun bd test.
## Risk/compat
- Only affects CONNECT/TLS path. Direct HTTP/HTTPS unchanged. Behavior
mirrors existing
[HTTPClient.onClose](https://github.com/oven-sh/bun/blob/bun-v1.3.0/src/http.zig#L223-L241).
## Repro (minimal)
See issue; core condition is no Content-Length and no Transfer-Encoding
(close-delimited).
Co-authored-by: Ciro Spaciari <ciro.spaciari@gmail.com>
## Summary
This PR refactors `NapiEnv` to use `bun.ptr.ExternalShared` instead of
manual `ref()`/`deref()` calls, fixing a use-after-free bug in the NAPI
implementation.
## Bug Fixed
The original issue was in `ThreadSafeFunction.deinit()`:
1. `maybeQueueFinalizer()` schedules a task that holds a pointer to
`this` (which includes `this.env`)
2. The task will eventually call `onDispatch()` → `deinit()`
3. But `deinit()` immediately calls `this.env.deref()` before the task
completes
4. This could cause the `NapiEnv` reference count to go to 0 while the
pointer is still in use
## Changes
### Core Changes
- Added `NapiEnv.external_shared_descriptor` and `NapiEnv.EnvRef` type
alias
- Changed struct fields from `*NapiEnv` to `NapiEnv.EnvRef` where
ownership is required:
- `ThreadSafeFunction.env`
- `napi_async_work.env`
- `Finalizer.env` (now `NapiEnv.EnvRef.Optional`)
### API Changes
- Use `.get()` to access the raw `*NapiEnv` pointer from `EnvRef`
- Use `.cloneFromRaw(env)` when storing `env` in long-lived structs
- Use `EnvRef.deinit()` instead of manual `env.deref()`
- Removed manual `env.ref()` calls (now handled automatically by
`cloneFromRaw`)
### Safety Improvements
- Reference counting is now managed by the `ExternalShared` wrapper
- Prevents manual ref/deref mistakes
- Ensures proper cleanup even when operations are cancelled or fail
- No more use-after-free risks from premature deref
## Testing
Built successfully with `bun bd`. NAPI tests pass (66/83 tests, with 17
timeouts that appear to be pre-existing issues).
## Implementation Notes
Following the pattern from `Blob.zig` and `array_buffer.zig`, structs
that own a reference use `NapiEnv.EnvRef`, while functions that only
borrow temporarily continue to use `*NapiEnv` parameters.
The `ExternalShared` interface ensures:
- `.clone()` increments the ref count
- `.deinit()` decrements the ref count
- No direct access to the internal ref/deref functions
This makes the ownership semantics explicit and type-safe.
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: taylor.fish <contact@taylor.fish>
## Summary
Fixes `Buffer.isEncoding('')` to return `false` instead of `true`,
matching Node.js behavior.
## Description
Previously, `Buffer.isEncoding('')` incorrectly returned `true` in Bun,
while Node.js correctly returns `false`. This was caused by
`parseEnumerationFromView` in `JSBufferEncodingType.cpp` treating empty
strings (length 0) as valid utf8 encoding.
The fix modifies the switch statement to return `std::nullopt` for empty
strings, along with other invalid short strings.
## Changes
- Modified `src/bun.js/bindings/JSBufferEncodingType.cpp` to return
`std::nullopt` for empty strings
- Added regression test `test/regression/issue23966.test.ts`
## Test Plan
- [x] Test fails with `USE_SYSTEM_BUN=1 bun test
test/regression/issue23966.test.ts` (confirms bug exists)
- [x] Test passes with `bun bd test test/regression/issue23966.test.ts`
(confirms fix works)
- [x] Verified behavior matches Node.js v24.3.0
- [x] All test cases for valid/invalid encodings pass
Fixes#23966🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Replaces raw napi_env pointers with WTF::Ref<NapiEnv> for improved
memory management and safety. Updates related classes, function
signatures, and finalizer handling to use reference counting. Adds
ref/deref methods to NapiEnv and integrates them in Zig and C++ code
paths, ensuring proper lifecycle management for N-API environments.
### How did you verify your code works?
found with https://github.com/oven-sh/bun/pull/21663 again
case found in `test/js/bun/net/socket.test.ts`
test `"should throw when a socket from a file descriptor has a bad file
descriptor"`
## Summary
Fixed a bug in the Windows bunx fast path code where UTF-8 byte length
was incorrectly used instead of UTF-16 code unit length when calculating
buffer offsets.
## Details
In `run_command.zig:1565`, the code was using `target_name.len` (UTF-8
byte length) instead of `encoded.len` (UTF-16 code unit length) when
calculating the total path length. This caused an index out of bounds
panic when package names contained multi-byte UTF-8 characters.
**Example scenario:**
- Package name contains character "中" (U+4E2D)
- UTF-8: 3 bytes (0xE4 0xB8 0xAD) → `target_name.len` counts as 3
- UTF-16: 1 code unit (0x4E2D) → `encoded.len` counts as 1
- Using the wrong length led to: `panic: index out of bounds: index 62,
len 60`
## Changes
- Changed line 1565 from `target_name.len` to `encoded.len`
## Test plan
- [x] Build compiles successfully
- [x] Code review confirms the fix addresses the root cause
- [ ] Windows-specific testing (if available)
Fixes the panic reported in Sentry/crash reports.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
toSlice has a bug
### How did you verify your code works?
---------
Co-authored-by: taylor.fish <contact@taylor.fish>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
`bun.String.toOwnedSliceReturningAllASCII` is supposed to return a
boolean indicating whether or not the string is entirely composed of
ASCII characters. However, the current implementation frequently
produces incorrect results:
* If the string is a `ZigString`, it always returns true, even though
`ZigString`s can be UTF-16 or Latin-1.
* If the string is a `StaticZigString`, it always returns false, even
though `StaticZigStrings` can be all ASCII.
* If the string is a 16-bit `WTFStringImpl`, it always returns false,
even though 16-bit `WTFString`s can be all ASCII.
* If the string is empty, it always returns false, even though empty
strings are valid ASCII strings.
`toOwnedSliceReturningAllASCII` is currently used in two places, both of
which assume its answer is accurate:
* `bun.webcore.Blob.fromJSWithoutDeferGC`
* `bun.api.ServerConfig.fromJS`
(For internal tracking: fixes ENG-21249)
### What does this PR do?
Adds missing exception check for ReadableStream.
### How did you verify your code works?
Tests
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Fixes a small bug I found in https://github.com/oven-sh/bun/pull/23107
which caused `SlicedString` not to correctly provide us with subslices.
This would have been a **killer** use-case for the interval utility we
decided to reject in https://github.com/oven-sh/bun/pull/23882. Consider
how nice the code could've been:
```zig
pub inline fn sub(this: SlicedString, input: string) SlicedString {
const buf_r = bun.math.interval.fromSlice(this.buf);
const inp_r = bun.math.interval.fromSlice(this.input);
if (Environment.allow_assert) {
if (!buf_r.superset(inp_r)) {
bun.Output.panic("SlicedString.sub input [{}, {}) is not a substring of the " ++
"slice [{}, {})", .{ start_i, end_i, start_buf, end_buf });
}
}
return SlicedString{ .buf = this.buf, .slice = input };
}
```
That's a lot more readable than the middle-school algebra we have here,
but here we are.
### How did you verify your code works?
CI
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
msvc doesn't support c23 yet
### How did you verify your code works?
---------
Co-authored-by: Marko Vejnovic <marko@bun.com>
## Summary
This PR adds a Claude Code-powered issue deduplication system to help
reduce duplicate issues in the Bun repository.
### What's included:
1. **`/dedupe` slash command** (`.claude/commands/dedupe.md`)
- Claude Code command to find up to 3 duplicate issues for a given
GitHub issue
- Uses parallel agent searches with diverse keywords
- Filters out false positives
2. **Automatic dedupe on new issues**
(`.github/workflows/claude-dedupe-issues.yml`)
- Runs automatically when a new issue is opened
- Can also be triggered manually via workflow_dispatch
- Uses the Claude Code base action to run the `/dedupe` command
3. **Auto-close workflow**
(`.github/workflows/auto-close-duplicates.yml`)
- Runs daily to close issues marked as duplicates after 3 days
- Only closes if:
- Issue has a duplicate detection comment from bot
- Comment is 3+ days old
- No comments or activity after duplicate comment
- Author hasn't reacted with 👎 to the duplicate comment
4. **Auto-close script** (`scripts/auto-close-duplicates.ts`)
- TypeScript script that handles the auto-closing logic
- Fetches open issues and checks for duplicate markers
- Closes issues with proper labels and notifications
### How it works:
1. When a new issue is opened, the workflow runs Claude Code to analyze
it
2. Claude searches for duplicates and comments on the issue if any are
found
3. Users have 3 days to respond if they disagree
4. After 3 days with no activity, the issue is automatically closed
### Requirements:
- `ANTHROPIC_API_KEY` secret needs to be set in the repository settings
for the dedupe workflow to run
## Test plan
- [x] Verified workflow files have correct syntax
- [x] Verified script references correct repository (oven-sh/bun)
- [x] Verified slash command matches claude-code implementation
- [ ] Test workflow manually with workflow_dispatch (requires
ANTHROPIC_API_KEY)
- [ ] Monitor initial runs to ensure proper behavior
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Fixes a bug where the `Bun.build()` API with `compile: true` did not
properly apply sourcemaps, even when `sourcemap: "inline"` was
specified. This resulted in error stack traces showing bundled virtual
paths (`/$bunfs/root/`) instead of actual source file names and line
numbers.
## Problem
The CLI `bun build --compile --sourcemap` worked correctly, but the
equivalent API call did not:
```javascript
// This did NOT work (before fix)
await Bun.build({
entrypoints: ['./app.js'],
compile: true,
sourcemap: "inline" // <-- Was ignored/broken
});
```
Error output showed bundled paths:
```
error: Error from helper module
at helperFunction (/$bunfs/root/app.js:4:9) // ❌ Wrong path
at main (/$bunfs/root/app.js:9:17) // ❌ Wrong line numbers
```
## Root Cause
The CLI explicitly overrides any sourcemap type to `.external` when
compile mode is enabled (in `/workspace/bun/src/cli/Arguments.zig`):
```zig
// when using --compile, only `external` works
if (ctx.bundler_options.compile) {
opts.source_map = .external;
}
```
The API implementation in `JSBundler.zig` was missing this override.
## Solution
Added the same sourcemap override logic to `JSBundler.zig` when compile
mode is enabled:
```zig
// When using --compile, only `external` sourcemaps work, as we do not
// look at the source map comment. Override any other sourcemap type.
if (this.source_map != .none) {
this.source_map = .external;
}
```
Now error output correctly shows source file names:
```
error: Error from helper module
at helperFunction (helper.js:2:9) // ✅ Correct file
at main (app.js:4:3) // ✅ Correct line numbers
```
## Tests
Added comprehensive test coverage in
`/workspace/bun/test/bundler/bun-build-compile-sourcemap.test.ts`:
- ✅ `sourcemap: "inline"` works
- ✅ `sourcemap: true` works
- ✅ `sourcemap: "external"` works
- ✅ Multiple source files show correct file names
- ✅ Without sourcemap, bundled paths are shown (expected behavior)
All tests:
- ✅ Fail with `USE_SYSTEM_BUN=1` (confirms bug exists)
- ✅ Pass with `bun bd test` (confirms fix works)
- ✅ Use `tempDir()` to avoid disk space issues
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Adds support for `publicHoistPattern` in `bunfig.toml` and
`public-hoist-pattern` from `.npmrc`. This setting allows you to select
transitive packages to hoist to the root node_modules making them
available for all workspace packages.
```toml
[install]
# can be a string
publicHoistPattern = "@types*"
# or an array
publicHoistPattern = [ "@types*", "*eslint*" ]
```
`publicHoistPattern` only affects the isolated linker.
---
Adds `hoistPattern`. `hoistPattern` is the same as `publicHoistPattern`,
but applies to the `node_modules/.bun/node_modules` directory instead of
the root node_modules. Also the default value of `hoistPattern` is `*`
(everything is hoisted to `node_modules/.bun/node_modules` by default).
---
Fixes a determinism issue constructing the
`node_modules/.bun/node_modules` directory.
---
closes#23481closes#6160closes#23548
### How did you verify your code works?
Added tests for
- [x] only include patterns
- [x] only exclude patterns
- [x] mix of include and exclude
- [x] errors for unexpected expression types
- [x] excluding direct dependency (should still include)
- [x] match all with `*`
- [x] string and array expression types
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
`short` is signed in C++ by default and not unsigned. Switched to
`uint16_t` so it's unambiguous.
### How did you verify your code works?
There is a test
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Fixes#19652
## Summary
Fixes a crash that occurred when using the `--production` flag with `bun
build`, particularly on Windows where assertions are enabled in release
builds.
## Root Cause
The crash occurred because an assertion for `jsx.development` was
running **before** `jsx.development` was properly configured. The
problematic sequence was:
1. Set `NODE_ENV=production` in env map
2. Call `configureDefines()` which reads `NODE_ENV` and calls
`setProduction(true)`, setting `jsx.development=false`
3. ❌ **Assert `jsx.development` is false** (assertion fired here, before
line 203 below)
4. Set `jsx.development = !production` on line 203 (too late)
## Changes
This PR reorders the code to move the assertion **after**
`jsx.development` is properly set:
1. Set both `BUN_ENV` and `NODE_ENV` to `"production"` in env map
2. Call `configureDefines()`
3. Set `jsx.development = !production` (now happens first)
4. ✅ **Assert `jsx.development` is false** (now runs after it's set)
Also adds `BUN_ENV=production` to match the behavior of setting
`NODE_ENV`.
## Test Plan
Added regression test in `test/regression/issue/19652.test.ts` that
verifies `bun build --production` doesn't crash.
The test:
- ✅ Passes on this branch
- ❌ Would fail on main (assertion failure)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
### What does this PR do?
Fixes a bug preventing workspace self dependencies from getting
symlinked to the workspace node_modules
Fixes#23605
### How did you verify your code works?
Added a test for normal `"workspace:*"` deps, and `"workspace:."` under
a different name.
---------
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
We read and write this field on multiple threads. Let's add a mutex.
Fixes BUN-MGB
### How did you verify your code works?
---------
Co-authored-by: Ciro Spaciari <ciro.spaciari@gmail.com>
## Summary
Fixed an off-by-one error in buffer allocation for several path module
functions when handling paths longer than `PATH_SIZE` (typically 4096
bytes on most platforms).
## Changes
- `normalizeJS_T`: Added +1 to buffer allocation for null terminator
- `relativeJS_T`: Added +1 to buffer allocation for null terminator
- `toNamespacedPathJS_T`: Added +9 bytes (8 for possible UNC prefix + 1
for null terminator)
## Test plan
- Added tests for `path.normalize()` with paths up to 100,000 characters
- Added tests for `path.relative()` with very long paths
- All existing path tests continue to pass
The issue occurred because when a path is exactly equal to or longer
than `PATH_SIZE`, the buffer was allocated with size equal to the path
length, but then a null terminator was written at `buf[bufSize]`, which
was out of bounds.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
Fixes a panic that occurred when a WebSocket close frame's payload was
split across multiple TCP packets.
## The Bug
The panic occurred at `websocket_client.zig:681`:
```
panic: index out of bounds: index 24, len 14
```
This happened when:
- A close frame had a payload of 24 bytes (2 byte code + 22 byte reason)
- The first TCP packet contained 14 bytes (header + partial payload)
- The code tried to access `data[2..24]` causing the panic
## Root Causes
1. **Bounds checking issue**: The code assumed all close frame data
would arrive in one packet and tried to `@memcpy` without verifying
sufficient data was available.
2. **Premature flag setting**: `close_received = true` was set
immediately upon entering the close state. This prevented `handleData`
from being called again when the remaining bytes arrived (early return
at line 354).
## The Fix
Implemented proper fragmentation handling for close frames, following
the same pattern used for ping frames:
- Added `close_frame_buffering` flag to track buffering state
- Buffer incoming data incrementally using the existing
`ping_frame_bytes` buffer
- Track total expected length and bytes received so far
- Only set `close_received = true` after all bytes are received
- Wait for more data if the frame is incomplete
## Testing
- Created two regression tests that fragment close frames across
multiple packets
- All existing WebSocket tests pass (`test/js/web/websocket/`)
- Verified the original panic no longer occurs
## Related
This appears to be the root cause of crashes reported on Windows when
WebSocket connections close, particularly when close frames have reasons
that get fragmented by the network stack.
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
Let MySQL unref when idle and make sure that is behaving like this.
Only set up the timers after all status changes are complete since the
timers rely on the status to determine timeouts, this was causing the
CPU usage spike to 100% (thats why only happened in TLS)
CPU usage it self will be improved in
https://github.com/oven-sh/bun/pull/23700 not in this PR
Fixes: https://github.com/oven-sh/bun/issues/23273
Fixes: https://github.com/oven-sh/bun/issues/23256
### How did you verify your code works?
Test
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
### What does this PR do?
This PR implements support for the `email` field in `.npmrc` files for
registry scope authentication. Some private registries (particularly
Nexus) require the email field to be specified in the registry
configuration alongside username/password or token authentication.
The email field can now be specified in `.npmrc` files like:
```ini
//registry.example.com/:email=user@example.com
//registry.example.com/:username=myuser
//registry.example.com/:_password=base64encodedpassword
```
### How did you verify your code works?
1. **Built Bun successfully** - Confirmed the code compiles without
errors using `bun bd --debug`
2. **Wrote comprehensive unit tests** - Added two test cases to
`test/cli/install/npmrc.test.ts`:
- Test for standalone email field parsing
- Test for email combined with username/password authentication
3. **Verified tests pass** - Ran `bun bd test
test/cli/install/npmrc.test.ts -t "email"` and confirmed both tests
pass:
```
✓ 2 pass
✓ 0 fail
✓ 6 expect() calls
```
4. **Code changes include**:
- Added `email` field to `NpmRegistry` struct in `src/api/schema.zig`
- Updated `encode()` and `decode()` methods to handle the email field
- Modified `ini.zig` to parse and store the email field from `.npmrc`
- Removed email from the unsupported options warning (certfile and
keyfile remain unsupported)
- Updated all `NpmRegistry` struct initializations to include the email
field
- Updated `loadNpmrcFromJS` test API to return the email field
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Fixes#23489
The YAML parser was incorrectly treating `...` inside double-quoted
strings as document end markers, causing parse errors for strings
containing ellipsis, particularly affecting internationalized text.
### Example of the bug:
```yaml
balance: "👛 لا تمتلك محفظة... !"
```
This would fail with: `error: Unexpected document end`
### Root cause:
The bug was introduced in commit fcbd57ac48 which attempted to optimize
document marker detection by using `self.line_indent == .none` instead
of tracking newlines with a local flag. However, this check was
incomplete - it didn't track whether we had just processed a newline
character.
### The fix:
Restored the `nl` (newline) flag pattern from the single-quoted scanner
and combined it with the `line_indent` check. Document markers `...` and
`---` are now only recognized when **all** of these conditions are met:
1. We're after a newline (`nl == true`)
2. We're at column 0 (`self.line_indent == .none`)
3. Followed by whitespace or EOF
This allows `...` to appear freely in double-quoted strings while still
correctly recognizing actual document end markers at the start of lines.
### How did you verify your code works?
1. Reproduced the original issue from #23489
2. Applied the fix and verified all test cases pass:
- Original Arabic text with emoji: `"👛 لا تمتلك محفظة... !"`
- Various `...` positions: start, middle, end
- Both single and double quotes
- Multiline strings with indented `...` (issue #22392)
3. Created regression test in `test/regression/issue/23489.test.ts`
4. Verified existing YAML tests still pass (514 pass, up from 513)
cc @dylan-conway for review
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
## Summary
Fixes a panic that occurred when passing `NumberObject` or
`BooleanObject` as MySQL query parameters.
**Panic message:** `A JavaScript exception was thrown, but it was
cleared before it could be read.`
## Root Cause
The `FieldType.fromJS` function in `src/sql/mysql/MySQLTypes.zig` was
returning `error.JSError` without throwing a JavaScript exception first
for:
- `NumberObject` (created via `new Number(42)`)
- `BooleanObject` (created via `new Boolean(true)`)
- Non-indexable types
This violated the contract that `error.JSError` means "an exception has
already been thrown and is ready to be taken."
## Call Chain
1. User executes `await sql\`SELECT ${new Number(42)} as value\``
2. `FieldType.fromJS()` detects `.NumberObject` and returns
`error.JSError` without throwing
3. Error propagates to `MySQLQuery.runPreparedQuery()`
4. Code checks `hasException()` → returns false (no exception exists!)
5. Calls `mysqlErrorToJS(globalObject, "...", error.JSError)`
6. `mysqlErrorToJS` tries to `takeException(error.JSError)` but there's
no exception
7. **PANIC**
## Fix
The fix throws a proper exception with a helpful message before
returning `error.JSError`:
- `"Cannot bind NumberObject to query parameter. Use a primitive number
instead."`
- `"Cannot bind BooleanObject to query parameter. Use a primitive
boolean instead."`
- `"Cannot bind this type to query parameter"`
## Test Plan
Added regression tests in `test/js/sql/sql-mysql.test.ts`:
- Test passing `NumberObject` as parameter
- Test passing `BooleanObject` as parameter
Both tests verify that a proper error is thrown instead of crashing.
Verified manually with local MySQL server that:
- ✅ NumberObject now throws proper error (was crashing)
- ✅ BooleanObject now throws proper error (was crashing)
- ✅ Primitive numbers still work correctly
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Adds a new `--only-failures` flag to `bun test` that only displays test
failures, similar to `--dots` but without printing dots for each test.
## Motivation
When running large test suites or in CI environments, users often only
care about test failures. The existing `--dots` reporter reduces
verbosity by showing dots, but still requires visual scanning to find
failures. The `--only-failures` flag provides a cleaner output by
completely suppressing passing tests.
## Changes
- Added `--only-failures` CLI flag in `Arguments.zig`
- Added `only_failures` boolean to the test reporters struct in
`cli.zig`
- Updated test output logic in `test_command.zig` to skip non-failures
when flag is set
- Updated `jest.zig` and `bun_test.zig` to handle the new flag
- Added comprehensive tests in `only-failures.test.ts`
## Usage
```bash
bun test --only-failures
```
Example output (only shows failures):
```
test/example.test.ts:
(fail) failing test
error: expect(received).toBe(expected)
Expected: 3
Received: 2
5 pass
1 skip
2 fail
Ran 8 tests across 1 file.
```
## Test Plan
- Verified `--only-failures` flag only shows failing tests
- Verified normal test output still works without the flag
- Verified `--dots` reporter still works correctly
- Added regression tests with snapshot comparisons
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: pfg <pfg@pfg.pw>
Fixes#23569
## Summary
HTML imports require bundling to work correctly, as they need to process
and transform linked assets (JS/CSS). When `--no-bundle` is used, no
bundling or transformation happens, which causes a crash.
This change adds validation to detect HTML entrypoints when
`--no-bundle` is used and provides a clear error message explaining that
"HTML imports are only supported when bundling".
## Changes
- Added validation in `src/cli/build_command.zig` to check for HTML
entrypoints when `--no-bundle` flag is used
- Shows clear error message: "HTML imports are only supported when
bundling"
- Added regression tests in `test/regression/issue/23569.test.ts`
## Test Plan
### Before
```bash
$ bun build ./index.html --no-bundle
# Crashes without helpful error
```
### After
```bash
$ bun build ./index.html --no-bundle
error: HTML imports are only supported when bundling
```
### Tests
- ✅ Test with `--no-bundle` flag errors correctly
- ✅ Test with `--no-bundle --outdir` errors correctly
- ✅ Test without `--no-bundle` works normally
- ✅ All 3 regression tests pass
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Fixes#23521
### How did you verify your code works?
Added 3 previously failing tests for `"bin"`, `"directories.bin"`, and
deduplicating entry in both `"bin.directories"` and `"files"`
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Fixes two critical bugs in Bun Shell:
1. **Memory leaks & incorrect GC reporting**: Shell objects weren't
reporting their memory usage to JavaScriptCore's garbage collector,
causing memory to accumulate unchecked. Also fixes a leak where
`ShellArgs` wasn't being freed in `Interpreter.finalize()`.
2. **Blocking I/O on macOS**: Fixes a bug where writing large amounts of
data (>1MB) to pipes would block the main thread on macOS. The issue:
`sendto()` with `MSG_NOWAIT` flag blocks on macOS despite the flag, so
we now avoid the socket fast path unless the socket is already
non-blocking.
## Changes
- Adds `memoryCost()` and `estimatedSize()` implementations across shell
AST nodes, interpreter, and I/O structures
- Reports estimated memory size to JavaScriptCore GC via
`vm.heap.reportExtraMemoryAllocated()`
- Fixes missing `this.args.deinit()` call in interpreter finalization
- Fixes `BabyList.memoryCost()` to return bytes, not element count
- Conditionally uses socket fast path in IOWriter based on platform and
socket state
## Test plan
- [x] New test: `shell-leak-args.test.ts` - validates memory doesn't
leak during parsing/execution
- [x] New test: `shell-blocking-pipe.test.ts` - validates large pipe
writes don't block the main thread
- [x] Existing shell tests pass
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
## Summary
Adds debug logging that prints the name of each test when it starts
running, controlled by the `BUN_DEBUG_jest=1` environment variable.
## Changes
- Modified `src/bun.js/test/Execution.zig` to add logging in the
`onEntryStarted()` function
- Added a scoped logger using `bun.Output.scoped(.jest, .visible)`
- When `BUN_DEBUG_jest=1` is set, prints: `[jest] Running test: <test
name>`
## Testing
Manually tested with various test files:
**Without BUN_DEBUG_jest:**
```
$ bun bd test /tmp/test-jest-log.test.ts
bun test v1.3.1 (642d04b9)
3 pass
0 fail
3 expect() calls
Ran 3 tests across 1 file. [2.90s]
```
**With BUN_DEBUG_jest=1:**
```
$ BUN_DEBUG_jest=1 bun bd test /tmp/test-jest-log.test.ts
bun test v1.3.1 (642d04b9)
[jest] Running test: first test
[jest] Running test: second test
[jest] Running test: third test
3 pass
0 fail
3 expect() calls
Ran 3 tests across 1 file. [2.77s]
```
Also tested with nested describe blocks and all test names are logged
correctly.
## Notes
- This feature is only available in debug builds (not release builds)
- No tests were added as this is a debug-only feature
- Helps with debugging test execution flow and understanding when tests
start running
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: pfg <pfg@pfg.pw>
## Summary
Fixes a panic that occurred when formatting deeply nested objects with
many properties in test output.
## Problem
The `writeIndent()` function in `pretty_format.zig:648` performed
`written * 2` which triggered integer overflow checking in debug builds
when formatting complex nested structures.
**Original crash:**
```
panic: integer overflow
writeIndent at bun.js/test/pretty_format.zig:648
```
**Platform:** Windows x86_64_baseline, Bun v1.3.0
## Solution
Changed from:
```zig
try writer.writeAll(buf[0 .. written * 2]);
```
To:
```zig
const byte_count = @min(buf.len, written *% 2);
try writer.writeAll(buf[0..byte_count]);
```
- Used wrapping multiplication (`*%`) to prevent overflow panic
- Added bounds checking with `@min(buf.len, ...)` for safety
- Maintains correct behavior while preventing crashes
## Test
Added regression test at
`test/js/bun/test/pretty-format-overflow.test.ts` that:
- Creates deeply nested objects (500 levels with 50 properties each)
- Verifies no panic/overflow/crash occurs when formatting
- Uses exact configuration that triggered the original crash
## Verification
- ✅ Test passes with the fix
- ✅ Test would crash without the fix (in debug builds)
- ✅ No changes to behavior, only safety improvement
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
Fixes printing `import.meta.url` and others with `--bytecode`. Fixes
#14954.
Fixes printing `__toESM` when output module format is CJS and input
module format is ESM.
The key change is that `__toESM`'s `isNodeMode` parameter now depends on
the **input module type** (whether the importing file uses ESM syntax
like `import`/`export`) rather than the output format. This matches
Node.js ESM behavior where importing CommonJS from `.mjs` files always
wraps the entire `module.exports` object as the default export, ignoring
`__esModule` markers.
### How did you verify your code works?
Added comprehensive test suite in `test/bundler/bundler_cjs.test.ts`
with **23 tests** covering:
#### Core Behaviors:
- ✅ Files using `import` syntax always get `isNodeMode=1`, which
**ignores `__esModule`** markers and wraps the entire CJS module as
default
- ✅ This matches Node.js ESM semantics for importing CJS from `.mjs`
files
- ✅ Different CJS export patterns (`exports.x`, `module.exports = ...`,
functions, primitives)
- ✅ Named, default, and namespace (`import *`) imports
- ✅ Different targets (node, browser, bun) - all behave the same
- ✅ Different output formats (esm, cjs) - format doesn't affect the
behavior
- ✅ `.mjs` files re-exporting from `.cjs`
- ✅ Deep re-export chains
- ✅ Edge cases (non-boolean `__esModule`, `__esModule=false`, etc.)
#### Test Results:
- **With this PR's changes**: All 23 tests pass ✅
- **Without this PR (system bun)**: 22 pass, 1 fails (the one testing
that `__esModule` is ignored with import syntax + CJS format)
The failing test with system bun demonstrates the bug being fixed:
currently, format=cjs with import syntax still respects `__esModule`,
but it should ignore it (matching Node.js behavior).
---------
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
## Summary
The `EventLoopTimer.Arm` result from `EventLoopTimer.fire()` was being
ignored at both call sites. This PR removes the unused return type and
simplifies the code.
## Changes
- Changed `EventLoopTimer.fire()` to return `void` instead of `Arm`
- Updated all 15 timer callback functions to return `void`
- Removed the `Arm` type definition
- Simplified the `drainTimers()` loop that was ignoring the return value
- Updated both call sites in `Timer.zig`
## Details
The `.rearm` functionality was unused - timers that need to reschedule
themselves (like DNS resolver) handle this by calling
`addTimer()`/`update()` directly rather than relying on the return
value.
This change removes:
- The `Arm` union enum type (3 lines)
- All `return .disarm` and `return .{ .rearm = ... }` statements
- The switch statement in `drainTimers()` that did nothing with the
return value
Net result: **-58 lines** of dead code removed.
## Testing
- [x] Bun builds successfully with `bun bd`
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Fixed an unsigned integer underflow in the bounds check for
`writeBigInt64LE`, `writeBigInt64BE`, `writeBigUInt64LE`, and
`writeBigUInt64BE` methods.
## Problem
When `byteLength < 8`, the bounds check `offset > byteLength - 8` would
cause unsigned integer underflow (since both are `size_t`), resulting in
a large positive number that would pass the check. This allowed
out-of-bounds writes and caused ASAN use-after-poison errors.
**Reproduction:**
```js
const buf = Buffer.from("Hello World");
const slice = buf.slice(0, 5);
slice.writeBigUInt64BE(4096n, 10000); // ASAN error!
```
## Solution
Added an explicit `byteLength < 8` check before the subtraction to
prevent the underflow. The fix is applied to all four functions:
- `writeBigInt64LE` (src/bun.js/bindings/JSBuffer.cpp:2464)
- `writeBigInt64BE` (src/bun.js/bindings/JSBuffer.cpp:2504)
- `writeBigUInt64LE` (src/bun.js/bindings/JSBuffer.cpp:2543)
- `writeBigUInt64BE` (src/bun.js/bindings/JSBuffer.cpp:2582)
## Test plan
- Added comprehensive regression tests covering all edge cases
- Verified the original reproduction case now throws a proper RangeError
instead of crashing
- All tests pass
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
Fixes an assertion failure that occurred when `URLSearchParams.toJSON()`
was called with numeric string keys.
## The Problem
When using numeric string keys (e.g., `"39208"`, `"0"`, `"100"`),
calling `toJSON()` would trigger:
```
ASSERTION FAILED: !parseIndex(propertyName)
cache/webkit-6d0f3aac0b817cc0/include/JavaScriptCore/JSObjectInlines.h:444
```
Reproduction:
```javascript
const params = new URLSearchParams();
params.set("39208", "updated");
params.toJSON(); // crashes
```
## Root Cause
The `getInternalProperties` function in `JSURLSearchParams.cpp` was
using `putDirect()` to add properties to the result object. However,
`putDirect()` cannot be used with property names that can be parsed as
array indices - JSC expects such properties to use indexed storage
instead.
## The Fix
- Replace `putDirect()` with `putDirectMayBeIndex()`, which
automatically handles both regular properties and numeric indices
- Replace `getDirect()` with `get()` to properly retrieve values for
both types of properties
## Test Plan
Added comprehensive tests to `test/js/web/html/URLSearchParams.test.ts`:
- ✅ Single numeric string keys
- ✅ Multiple numeric keys
- ✅ Mixed numeric and non-numeric keys
- ✅ Duplicate numeric keys
- ✅ Extra arguments (original crash case)
All tests pass, and the original crash no longer occurs.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
Fixes#23621.
Note that the quality of this code is quite low, but since Redis is
getting a rewrite, this is a stop-gap. The tests are what really matters
here.
This whole PR is claude.
### How did you verify your code works?
CI.
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Fixes a panic that occurred when `console.log()` tried to format a Set
or Map instance with a non-numeric `size` property.
## Issue
When a Set or Map subclass overrides the `size` property with a
non-numeric value (like a constructor function, string, or other
object), calling `console.log()` on the instance would trigger a panic:
```javascript
class C1 extends Set {
constructor() {
super();
Object.defineProperty(this, "size", {
writable: true,
enumerable: true,
value: Set
});
console.log(this); // panic!
}
}
new C1();
```
## Root Cause
In `src/bun.js/ConsoleObject.zig`, the Map and Set formatting code
called `toInt32()` directly on the `size` property value. This function
asserts that the value is not a Cell (objects/functions), causing a
panic when `size` was overridden with non-numeric values.
## Solution
Changed both Map and Set formatting to use `coerce(i32, globalThis)`
instead of `toInt32()`. This properly handles non-numeric values using
JavaScript's standard type coercion rules and propagates any coercion
errors appropriately.
## Test Plan
Added regression tests to `test/js/bun/util/inspect.test.js` that verify
Set and Map instances with overridden non-numeric `size` properties can
be inspected without panicking.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Bun bundler documentation duplicated the "linked" type for sourcemap.
### What does this PR do?
Fix documentation mistake.
### How did you verify your code works?
No code changes have been made.
## Summary
This PR adds support for the `--pass-with-no-tests` CLI flag to the test
runner, addressing issue #20814.
With the latest v1.2.8 release, the test runner now fails when no tests
match a filter. While this is useful for agentic coding workflows, there
are legitimate cases where the previous behavior is preferred, such as
in monorepos where a standard test file pattern is used as a filter but
not all packages contain tests.
This flag makes the test runner behave like Jest and Vitest, exiting
with code 0 when no tests are found.
## Changes
- Added `--pass-with-no-tests` flag to CLI arguments in
`src/cli/Arguments.zig`
- Added `pass_with_no_tests` field to `TestOptions` struct in
`src/cli.zig`
- Updated test runner logic in `src/cli/test_command.zig` to respect the
flag
- Added comprehensive tests in
`test/cli/test/pass-with-no-tests.test.ts`
## Test Plan
All new tests pass:
- ✅ `--pass-with-no-tests` exits with 0 when no test files found
- ✅ `--pass-with-no-tests` exits with 0 when filters match no tests
- ✅ Without flag, still exits with 1 when no tests found (preserves
existing behavior)
- ✅ `--pass-with-no-tests` still fails when actual tests fail
Closes#20814🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: pfg <pfg@pfg.pw>
### What does this PR do?
reduce memory usage when streaming (this should be a temporary solution
until owned_and_done is fixed)
### How did you verify your code works?
Added a test that should not be flaky in CI
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Avoid calling into C++ in `jsc.JSValue.asCell`.
(For internal tracking: fixes ENG-20820)
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Fixes a race condition on macOS where editing the entrypoint with vim's
atomic save causes "Module not found" errors during hot reload.
## Root Cause
On macOS, kqueue watches file descriptors/inodes, not paths. Vim's
atomic save sequence:
1. Rename `a.js` to `a.js~` → kqueue reports `NOTE_RENAME` on watched fd
2. Hot reloader immediately triggers reload
3. New file hasn't been created yet → `ENOENT` error
4. Vim re-creates `a.js`, and writes file contents into it
5. Directory gets `NOTE_WRITE` but file already removed from watchlist
```
rename("a.js", "a.js~") = 0
openat(AT_FDCWD, "a.js", O_WRONLY|O_CREAT, 0664) = 3
ftruncate(3, 0) = 0
write(3, "foobar\n", 7) = 7
close(3) = 0
```
This is macOS-specific because:
- **kqueue**: watches inodes, fd becomes stale when inode deleted
- **inotify (Linux)**: watches paths, gets `IN.MOVED_TO` (not
`IN.MOVE_SELF`), so files stay in watchlist
## Solution
When the entrypoint receives `NOTE_RENAME` on macOS:
1. Set `is_waiting_for_dir_change` flag
2. Skip immediate reload
3. Wait for parent directory `NOTE_WRITE` event
4. Use `faccessat()` to verify file exists
5. Trigger reload
This only applies to the entrypoint because dependencies have buffering
time during import graph traversal.
## Test Plan
Manual testing with vim on macOS:
1. Run `bun --hot entrypoint.js`
2. Edit entrypoint with vim (`:w`)
3. Verify no "Module not found" errors
4. Verify hot reload succeeds
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: taylor.fish <contact@taylor.fish>
### What does this PR do?
Fixes unhelpful FFI error messages that made debugging extremely
difficult. The user reported that when dlopen fails, the error doesn't
tell you which library failed or why.
**Before:**
```
Failed to open library. This is usually caused by a missing library or an invalid library path.
```
**After:**
```
Failed to open library "libnonexistent.so": /path/libnonexistent.so: cannot open shared object file: No such file or directory
```
### How did you verify your code works?
1. **Cross-platform compilation verified**
- Ran `bun run zig:check-all` - all platforms compile successfully
(Windows, macOS x86_64/arm64, Linux x86_64/arm64 glibc/musl)
2. **Added comprehensive regression tests**
(`test/regression/issue/dlopen-missing-symbol-error.test.ts`)
- ✅ Tests dlopen error shows library name when it can't be opened
- ✅ Tests dlopen error shows symbol name when symbol isn't found
- ✅ Tests linkSymbols shows helpful error when ptr is missing
- ✅ Tests handle both glibc and musl libc systems
3. **Manually tested error messages**
- Missing library: Shows full path and "No such file or directory"
- Invalid library: Shows "invalid ELF header"
- Missing symbol: Shows symbol and library name
- linkSymbols without ptr: Shows helpful explanation
### Implementation Details
1. **Created cross-platform getDlError() helper**
(src/bun.js/api/ffi.zig:8-21)
- On POSIX: Calls `std.c.dlerror()` to get actual system error message
- On Windows: Returns generic message (detailed errors handled in C++
layer via `GetLastError()` + `FormatMessageW()`)
- Follows the pattern established in `BunProcess.cpp` for dlopen error
handling
2. **Improved error messages**
- dlopen errors now include library name and system error details
- linkSymbols errors explain the ptr field requirement clearly
- Symbol lookup errors already showed both symbol and library name
3. **Fixed linkSymbols error propagation** (src/js/bun/ffi.ts:529)
- Added missing `if (Error.isError(result)) throw result;` check
- Now consistent with dlopen which already had this check
### Example Error Messages
- **Missing library:** `Failed to open library "libnonexistent.so":
cannot open shared object file: No such file or directory`
- **Invalid library:** `Failed to open library "/etc/passwd": invalid
ELF header`
- **Missing symbol:** `Symbol "nonexistent_func" not found in
"libc.so.6"`
- **Missing ptr:** `Symbol "myFunc" is missing a "ptr" field. When using
linkSymbols() or CFunction()...`
Fixes the issue mentioned in:
https://fxtwitter.com/hassanalinali/status/1977710104334963015🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Adds comprehensive support to `generate-classes.ts` for JavaScript
classes that need both named WriteBarrier members (like callbacks) and a
dynamic array of JSValues, all properly tracked by the garbage
collector. This replaces error-prone manual `protect()/unprotect()`
calls with proper GC integration.
## Motivation
The shell interpreter was using `JSValue.protect()/unprotect()` to keep
JavaScript objects alive, which caused memory leaks when cleanup paths
didn't properly unprotect values. This is a common pattern that needed a
better solution.
## What Changed
### Code Generator (`generate-classes.ts`)
When a class has both `values: ["resolve", "reject"]` and `valuesArray:
true`:
**Generated C++ class gets:**
- `WTF::FixedVector<JSC::WriteBarrier<JSC::Unknown>> jsvalueArray`
member for dynamic array
- Individual `JSC::WriteBarrier<JSC::Unknown> m_resolve, m_reject`
members for named values
- 4 `create()` overloads covering all combinations:
1. Basic: `create(vm, globalObject, structure, ptr)`
2. Array only: `create(..., FixedVector<WriteBarrier<Unknown>>&&)`
3. Named values: `create(..., JSValue resolve, JSValue reject)`
4. Both: `create(..., FixedVector&&, JSValue resolve, JSValue reject)`
**Constructor overloads using `WriteBarrierEarlyInit`:**
```cpp
JSShellInterpreter(VM& vm, Structure* structure, void* ptr,
JSValue resolve, JSValue reject)
: Base(vm, structure)
, m_resolve(resolve, JSC::WriteBarrierEarlyInit) // ← Key technique
, m_reject(reject, JSC::WriteBarrierEarlyInit)
{
m_ctx = ptr;
}
```
The `WriteBarrierEarlyInit` tag allows initializing WriteBarriers in the
constructor initializer list before the object is fully constructed,
which is required for proper GC integration.
**Extern C bridge functions:**
- `TypeName__createWithValues(globalObject, ptr, markedArgumentBuffer*)`
- `TypeName__createWithInitialValues(globalObject, ptr, resolve,
reject)`
- `TypeName__createWithValuesAndInitialValues(globalObject, ptr,
buffer*, resolve, reject)`
**Zig convenience wrappers:**
- `toJSWithValues(this, globalObject, markedArgumentBuffer)`
- `toJSWithInitialValues(this, globalObject, resolve, reject)`
- `toJSWithValuesAndInitialValues(this, globalObject, buffer, resolve,
reject)`
### Shell Interpreter Memory Leak Fix
**Before:**
```zig
const js_value = JSShellInterpreter.toJS(interpreter, globalThis);
resolve.protect(); // Manual reference counting
reject.protect();
// ... later in cleanup ...
resolve.unprotect(); // Easy to forget/miss in error paths
reject.unprotect();
```
**After:**
```zig
const js_value = Bun__createShellInterpreter(
globalThis,
interpreter,
parsed_shell_script,
resolve, // Stored with WriteBarrierEarlyInit
reject, // GC tracks automatically
);
// No manual memory management needed!
```
### Supporting Changes
- Added `MarkedArgumentBuffer.wrap()` helper in Zig for safe
MarkedArgumentBuffer usage
- Created `ShellBindings.cpp` with `Bun__createShellInterpreter()` using
the new API
- Removed all `protect()/unprotect()` calls from shell interpreter
- Applied pattern to both `ShellInterpreter` and `ShellArgs` classes
## Benefits
1. **No memory leaks**: GC tracks all references automatically
2. **Safer**: Cannot forget to unprotect values
3. **Cleaner code**: No manual reference counting
4. **Reusable**: Pattern works for any class needing to store JSValues
5. **Performance**: Same cost as manual protect/unprotect but safer
## Testing
Existing shell tests verify the functionality. The pattern is already
used throughout JavaScriptCore for similar cases (see
`JSWrappingFunction`, `AsyncContextFrame`, `JSModuleMock`, etc.)
## When to Use This Pattern
Use `values` + `valuesArray` + `WriteBarrierEarlyInit` when:
- Your C++ class needs to keep JavaScript values alive
- You have both known named callbacks AND dynamic arrays of values
- You want the GC to track references instead of manual
protect/unprotect
- Your class extends `JSDestructibleObject`
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Fixes flaky tests in `test/cli/inspect/BunFrontendDevServer.test.ts` by
resolving a race condition where tests would miss the `clientConnected`
event.
## Problem
Two tests were failing intermittently (~30% failure rate):
- `should notify on clientNavigated events`
- `should notify on consoleLog events`
Both tests would timeout after 5000ms waiting for the `clientConnected`
event that never arrived.
## Root Cause
In `src/bake/DevServer/HmrSocket.zig:30-41`, when a WebSocket connection
opens, the `onOpen()` handler immediately sends the `clientConnected`
inspector event.
The flaky tests had this problematic sequence:
1. Create WebSocket with `await createHMRClient()`
2. Server's `onOpen()` fires instantly and emits `clientConnected` event
3. Test then calls
`session.waitForEvent("BunFrontendDevServer.clientConnected")`
4. **Race condition**: Event already sent, test waits forever and times
out
## Solution
Set up event listeners **before** creating the WebSocket connection,
matching the pattern from the working test "should receive
clientConnected and clientDisconnected events":
```typescript
// Set up listener FIRST
const connectedEventPromise = session.waitForEvent("BunFrontendDevServer.clientConnected");
// Then create WebSocket
const ws = await createHMRClient();
// Now await the event
const connectedEvent = await connectedEventPromise;
```
## Testing
Verified with 30 consecutive test runs:
- **Before fix**: ~30% failure rate
- **After fix**: 100% pass rate (30/30 passes)
Tested with both:
- Debug build: `bun bd test`
- System bun v1.3.0: `bun test`
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Michael H <git@riskymh.dev>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Marko Vejnovic <marko@bun.com>
### What does this PR do?
Handles EXDEV correctly after first clonefile fails with ENOENT
Fixes#23579Fixes#23577
### How did you verify your code works?
Manually
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
This PR moves error-related functions from `bindings.cpp` into a new
dedicated file `ZigException.cpp` for better code organization.
## Changes
Moved the following functions to `ZigException.cpp`:
- `populateStackFrameMetadata`
- `populateStackFramePosition`
- `populateStackFrame`
- `populateStackTrace`
- `fromErrorInstance`
- `exceptionFromString`
- `JSC__JSValue__toZigException`
- `ZigException__collectSourceLines`
- `JSC__Exception__getStackTrace`
Also moved helper functions and types:
- `V8StackTraceIterator` class
- `getNonObservable`
- `PopulateStackTraceFlags` enum
- `StringView_slice` helper
- `SYNTAX_ERROR_CODE` macro
## Test plan
- Built successfully with `bun bd`
- All exception handling functions are properly exported
- No functional changes, pure refactoring
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Fixes the crash handler failing to capture and display stack traces on
Linux ARM64 systems.
**Before:**
```
============================================================
panic(main thread): cast causes pointer to be null
```
No stack trace shown.
**After:**
```
============================================================
panic(main thread): cast causes pointer to be null
bun.js.api.FFIObject.Reader.u8
/workspace/bun/src/bun.js/api/FFIObject.zig:67:41
bun.js.jsc.host_fn.toJSHostCall__anon_2545765
/workspace/bun/src/bun.js/jsc/host_fn.zig:93:5
```
Full stack trace with source locations.
#### Root Cause
- Zig's `std.debug.captureStackTrace` uses `StackIterator.init()` which
falls back to frame pointer-based unwinding when no context is provided
- Frame pointer-based unwinding doesn't work reliably on ARM64, even
with `-fno-omit-frame-pointer` enabled
- This resulted in 0 frames being captured (`trace.index == 0`)
#### Changes
1. **Use glibc's backtrace() on Linux**: On Linux with glibc (not musl),
always use glibc's `backtrace()` function instead of Zig's
StackIterator. glibc's implementation properly uses DWARF unwinding
information from `.eh_frame` sections.
2. **Skip crash handler frames**: After capturing with `backtrace()`,
find the desired `begin_addr` in the trace (within 128 byte tolerance)
and filter out crash handler internal frames for cleaner output. If
`begin_addr` is not found, use the complete backtrace.
3. **Preserve existing behavior**:
- Non-debug builds: Use WTF printer (fast, no external deps)
- Debug builds: Fall through to llvm-symbolizer (detailed source info)
### How did you verify your code works?
Reproduced the crash:
```bash
bun-debug --print 'Bun.FFI.read.u8(0)'
```
Verified that:
- ✅ Stack traces now appear on Linux ARM64 with proper source locations
- ✅ Crash handler frames are properly filtered out
- ✅ llvm-symbolizer integration works for debug builds
- ✅ WTF printer is used for release builds
- ✅ When begin_addr is not found, complete backtrace is used
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## What does this PR do?
Fixes a race condition where multiple threads could attempt to
initialize JavaScriptCore concurrently when the bundler's thread pool
processes files with macros.
Fixes#23540
## How did you verify your code works?
Reproduced the segfault with the Brisa project build and verified the
fix resolves it:
```bash
git clone https://github.com/brisa-build/brisa
cd brisa
bun install
bun run build
```
Before the fix: Segmentation fault with assertion failure
After the fix: Build proceeds without crashing
## Root Cause
The previous implementation used a simple boolean flag `has_loaded_jsc`
without synchronization. When multiple bundler threads tried to execute
macros simultaneously, they could race through the initialization check
before `JSC::initialize()` finished finalizing options on another
thread.
This caused crashes with:
```
ASSERTION FAILED: g_jscConfig.options.allowUnfinalizedAccess || g_jscConfig.options.isFinalized
vendor/WebKit/Source/JavaScriptCore/runtime/Options.h(146) : static OptionsStorage::Bool &JSC::Options::forceTrapAwareStackChecks()
```
## The Fix
Replace the boolean flag with `std::call_once`, which provides:
- Thread-safe initialization
- Guaranteed exactly-once execution
- Proper memory barriers to ensure visibility across threads
The initialization code is now wrapped in a lambda passed to
`std::call_once`, capturing the necessary parameters (`evalMode`,
`envp`, `envc`, `onCrash`).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Adds `BUN_WATCHER_TRACE` environment variable that logs all file watcher
events to a JSON file for debugging. When set, the watcher appends
detailed event information to the specified file path.
## Motivation
Debugging watch-related issues (especially with `bun --watch` and `bun
--hot`) can be difficult without visibility into what the watcher is
actually seeing. This feature provides detailed trace logs showing
exactly which files are being watched and what events are triggered.
## Implementation
- **Isolated module** (`src/watcher/WatcherTrace.zig`) - All trace logic
in separate file
- **No locking needed** - Watcher runs on its own thread, no mutex
required
- **Append-only mode** - Traces persist across multiple runs for easier
debugging
- **Silent errors** - Won't break functionality if trace file can't be
created
- **JSON format** - Easy to parse and analyze
## Usage
```bash
BUN_WATCHER_TRACE=/tmp/watch.log bun --watch script.js
BUN_WATCHER_TRACE=/tmp/hot.log bun --hot server.ts
```
## JSON Output Format
Each line is a JSON object with:
```json
{
"timestamp": 1760280923269,
"index": 0,
"path": "/path/to/watched/file.js",
"delete": false,
"write": true,
"rename": false,
"metadata": false,
"move_to": false,
"changed_files": ["script.js"]
}
```
## Testing
All tests use stdout streaming to wait for actual reloads (no
sleeps/timeouts):
- Tests with `--watch` flag
- Tests with `fs.watch` API
- Tests that trace file appends across multiple runs
- Tests validation of JSON format and event details
```
✅ 4 pass
❌ 0 fail
📊 52 expect() calls
```
## Files Changed
- `src/Watcher.zig` - Minimal integration with WatcherTrace module
- `src/watcher/WatcherTrace.zig` - New isolated trace implementation
- `src/watcher/KEventWatcher.zig` - Calls writeTraceEvents before
onFileUpdate
- `src/watcher/INotifyWatcher.zig` - Calls writeTraceEvents before
onFileUpdate
- `src/watcher/WindowsWatcher.zig` - Calls writeTraceEvents before
onFileUpdate
- `test/cli/watch/watcher-trace.test.ts` - Comprehensive tests
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
This PR implements support for `localAddress` and `localPort` options in
TCP connections, allowing users to bind outgoing connections to a
specific local IP address and port.
This addresses issue #6888 and implements Node.js-compatible behavior
for these options.
## Changes
### C Layer (uSockets)
- **`bsd.c`**: Modified `bsd_create_connect_socket()` to accept a
`local_addr` parameter and call `bind()` before `connect()` when a local
address is specified
- **`context.c`**: Updated `us_socket_context_connect()` and
`start_connections()` to parse and pass local address parameters through
the connection flow
- **`libusockets.h`**: Updated public API signatures to include
`local_host` and `local_port` parameters
- **`internal.h`**: Added `local_host` and `local_port` fields to
`us_connecting_socket_t` structure
- **`openssl.c`**: Updated SSL connection function to match the new
signature
### Zig Layer
- **`SocketContext.zig`**: Updated `connect()` method to accept and pass
through `local_host` and `local_port` parameters
- **`socket.zig`**: Modified `connectAnon()` to handle local address
binding, including IPv6 bracket removal and proper memory management
- **`Handlers.zig`**: Added `localAddress` and `localPort` fields to
`SocketConfig` and implemented parsing from JavaScript options
- **`Listener.zig`**: Updated connection structures to store and pass
local binding information
- **`socket.zig` (bun.js/api/bun)**: Modified `doConnect()` to extract
and pass local address options
- Updated all other call sites (HTTP, MySQL, PostgreSQL, Valkey) to pass
`null, 0` for backward compatibility
### JavaScript Layer
- **`net.ts`**: Enabled `localAddress` and `localPort` support by
passing these options to `doConnect()` and removing TODO comments
### Tests
- **`06888-localaddress.test.ts`**: Added comprehensive tests covering:
- IPv4 local address binding
- IPv4 local address and port binding
- IPv6 local address binding (loopback)
- Backward compatibility (connections without local address)
## Test Results
All tests pass successfully:
```
✓ TCP socket can bind to localAddress - IPv4
✓ TCP socket can bind to localAddress and localPort - IPv4
✓ TCP socket can bind to localAddress - IPv6 loopback
✓ TCP socket without localAddress works normally
4 pass, 0 fail
```
## API Usage
```typescript
import net from "net";
// Connect with a specific local address
const client = net.createConnection({
host: "example.com",
port: 80,
localAddress: "192.168.1.100", // Bind to this local IP
localPort: 0, // Let system assign port (optional)
});
```
## Implementation Details
The implementation follows the same flow as Node.js:
1. JavaScript options are parsed in `Handlers.zig`
2. Local address/port are stored in the connection configuration
3. The Zig layer processes and passes them to the C layer
4. The C layer parses the local address and calls `bind()` before
`connect()`
5. Both IPv4 and IPv6 addresses are supported
Memory management is handled properly throughout the stack, with
appropriate allocation/deallocation at each layer.
Closes#6888🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Makes sure strings are doubled quoted when they start with flow
indicators and `:`.
Fixes#23502
### How did you verify your code works?
Added tests for each indicator in flow and block context
### What does this PR do?
### How did you verify your code works?
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Add missing error handling for directory entries errors
The code was missing a check for .err
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Fixes#23474
## Summary
When `request.cookies.set()` is called before `server.upgrade()`, the
cookies are now properly included in the WebSocket upgrade response
headers.
## Problem
Previously, cookies set on the request via `req.cookies.set()` were only
written for regular HTTP responses but were ignored during WebSocket
upgrades. Users had to manually pass cookies via the `headers` option:
```js
server.upgrade(req, {
headers: {
"Set-Cookie": `SessionId=${sessionId}`,
},
});
```
## Solution
Modified `src/bun.js/api/server.zig` to check for and write cookies to
the WebSocket upgrade response after the "101 Switching Protocols"
status is set but before the actual upgrade is performed.
The fix handles both cases:
- When `upgrade()` is called without custom headers
- When `upgrade()` is called with custom headers
## Testing
Added comprehensive regression tests in
`test/regression/issue/23474.test.ts` that:
- Verify cookies are set in the upgrade response without custom headers
- Verify cookies are set in the upgrade response with custom headers
- Use `Promise.withResolvers()` for efficient async handling (no
arbitrary timeouts)
Tests confirmed:
- ❌ Fail with system bun v1.2.23 (without fix)
- ✅ Pass with debug build v1.3.0 (with fix)
## Manual verification
```bash
curl -i -H "Connection: Upgrade" -H "Upgrade: websocket" \
-H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
-H "Sec-WebSocket-Version: 13" \
http://localhost:3000/ws
```
Response now includes:
```
HTTP/1.1 101 Switching Protocols
Set-Cookie: test=123; Path=/; SameSite=Lax
Upgrade: websocket
Connection: Upgrade
...
```
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Fixes Clang 19 detection in the Nix flake environment by explicitly
setting CMAKE compiler environment variables in the shellHook.
## Problem
When using `nix develop` or `nix print-dev-env`, CMake was unable to
detect the Clang 19 compiler because the `CMAKE_C_COMPILER` and
`CMAKE_CXX_COMPILER` environment variables were not being set, even
though the compiler was available in the environment.
The `shell.nix` file correctly sets these variables (lines 80-87), but
`flake.nix` was missing them.
## Solution
Updated `flake.nix` shellHook to export the same compiler environment
variables as `shell.nix`:
- `CC`, `CXX`, `AR`, `RANLIB`
- `CMAKE_C_COMPILER`, `CMAKE_CXX_COMPILER`, `CMAKE_AR`, `CMAKE_RANLIB`
This ensures consistent compiler detection across both Nix entry points
(`nix develop` with flakes and `nix-shell` with shell.nix).
## Testing
Verified that all compiler variables are now properly set:
```bash
nix develop --accept-flake-config --impure --command bash -c 'echo "CMAKE_C_COMPILER=$CMAKE_C_COMPILER"'
# Output: CMAKE_C_COMPILER=/nix/store/.../clang-wrapper-19.1.7/bin/clang
```
Also tested with the profile workflow:
```bash
nix develop --accept-flake-config --impure --profile ./dev-profile --command true
eval "$(nix print-dev-env ./dev-profile --accept-flake-config --impure)"
echo "CMAKE_C_COMPILER=$CMAKE_C_COMPILER"
# Output: CMAKE_C_COMPILER=/nix/store/.../clang
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
This PR fixes incorrect WriteBarrier initialization patterns throughout
the Bun codebase where `.set()` or `.setEarlyValue()` was being called
in the constructor body or in `finishCreation()`. According to
JavaScriptCore's `WriteBarrier.h`, WriteBarriers that are initialized
during construction should use the `WriteBarrierEarlyInit` constructor
in the initializer list to avoid triggering unnecessary write barriers.
## Changes
The following classes were updated to properly initialize WriteBarrier
fields:
1. **InternalModuleRegistry** - Initialize internal fields in
constructor using `setWithoutWriteBarrier()` instead of calling `.set()`
in `finishCreation()`
2. **AsyncContextFrame** - Pass callback and context to constructor and
use `WriteBarrierEarlyInit`
3. **JSCommonJSModule** - Pass id, filename, dirname to constructor and
use `WriteBarrierEarlyInit`
4. **JSMockImplementation** - Pass initial values to constructor and use
`WriteBarrierEarlyInit`
5. **JSConnectionsList** - Pass connection sets to constructor and use
`WriteBarrierEarlyInit`
6. **JSBunRequest** - Pass params to constructor and initialize both
`m_params` and `m_cookies` using `WriteBarrierEarlyInit`
7. **JSNodeHTTPServerSocket** - Initialize `currentResponseObject` using
`WriteBarrierEarlyInit` instead of calling `setEarlyValue()`
## Why This Matters
From JavaScriptCore's `WriteBarrier.h`:
```cpp
enum WriteBarrierEarlyInitTag { WriteBarrierEarlyInit };
// Constructor for early initialization during object construction
WriteBarrier(T* value, WriteBarrierEarlyInitTag)
{
this->setWithoutWriteBarrier(value);
}
```
Using `WriteBarrierEarlyInit` during construction:
- Avoids triggering write barriers when they're not needed
- Is the correct pattern for initializing WriteBarriers before the
object is fully constructed
- Aligns with JavaScriptCore best practices
## Testing
- ✅ Full debug build completes successfully
- ✅ Basic functionality tested (CommonJS modules, HTTP requests, Node
HTTP servers)
- ✅ No regressions observed
## Note on generate-classes.ts
The code generator (`generate-classes.ts`) does not need updates because
generated classes intentionally leave WriteBarrier fields (callbacks,
cached fields, values) uninitialized. They start with
default-constructed WriteBarriers and are populated later by Zig code
via setter functions, which is the correct pattern for those fields.
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Fixes test\regression\issue\23316-long-path-spawn.test.ts
The problem was ``await Bun.write(join(deepPath, "test.js"),
`console.log("hello");`);`` was failing because the name was too long,
but it failed before refConcurrently was called and it called
unrefConcurrently after failing. so then when the subprocess spawned it
didn't ref.
---------
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
Fixes `bun -p "process.stderr.write('Hello' +
String.fromCharCode(0xd800))"`.
Also fixes potential index out of bounds if there are many invalid
sequences.
This also affects `TextEncoder`.
### How did you verify your code works?
Added tests for edgecases
---------
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Provides a Nix flake as an alternative to `scripts/bootstrap.sh` for
setting up the Bun development environment.
## What's included:
- **flake.nix**: Full development environment with all dependencies from
bootstrap.sh
- LLVM 19, CMake 3.30+, Node.js 24, Rust, Go
- Build tools: ninja, ccache, pkg-config, make
- Chromium dependencies for Puppeteer testing
- gdb for core dump debugging
- **shell.nix**: Simple wrapper for `nix-shell` usage
- **cmake/CompilerFlags.cmake**: Nix compatibility fixes
- Disable zstd debug compression (Nix's LLVM not built with zstd)
- Set _FORTIFY_SOURCE=0 for -O0 debug builds
- Downgrade _FORTIFY_SOURCE warning to not error
## Usage:
```bash
nix-shell
export CMAKE_SYSTEM_PROCESSOR=$(uname -m)
bun bd
```
## Verified working:
✅ Successfully compiles Bun debug build
✅ Binary tested: `./build/debug/bun-debug --version` → 1.2.24-debug
✅ All dependencies from bootstrap.sh included
## Advantages:
- Fully isolated (no sudo required)
- 100% reproducible dependency versions
- Fast setup with binary caching
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Calls `uncork()` after flushing response headers to ensure data is sent
as soon as possible, improving responsiveness.
This behavior still works correctly even without the explicit `uncork()`
call, due to the deferred uncork logic implemented here:
6e3359dd16/packages/bun-uws/src/Loop.h (L57-L64)
A test already covers this scenario in
`test/js/node/test/parallel/test-http-flush-response-headers.js`.
### How did you verify your code works?
CI
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
fix tests failing because of example.com
### How did you verify your code works?
CI
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Fixes#23333, Fixes#13978
### What does this PR do?
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: pfg <pfg@pfg.pw>
Co-authored-by: Zack Radisic <zack@theradisic.com>
## What does this PR do?
Bumps Bun version from 1.2.24 to 1.3.0, marking the start of the 1.3.x
release series.
## Changes
- **`package.json`**: Updated version from `1.2.24` to `1.3.0`
- **`LATEST`**: Updated from `1.2.23` to `1.3.0` (used by installation
scripts)
- **`test/bundler/bundler_bun.test.ts`**: Updated version check to
include `1.3.x` so export conditions tests continue to run
## Verification
✅ Debug build successful showing version `1.3.0-debug`
✅ All platforms compile successfully via `bun run zig:check-all` (49/49
steps)
✅ Bundler tests pass with updated version check
## Additional Notes
- CI workflow Bun versions (e.g., `1.2.3`, `1.2.0` in
`.github/workflows/release.yml`) are intentionally left unchanged -
these are pinned versions used to run the release tooling, not the
version being released
- Docker images use `ARG BUN_VERSION` passed at build time and don't
need updates
- The actual release version comes from git tags via `${{
env.BUN_VERSION }}`
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Fixes#23380 - this is a use-case for the `--only` flag that I missed
Adds back the `--only` flag. When running `bun test` on a full test
suite, without this flag it will run only that test in its file, but it
will run all other tests from other files. With this flag, it will not
run things from other files.
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: pfg <pfg@pfg.pw>
## Summary
Modernizes `test/bundler/bundler_promiseall_deadcode.test.ts` to use the
`itBundled` test helper instead of manual temp directory creation and
spawning. This makes the test more concise, maintainable, and consistent
with other bundler tests.
## Changes
- Replace `tempDirWithFiles` + manual `Bun.spawn` with `itBundled`
- Use `files` object for test fixtures instead of creating a temp
directory
- Use `onAfterBundle` callback for bundled output assertions
- Use `run.validate` for runtime stderr validation
- Use `run.partialStdout` for stdout verification
- Preserve all original test assertions and behavior
## Test Results
All 3 tests pass with identical functional behavior:
```
3 pass
0 fail
2 snapshots, 23 expect() calls
Ran 3 tests across 1 file. [8.95s]
```
## Verification
All original assertions are preserved:
- ✅ Build success validation
- ✅ Bundled output snapshots (updated paths to match itBundled format)
- ✅ `__esm` and `__promiseAll` presence/absence checks
- ✅ Runtime execution validation (exit code 0)
- ✅ Runtime stderr validation (no async syntax errors)
- ✅ Runtime stdout validation (contains expected output)
The test is now more concise (407 insertions vs 514 deletions) while
maintaining full test coverage.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Makes isolated installs the default install strategy for projects with
workspaces in Bun v1.3.
Also fixes creating patches with `bun patch` and `--linker isolated`
Fixes#22693
### How did you verify your code works?
Added tests for node_modules renaming `bun patch` with isolated install.
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Alternative to #15596 where it now only impacts `bun run` for the same
cwd dir. This does not effect `bunx` ([even though according to code it
should load
it](7830e15650/src/cli.zig (L2597-L2628))),
and isnt as fancy as `bun install` where it ensures to check the bunfig
in `package.json` dir.
This shouldn't have any performance issues because its already loading
the file, but now its loading earlier so it can use `run.bun` option.
Fixes#11445, (as well as fixes#15484, fixes#15483, fixes#17064)
---------
Co-authored-by: pfg <pfg@pfg.pw>
## Summary
This PR improves the correctness of bin linking by atomically
normalizing `\r\n` to `\n` in shebang lines when linking bins.
### Changes
- **Refactored shebang normalization in `src/install/bin.zig`**:
- Extracted logic into separate `tryNormalizeShebang` function
- Changed from in-place file modification to atomic file replacement
- Reads entire file, creates temporary file with corrected shebang, then
atomically renames
- Properly cleans up temporary files on errors
- **Added test coverage**:
- New test file `test/cli/install/shebang-normalize.test.ts` verifies
CRLF normalization works correctly
- Modified existing test in `bun-link.test.ts` to use Python script with
CRLF shebang
### Why
The previous implementation modified files in-place by seeking to the
`\r` position and overwriting with `\n`. This could potentially corrupt
files if interrupted mid-write. The new atomic approach ensures file
integrity by writing to a temporary file first, then renaming it to
replace the original.
## Test plan
- ✅ `bun bd test test/cli/install/shebang-normalize.test.ts` - passes
- ✅ Verified bins with CRLF shebangs are normalized to LF during linking
- ✅ Code compiles successfully
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
BeforeOpen code is not necessary since we have `setOnSocketUpgraded`
callback now,and we should NOT convert websocket to a response, make
sure that no closed socket is passed to `JSNodeHTTPServerSocket`, change
isIdle to be inside AsyncSocketData to be more reliable (works for
websocket and normal sockets)
### How did you verify your code works?
CI
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Fixed a race condition where calling `pause()` followed by `resume()` on
`process.stdin` would prevent data from being received, causing the
process to exit immediately instead of listening for input.
## Root Cause
The issue was in the pause/resume event handling logic in
`ProcessObjectInternals.ts`:
1. When `pause()` is called, the "pause" event handler schedules a
`disown()` call for the next tick
2. When `resume()` is called immediately after, it calls `own()` to
acquire a stream reader
3. On the next tick, the scheduled `disown()` from step 1 executes and
incorrectly releases the reader that was just acquired in step 2
This race condition left the stream without a reader, so no data could
be received.
## Solution
Added a `pendingDisown` flag that:
- Gets set to `true` when scheduling a disown operation
- Gets cleared to `false` when `own()` is called (during resume)
- Prevents the scheduled disown from executing if it has been cancelled
by a subsequent `own()` call
## Test Plan
- [x] Added regression tests in
`test/regression/issue/stdin-pause-resume.test.ts`
- [x] Verified fix with original reproduction case
- [x] Existing stdin/tty tests still pass
(`tty-readstream-ref-unref.test.ts`,
`tty-reopen-after-stdin-eof.test.ts`)
## Reproduction
Before this fix, the following code would exit immediately:
```ts
process.stdin.on("data", chunk => {
process.stdout.write(chunk);
});
process.stdin.pause();
process.stdin.resume();
```
After the fix, it correctly waits for and processes input.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Fixes data loss when reading large amounts of data from subprocess pipes
on Windows, a regression introduced by the libuv 1.51.0 upgrade in
commit e3783c244f.
### The Problem
When piping large data through a subprocess on Windows (e.g.,
`process.stdin.pipe(process.stdout)`), Bun randomly loses ~73KB of data
out of 1MB, receiving only ~974KB instead of the full 1048576 bytes.
The subprocess correctly receives all 1MB on stdin, but the parent
process loses data when reading from the subprocess stdout.
### Root Cause Analysis
#### libuv 1.51.0 Change
The libuv 1.51.0 upgrade (commit
[libuv/libuv@727ee723](727ee7237e))
changed Windows pipe reading behavior:
**Before:** libuv would call `PeekNamedPipe` to check available bytes,
then read exactly that amount.
**After:** libuv attempts immediate non-blocking reads (up to 65536
bytes) before falling back to async reads. If less data is available
than requested, it returns what's available and signals `more=0`,
causing the read loop to break.
This optimization introduces **0-byte reads** when data isn't
immediately available, which are delivered to Bun's read callback.
#### The Race Condition
When Bun's `WindowsBufferedReader` called `onRead(.drained)` for these
0-byte reads, it created a race condition. Debug logs clearly show the
issue:
**Error case (log.txt):**
```
Line 79-80: onStreamRead = 0 (drained)
Line 81: filesink closes (stdin closes)
Line 85: onStreamRead = 6024 ← Should be 74468!
Line 89: onStreamRead = -4095 (EOF)
```
**Success case (success.log.txt):**
```
Line 79-80: onStreamRead = 0 (drained)
Line 81: filesink closes (stdin closes)
Line 85: onStreamRead = 74468 ← Full chunk!
Line 89-90: onStreamRead = 0 (drained)
Line 91: onStreamRead = 6024
Line 95: onStreamRead = -4095 (EOF)
```
When stdin closes while a 0-byte drained read is pending, the next read
returns truncated data (6024 bytes instead of 74468 bytes).
### The Fix
Two changes to `WindowsBufferedReader` in `src/io/PipeReader.zig`:
#### 1. Ignore 0-byte reads (line 937-940)
Don't call `onRead(.drained)` for 0-byte reads. Just return and let
libuv queue the next read. This prevents the race condition that causes
truncated reads.
```zig
0 => {
// With libuv 1.51.0+, calling onRead(.drained) here causes a race condition
// where subsequent reads return truncated data. Just ignore 0-byte reads.
return;
},
```
#### 2. Defer `has_inflight_read` flag clearing (line 827-839)
Clear the flag **after** the read callback completes, not before. This
prevents libuv from starting a new overlapped read operation while we're
still processing the current data buffer, which could cause memory
corruption per the libuv commit message:
> "Starting a new read after uv_read_cb returns causes memory corruption
on the OVERLAPPED read_req if uv_read_stop+uv_read_start was called
during the callback"
```zig
const result = onReadChunkFn(this.parent, buf, hasMore);
// Clear has_inflight_read after the callback completes
this.flags.has_inflight_read = false;
return result;
```
### How to Test
Run the modified test in
`test/js/bun/spawn/spawn-stdin-readable-stream.test.ts`:
```js
test("ReadableStream with very large chunked data", async () => {
const chunkSize = 64 * 1024; // 64KB chunks
const numChunks = 16; // 1MB total
const chunk = Buffer.alloc(chunkSize, "x");
const stream = new ReadableStream({
pull(controller) {
if (pushedChunks < numChunks) {
controller.enqueue(chunk);
pushedChunks++;
} else {
controller.close();
}
},
});
await using proc = spawn({
cmd: [bunExe(), "-e", `
let length = 0;
process.stdin.on('data', (data) => length += data.length);
process.once('beforeExit', () => console.error(length));
process.stdin.pipe(process.stdout)
`],
stdin: stream,
stdout: "pipe",
env: bunEnv,
});
const text = await proc.stdout.text();
expect(text.length).toBe(chunkSize * numChunks); // Should be 1048576
});
```
**Before fix:** Randomly fails with ~974KB instead of 1MB
**After fix:** Consistently passes with full 1MB
Run ~100 times to verify the race condition is fixed.
### Related Issues
This may also fix#23071 (Windows scripts hanging), though that issue
needs separate verification.
### Why Draft?
Marking as draft for Windows testing by the team. The fix is based on
detailed debug log analysis showing the exact race condition, but needs
verification on Windows CI.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
When a snapshot is created in CI without `--update-snapshots`, the error
message now displays the received value that was attempting to be
snapshotted. This helps developers understand what value triggered the
error.
## Changes
- Modified the `SnapshotCreationNotAllowedInCI` error message in
`src/bun.js/test/expect.zig` to include the received value using the
same formatting pattern as other expect error messages
## Before
```
Snapshot creation is not allowed in CI environments unless --update-snapshots is used
If this is not a CI environment, set the environment variable CI=false to force allow.
```
## After
```
Snapshot creation is not allowed in CI environments unless --update-snapshots is used
If this is not a CI environment, set the environment variable CI=false to force allow.
Received: <formatted value>
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Breaking changes:
- bun:test: disallow creating snapshots or using .only() in ci
- for users: hopefully this should only reveal existing bugs in tests,
not cause failures.
- general: enable calling unhandled rejection handlers for
ErrorBuilder.reject()
- for users: this might reveal some unhandled rejections that were not
visible before.
## Summary
- Clone `bunEnv` and delete `AGENTS` property in `beforeAll`
- Replace all `bunEnv` references with `testEnv` in test spawns
- Prevents parent process's `AGENTS` env var from leaking into tests
## Problem
The `claudecode-flag` test was using `bunEnv` directly, which includes
`...process.env`. When running in environments like Claude Code where
`AGENTS` may be set, this variable would leak into the test child
processes and potentially affect test behavior.
## Solution
Created a `testEnv` clone in `beforeAll` that explicitly deletes
`AGENTS`, ensuring consistent test behavior regardless of the parent
process's environment.
## Test plan
- [x] Test passes without `AGENTS` set
- [x] Test passes with `AGENTS=1` set in parent environment
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
This PR upgrades the `react-shadcn` template:
- Upgrades to the new Tailwind v4 styles and components
- Updates the example components to use the new ones.
- Removed unused form component
- Fixed some a11y issues with the example component.
### How did you verify your code works?
- Ran `bun build` to test if the template builds with no errors.
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Fixes#23206
When using `test.each` with object syntax and `$variable` interpolation,
string values were being quoted (e.g., `"apple"` instead of `apple`).
This didn't match the behavior of `%s` formatting or Jest's behavior.
## Changes
- Modified `formatLabel` in `src/bun.js/test/jest.zig` to check if the
value is a primitive string and use `toString()` instead of the
formatter with `quote_strings=true`
- Added regression test in `test/regression/issue/23206.test.ts`
## Example
**Before:**
```
test.each([
{ name: "apple" },
{ name: "banana" }
])("fruit #%# is $name", fruit => {
// Test names were:
// "fruit #0 is "apple""
// "fruit #1 is "banana""
});
```
**After:**
```
test.each([
{ name: "apple" },
{ name: "banana" }
])("fruit #%# is $name", fruit => {
// Test names are now:
// "fruit #0 is apple"
// "fruit #1 is banana"
});
```
## Test plan
- [x] Added regression test that verifies both `%s` and `$name` syntax
produce consistent output
- [x] Tested with `AGENT=0` - all tests pass
- [x] Verified other primitive types (numbers, booleans) still format
correctly
- [x] Verified complex objects still use proper formatting
This matches Jest's behavior after their fix:
https://github.com/jestjs/jest/issues/7689🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: pfg <pfg@pfg.pw>
### What does this PR do?
Fixes#23314 where `zlib.zstdCompress()` created data that caused an
out-of-memory error when decompressed with `Bun.zstdDecompressSync()`.
#### 1. `zlib.zstdCompress()` now sets `pledgedSrcSize`
The async convenience method now automatically sets the `pledgedSrcSize`
option to the input buffer size. This ensures the compressed frame
includes the content size in the header, making sync and async
compression produce identical output.
**Node.js compatibility**: `pledgedSrcSize` is a documented Node.js
option:
-
[`vendor/node/doc/api/zlib.md:754-758`](https://github.com/oven-sh/bun/blob/main/vendor/node/doc/api/zlib.md#L754-L758)
-
[`vendor/node/lib/zlib.js:893`](https://github.com/oven-sh/bun/blob/main/vendor/node/lib/zlib.js#L893)
-
[`vendor/node/src/node_zlib.cc:890-904`](https://github.com/oven-sh/bun/blob/main/vendor/node/src/node_zlib.cc#L890-L904)
#### 2. Added `bun.zstd.decompressAlloc()` - centralized safe
decompression
Created a new function in `src/deps/zstd.zig` that handles decompression
in one place with automatic safety features:
- **Handles unknown content sizes**: Automatically switches to streaming
decompression when the zstd frame doesn't include content size (e.g.,
from streams without `pledgedSrcSize`)
- **16MB safety limit**: For security, if the reported decompressed size
exceeds 16MB, streaming decompression is used instead of blindly
trusting the header
- **Fast path for small files**: Still uses efficient pre-allocation for
files < 16MB with known sizes
This centralized fix automatically protects:
- `Bun.zstdDecompressSync()` / `Bun.zstdDecompress()`
- `StandaloneModuleGraph` source map decompression
- Any other code using `bun.zstd` decompression
### How did you verify your code works?
**Before:**
```typescript
const input = "hello world";
// Async compression
const compressed = await new Promise((resolve, reject) => {
zlib.zstdCompress(input, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
// This would fail with "Out of memory"
const decompressed = Bun.zstdDecompressSync(compressed);
```
**Error**: `RangeError: Out of memory` (tried to allocate UINT64_MAX
bytes)
**After:**
```typescript
const input = "hello world";
// Async compression (now includes content size)
const compressed = await new Promise((resolve, reject) => {
zlib.zstdCompress(input, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
// ✅ Works! Falls back to streaming decompression if needed
const decompressed = Bun.zstdDecompressSync(compressed);
console.log(decompressed.toString()); // "hello world"
```
**Tests:**
- ✅ All existing tests pass
- ✅ New regression tests for async/sync compression compatibility
(`test/regression/issue/23314/zstd-async-compress.test.ts`)
- ✅ Test for large (>16MB) decompression using streaming
(`test/regression/issue/23314/zstd-large-decompression.test.ts`)
- ✅ Test for various input sizes and types
(`test/regression/issue/23314/zstd-large-input.test.ts`)
**Security:**
The 16MB safety limit protects against malicious zstd frames that claim
huge decompressed sizes in the header, preventing potential OOM attacks.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Fixes#12095
Manually confirmed to fix the case, but it would be better to have an
automated test to compare default reporter output with lcov reporter
output.
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: pfg <pfg@pfg.pw>
### What does this PR do?
Matches node behavior.
Fixes#20975
### How did you verify your code works?
Manually and added a test
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## What does this PR do?
Fixes#22003 by escaping tab characters in filenames when generating
sourcemap JSON.
When a filename contained a tab character (e.g., `file\ttab.js`), the
sourcemap JSON would contain a **literal tab byte** instead of the
escaped `\t`, producing invalid JSON that caused `error:
InvalidSourceMap`.
The root cause was in `src/bun.js/bindings/highway_strings.cpp` where
the scalar fallback path had:
```cpp
if (char_ >= 127 || (char_ < 0x20 && char_ != 0x09) || ...)
```
This **exempted tab characters** (0x09) from being detected as needing
escape, while the SIMD path correctly detected them. The fix removes the
`&& char_ != 0x09` exemption so both paths consistently escape tabs.
## How did you verify your code works?
Added regression test in `test/regression/issue/22003.test.ts` that:
- Creates a file with a tab character in its filename
- Builds it with sourcemap generation
- Verifies the sourcemap is valid JSON
- Checks that the tab is escaped as `\t` (not a literal byte)
The test **fails on system bun** (produces invalid JSON with literal
tab):
```bash
USE_SYSTEM_BUN=1 bun test test/regression/issue/22003.test.ts
# error: JSON Parse error: Unterminated string
```
The test **passes with the fix** (tab properly escaped):
```bash
bun bd test test/regression/issue/22003.test.ts
# ✓ 1 pass
```
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Sets the `reportViolationForUnsafeEval` global object method table
function pointer. JSC does not check if the pointer is null before
calling.
Fixes#23048Fixes#22000
### How did you verify your code works?
Manually, and added a test for codeGenerationOptions.
### What does this PR do?
Adds a new test which mirrors the _callback errors don't crash the
client_ test but doesn't rely on IPC.
### How did you verify your code works?
Hopefully, CI
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Three things:
- JSCommonJSExtensions.cpp `onAssign` was returning out of sync numbers
instead of `BunLoaderTypeJS`/`BunLoaderTypeNAPI`/...
- `bun.schema.api.Loader._none` was 255 instead of 254 like
`BunLoaderTypeNone`
- `Bun__transpileFile` used `bun.options.Loader.Optional` instead of
`bun.schema.api.Loader`. `bun.options.Loader` does not have a type kept
in sync in C++.
### How did you verify your code works?
Added tests that make sure the correct loader is used for modules
required with custom _extensions functions
## Summary
Fixes a macOS kernel (XNU) bug where `accept()` can return a valid
socket descriptor but with `addrlen=0`, indicating an already-dead
socket.
This occurs when an IPv4 connection to an IPv6 dual-stack listener is
immediately aborted (RST packet). The fix detects this condition on
Darwin and handles it intelligently - preserving buffered data when
present, discarding truly dead sockets when not.
## Background
This implements the equivalent of the bugfix from capnproto:
https://github.com/capnproto/capnproto/pull/2365
The issue manifests as:
1. IPv4 connection made to IPv6 dual-stack listener
2. Connection immediately aborted (sends RST packet)
3. `accept()` returns valid socket descriptor but `addrlen=0`
4. Socket may have buffered data from `connectx()` or be truly dead
## Enhanced Data-Preserving Solution
Unlike simple "close immediately" approaches, this fix **prevents data
loss** from the `connectx()` edge case:
**Race Condition Scenario:**
1. Client uses `connectx()` to send data immediately during connection
2. Network abort (RST) occurs after data is buffered but before full
connection establishment
3. Darwin kernel returns `socklen=0` but socket has buffered data
4. **Our fix preserves this data instead of losing it**
**Logic:**
```c
if (addr->len == 0) {
/* Check if there's any pending data before discarding the socket */
char peek_buf[1];
ssize_t has_data = recv(accepted_fd, peek_buf, 1, MSG_PEEK | MSG_DONTWAIT);
if (has_data <= 0) {
/* No data available, socket is truly dead - discard it */
bsd_close_socket(accepted_fd);
continue; /* Try to accept the next connection */
}
/* If has_data > 0, let the socket through - there's buffered data to read */
}
```
## XNU Kernel Source Analysis
After investigating the Darwin XNU kernel source code, I found this bug
affects **multiple system calls**, not just `accept()`. The bug is
rooted in the kernel's socket layer when protocol-specific functions
return NULL socket addresses.
### Affected System Calls
#### 1. accept() and accept_nocancel() ✅ FIXED
**Location:**
[`/bsd/kern/uipc_syscalls.c:596-605`](https://github.com/apple/darwin-xnu/blob/main/bsd/kern/uipc_syscalls.c#L596-L605)
```c
(void) soacceptlock(so, &sa, 0);
socket_unlock(head, 1);
if (sa == NULL) {
namelen = 0; // ← BUG: Returns socklen=0
if (uap->name) {
goto gotnoname;
}
error = 0;
goto releasefd;
}
```
#### 2. getsockname() ⚠️ ALSO AFFECTED
**Location:**
[`/bsd/kern/uipc_syscalls.c:2601-2603`](https://github.com/apple/darwin-xnu/blob/main/bsd/kern/uipc_syscalls.c#L2601-L2603)
```c
if (sa == 0) {
len = 0; // ← SAME BUG: Returns socklen=0
goto gotnothing;
}
```
#### 3. getpeername() ⚠️ ALSO AFFECTED
**Location:**
[`/bsd/kern/uipc_syscalls.c:2689-2691`](https://github.com/apple/darwin-xnu/blob/main/bsd/kern/uipc_syscalls.c#L2689-L2691)
```c
if (sa == 0) {
len = 0; // ← SAME BUG: Returns socklen=0
goto gotnothing;
}
```
### System Calls NOT Affected
#### connect() and connectx() ✅ SAFE
**Locations:**
-
[`/bsd/kern/uipc_syscalls.c:686-744`](https://github.com/apple/darwin-xnu/blob/main/bsd/kern/uipc_syscalls.c#L686-L744)
(connect)
-
[`/bsd/kern/uipc_syscalls.c:747+`](https://github.com/apple/darwin-xnu/blob/main/bsd/kern/uipc_syscalls.c#L747)
(connectx)
**Why they're safe:** These functions read socket addresses from
userspace via `getsockaddr()` and pass them to the protocol layer. They
don't receive socket addresses from the network stack, so they can't
encounter the `socklen=0` condition.
### Root Cause
The bug occurs when protocol layer functions (`pru_accept`,
`pru_sockaddr`, `pru_peeraddr`) return NULL socket addresses during
IPv4→IPv6 dual-stack connection race conditions. The kernel returns
`socklen=0` instead of treating it as an error case.
**Key XNU source reference:**
[`/bsd/kern/uipc_socket.c:1544`](https://github.com/apple/darwin-xnu/blob/main/bsd/kern/uipc_socket.c#L1544)
```c
error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
```
**Socket state vs buffered data:** From
[`/bsd/kern/uipc_socket2.c:2227`](https://github.com/apple/darwin-xnu/blob/main/bsd/kern/uipc_socket2.c#L2227):
```c
// Even with SS_CANTRCVMORE set, data can be buffered in so->so_rcv.sb_cc
return so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
((so->so_state & SS_CANTRCVMORE) && cfil_sock_data_pending(&so->so_rcv) == 0)
```
## Changes
- Added Darwin-specific check in `bsd_accept_socket()` in
`packages/bun-usockets/src/bsd.c:708-720`
- When `addr->len == 0` after successful `accept()`:
1. Check for buffered data with `recv(MSG_PEEK | MSG_DONTWAIT)`
2. If data exists, let socket through normally (prevents data loss)
3. If no data, close socket and continue accepting
- Only applies to `__APPLE__` builds to avoid affecting other platforms
## Test plan
- [x] Debug build compiles successfully
- [x] Basic HTTP server operations work correctly (exercises accept
path)
- [x] Regression test covers IPv4→IPv6 dual-stack connection abort
scenarios
- [x] Test verifies server doesn't crash/hang when encountering
socklen=0 condition
- [x] Enhanced fix preserves buffered data from connectx() edge cases
The regression test
(`test/regression/issue/darwin-accept-socklen-zero.test.ts`) creates the
exact conditions that trigger this kernel bug:
1. IPv6 dual-stack server (`hostname: "::"`)
2. IPv4 connections (`127.0.0.1`) with immediate abort (RST packets)
3. Concurrent connection attempts to maximize race condition probability
4. Verification that server remains stable and responsive
## Impact Assessment
### For Bun's uSockets Implementation
- **accept() path:** ✅ FIXED with data loss prevention - This PR handles
the primary case affecting network servers
- **connect() path:** ✅ NOT VULNERABLE - connect() doesn't receive
kernel sockaddrs
- **connectx() path:** ✅ NOT VULNERABLE - connectx() doesn't receive
kernel sockaddrs
- **connectx() data:** ✅ PRESERVED - Enhanced fix prevents losing
buffered data from immediate sends
### Additional Considerations
While `getsockname()` and `getpeername()` have the same kernel bug,
they're less critical for server stability since servers primarily use
`accept()` for incoming connections.
🤖 Generated with [Claude Code](https://claude.ai/code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
Fixes a bug since Bun v1.0.15: `var f = ([1, 2], "hi");`
Fixes a regression since Bun v1.2.22: `var f = (new Array([1, 2]),
"hi");`
Fixes#23287
### How did you verify your code works?
Added a test
### What does this PR do?
fixes#22679
* includes a better error if a package cant be met because of the age
(but would normally)
* logs the resolved one in --verbose (which can be helpful in debugging
to show it does know latest but couldn't use)
* makes bun outdated show in the table when the package isn't true
latest
* includes a rudimentary "stability" check if a later version is in
blacked out time (but only up to 7 days as it goes back to latest with
min age)
For extended security we could also Last-Modified header of the tgz
download and then abort if too new (just like the hash)
| install error with no recent version | bun outdated respecting the
rule |
| --- | --- |
<img width="838" height="119" alt="image"
src="https://github.com/user-attachments/assets/b60916a8-27f6-4405-bfb6-57f9fa8bb0d6"
/> | <img width="609" height="314" alt="image"
src="https://github.com/user-attachments/assets/d8869ff4-8e16-492c-8e4c-9ac1dfa302ba"
/> |
For stable release we will make it use `3d` type syntax instead of magic
second numbers.
### How did you verify your code works?
tests & manual
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
### What does this PR do?
In Bun v1.2.22 a minification for `typeof x === "undefined"` → `typeof x
> "u"` was added. This introduced a regression causing `return (typeof x
!== "undefined", false)` to minify to invalid syntax when
`--minify-syntax` is enabled (this is also enabled for transpilation at
runtime).
This pr fixes the regression making sure `return (typeof x !==
"undefined", false);` minifies correctly to `return !1;`.
fixes#21137
### How did you verify your code works?
Added a regression test.
### What does this PR do?
A bug in our typescript parser was causing `module.foo = foo` to parse
as a typescript namespace. If it didn't end with a semicolon and there's
a statement on the next line it would cause a syntax error. Example:
```ts
module.foo = foo
foo.foo = foo
```
fixes#22929fixes#22883
### How did you verify your code works?
Added a regression test
### What does this PR do?
Adds `expect().toBe()` checks for anchors/aliases. Also adds git commit
the tests were translated from.
### How did you verify your code works?
Manually
adds environment variable for proper tmpdir setup
actual fix for
d2a4fb8124
(which was reverted)
this fixes flakyness in node:fs and node:cluster when using
scripts/runner.node.mjs locally with the --parallel flag
### What does this PR do?
Fixes bugs in the parser bringing it to 90% passing the official
[yaml-test-suite](https://github.com/yaml/yaml-test-suite) (362/400
passing tests)
Still missing from our parser: |- and |+ (about 5%), and cyclic
references.
Translates the yaml-test-suite to our tests.
fixes#22659fixes#22392fixes#22286
### How did you verify your code works?
Added tests for yaml-test-suite and each of the linked issues
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Fixes#23275
### What does this PR do?
This PR fixes a bug where `bunfig.toml` files starting with a UTF-8 BOM
(byte order mark, `U+FEFF` or bytes `0xEF 0xBB 0xBF`) would fail to
parse with an "Unexpected" error.
The fix uses Bun's existing `File.toSource()` function with
`convert_bom: true` option when loading config files. This properly
detects and strips the BOM before parsing, matching the behavior of
other file readers in Bun (like the JavaScript lexer which treats
`0xFEFF` as whitespace).
**Changes:**
- Modified `src/cli/Arguments.zig` to use `bun.sys.File.toSource()` with
BOM conversion instead of manually reading the file
- Simplified the config loading code by removing intermediate file
handle and buffer logic
### How did you verify your code works?
Added comprehensive regression tests in
`test/regression/issue/23275.test.ts` that verify:
1. ✅ `bunfig.toml` with UTF-8 BOM parses correctly without errors
2. ✅ `bunfig.toml` without BOM still works (regression test)
3. ✅ `bunfig.toml` with BOM and actual config content parses the content
correctly
All three tests pass with the debug build:
```
3 pass
0 fail
11 expect() calls
Ran 3 tests across 1 file. [6.41s]
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
The `bun outdated` command now displays catalog dependencies with their
workspace grouping even when run without the `--filter` or `-r` flags.
## What changed
- Added detection for catalog dependencies in the outdated packages list
- The workspace column is now shown when:
- Using `--filter` or `-r` flags (existing behavior)
- OR when there are catalog dependencies to display (new behavior)
- When there are no catalog dependencies and no filtering, the workspace
column remains hidden as before
## Why
Previously, running `bun outdated` without any flags would not show
which workspaces were using catalog dependencies, making it unclear
where catalog entries were being used. This fix ensures catalog
dependencies are properly grouped and displayed with their workspace
information.
## Test
```bash
# Create a workspace project with catalog dependencies
mkdir test-catalog && cd test-catalog
cat > package.json << 'JSON'
{
"name": "test-catalog",
"workspaces": ["packages/*"],
"catalog": {
"react": "^17.0.0"
}
}
JSON
mkdir -p packages/{app1,app2}
echo '{"name":"app1","dependencies":{"react":"catalog:"}}' > packages/app1/package.json
echo '{"name":"app2","dependencies":{"react":"catalog:"}}' > packages/app2/package.json
bun install
bun outdated # Should now show catalog grouping without needing --filter
```
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
During `yarn.lock` migration, OS/CPU package metadata was not being
fetched from the npm registry when missing from `yarn.lock`. This caused
packages with platform-specific requirements to not be properly marked,
potentially leading to incorrect package installation behavior.
## Changes
Updated `fetchNecessaryPackageMetadataAfterYarnOrPnpmMigration` to
conditionally fetch OS/CPU metadata:
- **For yarn.lock migration**: Fetches OS/CPU metadata from npm registry
when not present in yarn.lock (`update_os_cpu = true`)
- **For pnpm-lock.yaml migration**: Skips OS/CPU fetching since
pnpm-lock.yaml already includes this data (`update_os_cpu = false`)
### Files Modified
- `src/install/lockfile.zig` - Added comptime `update_os_cpu` parameter
and conditional logic to fetch OS/CPU metadata
- `src/install/yarn.zig` - Pass `true` to enable OS/CPU fetching for
yarn migrations
- `src/install/pnpm.zig` - Pass `false` to skip OS/CPU fetching for pnpm
migrations (already parsed from lockfile)
## Why This Approach
- `yarn.lock` format often doesn't include OS/CPU constraints, requiring
us to fetch from npm registry
- `pnpm-lock.yaml` already parses OS/CPU during migration (lines 618-621
in pnpm.zig), making additional fetching redundant
- Using a comptime parameter allows the compiler to optimize away the
unused code path
## Testing
- ✅ Debug build compiles successfully
- Tested that the function correctly updates `pkg_meta.os` and
`pkg_meta.arch` only when:
- `update_os_cpu` is `true` (yarn migration)
- Current values are `.all` (not already set)
- Package metadata is available from npm registry
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Added Claude Code hooks to prevent common development mistakes when
working on the Bun codebase.
## Changes
- Created `.claude/hooks/pre-bash-zig-build.js` - A pre-bash hook that
validates commands
- Created `.claude/settings.json` - Hook configuration
## Prevented Mistakes
1. **Running `zig build obj` directly** → Redirects to use `bun bd`
2. **Using `bun test` in development** → Must use `bun bd test` (or set
`USE_SYSTEM_BUN=1`)
3. **Combining snapshot updates with test filters** → Prevents
`-u`/`--update-snapshots` with `-t`/`--test-name-pattern`
4. **Running `bun bd` with timeout** → Build needs time to complete
without timeout
5. **Running `bun bd test` from repo root** → Must specify a test file
path to avoid running all tests
## Test plan
- [x] Tested all validation rules with various command combinations
- [x] Verified USE_SYSTEM_BUN=1 bypass works
- [x] Verified file path detection works correctly
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
- Adds birthtime (file creation time) support on Linux using the `statx`
syscall
- Stores birthtime in architecture-specific unused fields of the kernel
Stat struct (x86_64 and aarch64)
- Falls back to traditional `stat` on kernels < 4.11 that don't support
`statx`
- Includes comprehensive tests validating birthtime behavior
Fixes#6585
## Implementation Details
**src/sys.zig:**
- Added `StatxField` enum for field selection
- Implemented `statxImpl()`, `fstatx()`, `statx()`, and `lstatx()`
functions
- Stores birthtime in unused padding fields (architecture-specific for
x86_64 and aarch64)
- Graceful fallback to traditional stat if statx is not supported
**src/bun.js/node/node_fs.zig:**
- Updated `stat()`, `fstat()`, and `lstat()` to use statx functions on
Linux
**src/bun.js/node/Stat.zig:**
- Added `getBirthtime()` helper to extract birthtime from
architecture-specific storage
**test/js/node/fs/fs-birthtime-linux.test.ts:**
- Tests non-zero birthtime values
- Verifies birthtime immutability across file modifications
- Validates consistency across stat/lstat/fstat
- Tests BigInt stats with nanosecond precision
- Verifies birthtime ordering relative to other timestamps
## Test Plan
- [x] Run `bun bd test test/js/node/fs/fs-birthtime-linux.test.ts` - all
5 tests pass
- [x] Compare behavior with Node.js - identical behavior
- [x] Compare with system Bun - system Bun returns epoch, new
implementation returns real birthtime
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Packages with self dependencies at a different version were colliding
with the current version in the store node_modules. This pr nests them
in another node_modules
Example:
self-dep@1.0.2 has a dependency on self-dep@1.0.1.
self-dep@1.0.2 is placed here in:
`./node_modules/.bun/self-dep@1.0.2/node_modules/self-dep`
and it's self-dep dependency symlink is now placed in:
`./node_modules/.bun/self-dep@1.0.2/node_modules/self-dep/node_modules/self-dep`
fixes#22681
### How did you verify your code works?
Manually tested the linked issue is working, and added a test
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Enable compiler flags
Update SQLite amalgamation using https://www.sqlite.org/download.html
source code
[sqlite-src-3500400.zip](https://www.sqlite.org/2025/sqlite-src-3500400.zip)
with:
```bash
./configure CFLAGS="-DSQLITE_ENABLE_UPDATE_DELETE_LIMIT"
make sqlite3.c
```
This is the same version that before just with this adicional flag that
must be enabled when generating the amalgamation so we are actually able
to use this option. You can also see that without this the build will
happen but the feature will not be enable
https://buildkite.com/bun/bun/builds/27940, as informed in
https://www.sqlite.org/howtocompile.html topic 5.
### How did you verify your code works?
Add in CI two tests that check if the feature is enabled on windows
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Bun sometimes crashes with a segmentation fault while generating stack
traces.
the following might be happening in `remapZigException`:
1. The first populateStackTrace (OnlyPosition) sets `frames_len` (e.g.,
frames_len = 5)
613aea1787/src/bun.js/bindings/bindings.cpp (L4793)
```
[frame1, frame2, frame3, frame4, frame5]
```
2. Frame filtering in remapZigException reduces `frames_len` (e.g.,
frames_len = 3)
613aea1787/src/bun.js/VirtualMachine.zig (L2686-L2704)
```
[frame1, frame4, frame5, (frame4, frame5)]
// frame2 and frame3 are removed by filtering; frames_len is set to 3 here, but frame4 and frame5 remain in their original positions
```
3. The second populateStackTrace (OnlySourceLine) increases `frames_len`
(e.g., frames_len = 5)
613aea1787/src/bun.js/bindings/bindings.cpp (L4793)
```
[frame1, frame4, frame5, frame4, frame5]
```
When deinit is executed on these frames, the ref count is excessively
decremented (for frame4 and frame5), resulting in a UAF.
### How did you verify your code works?
WIP. I'm working on creating minimal reproduction code.
However, I've confirmed that `twenty-server` tests passes with this PR.
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
Increase the stack trace buffer size in the crash handler from 10 to 20
frames to ensure more useful frames are included in crash reports sent
to bun.report.
## Motivation
Currently, we capture up to 10 stack frames when generating crash
reports. However, many of these frames get filtered out when
`StackLine.fromAddress()` returns `null` for invalid/empty frames. This
results in only a small number of frames (sometimes as few as 5)
actually being sent to the server.
## Changes
- Increased `addr_buf` array size from `[10]usize` to `[20]usize` in
`src/crash_handler.zig:307`
## Impact
By capturing more frames initially, we ensure that after filtering we
still have a meaningful number of frames in the crash report. This will
help with debugging crashes by providing more context about the call
stack.
The encoding function `encodeTraceString()` has no hardcoded limits and
will encode all available frames, so this change directly translates to
more frames being sent to bun.report.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Parsing would fail because the lockfile version might be parsing as a
non-whole float instead of a string (`5.4` vs `'5.4'`) and the migration
would have the wrong error.
### How did you verify your code works?
Added a test
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
It's common for monorepos to exclude portions of a large glob
```json
"workspaces": [
"packages/**",
"!packages/**/test/**",
"!packages/**/template/**"
],
```
closes#4621 (note: patterns like `"packages/!(*-standalone)"` will need
to be written `"!packages/*-standalone"`)
### How did you verify your code works?
Manually tested https://github.com/opentiny/tiny-engine, and added a new
workspace test.
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Add `jsc.DecodedJSValue`, an extern struct which is ABI-compatible with
`JSC::JSValue`. (By contrast, `jsc.JSValue` is ABI-compatible with
`JSC::EncodedJSValue`.) This enables `jsc.Strong.get` to be more
efficient: it no longer has to call into C++.
(For internal tracking: fixes ENG-20748)
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Returning clause should work with insert now
### How did you verify your code works?
Tests
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Split `JSNodeHTTPServerSocket` and `JSNodeHTTPServerSocketPrototype`
from `NodeHTTP.cpp` into dedicated files, following the same pattern as
`JSDiffieHellman` in the crypto module.
## Changes
- **Created 4 new files:**
- `JSNodeHTTPServerSocket.h` - Class declaration
- `JSNodeHTTPServerSocket.cpp` - Class implementation and methods
- `JSNodeHTTPServerSocketPrototype.h` - Prototype declaration
- `JSNodeHTTPServerSocketPrototype.cpp` - Prototype methods and property
table
- **Moved from NodeHTTP.cpp:**
- All custom getters/setters (onclose, ondrain, ondata, etc.)
- All host functions (close, write, end)
- Event handlers (onClose, onDrain, onData)
- Helper functions and templates
- **Preserved:**
- All extern C bindings for Zig interop
- All existing functionality
- Proper namespace and include structure
- **Merged changes from main:**
- Added `upgraded` flag for websocket support (from #23150)
- Updated `clearSocketData` to handle WebSocketData
- Added `onSocketUpgraded` callback handler
## Impact
- Reduced `NodeHTTP.cpp` from ~1766 lines to 1010 lines (43% reduction)
- Better code organization and maintainability
- No functional changes
## Test plan
- [x] Build compiles successfully
- [x] `test/js/node/http/node-http.test.ts` passes (72/74 tests pass,
same as before)
- [x] `test/js/node/http/node-http-with-ws.test.ts` passes (websocket
upgrade test)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Add a new generator for JS → Zig bindings. The bulk of the conversion is
done in C++, after which the data is transformed into an FFI-safe
representation, passed to Zig, and then finally transformed into
idiomatic Zig types.
In its current form, the new bindings generator supports:
* Signed and unsigned integers
* Floats (plus a “finite” variant that disallows NaN and infinities)
* Strings
* ArrayBuffer (accepts ArrayBuffer, TypedArray, or DataView)
* Blob
* Optional types
* Nullable types (allows null, whereas Optional only allows undefined)
* Arrays
* User-defined string enumerations
* User-defined unions (fields can optionally be named to provide a
better experience in Zig)
* Null and undefined, for use in unions (can more efficiently represent
optional/nullable unions than wrapping a union in an optional)
* User-defined dictionaries (arbitrary key-value pairs; expects a JS
object and parses it into a struct)
* Default values for dictionary members
* Alternative names for dictionary members (e.g., to support both
`serverName` and `servername` without taking up twice the space)
* Descriptive error messages
* Automatic `fromJS` functions in Zig for dictionaries
* Automatic `deinit` functions for the generated Zig types
Although this bindings generator has many features not present in
`bindgen.ts`, it does not yet implement all of `bindgen.ts`'s
functionality, so for the time being, it has been named `bindgenv2`, and
its configuration is specified in `.bindv2.ts` files. Once all
`bindgen.ts`'s functionality has been incorporated, it will be renamed.
This PR ports `SSLConfig` to use the new bindings generator; see
`SSLConfig.bindv2.ts`.
(For internal tracking: fixes STAB-1319, STAB-1322, STAB-1323,
STAB-1324)
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Alistair Smith <hi@alistair.sh>
### What does this PR do?
Replaces '.upgrade()' with '.cloneUpgrade()'. '.upgrade()' is confusing
and `.clone().upgrade()` was causing a leak. Caught by
https://github.com/oven-sh/bun/pull/23199#discussion_r2400667320
### How did you verify your code works?
## Summary
- Fixed crypto.hkdf callback to pass `null` instead of `undefined` for
the error parameter on success
- Added regression test to verify the fix
## Details
Fixes#23211
Node.js convention requires crypto callbacks to receive `null` as the
error parameter on success, but Bun was passing `undefined`. This caused
compatibility issues with code that relies on strict null checks (e.g.,
[matter.js](fdbec2cf88/packages/general/src/crypto/NodeJsStyleCrypto.ts (L169))).
### Changes
- Updated `CryptoHkdf.cpp` to pass `jsNull()` instead of `jsUndefined()`
for the error parameter in the success callback
- Added regression test in `test/regression/issue/23211.test.ts`
## Test plan
- [x] Added regression test that verifies callback receives `null` on
success
- [x] Test passes with the fix
- [x] Ran existing crypto tests (no failures)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
## Summary
Fixes a segmentation fault on Windows 11 when accessing `process.title`
in certain scenarios (e.g., when fetching system information or making
Discord webhook requests).
## Root Cause
The crash occurred in libuv's `uv_get_process_title()` at `util.c:413`
in the `strlen()` call. The issue is that `uv__get_process_title()`
could return success (0) but leave `process_title` as NULL in edge cases
where:
1. `GetConsoleTitleW()` returns an empty string
2. `uv__convert_utf16_to_utf8()` succeeds but doesn't allocate memory
for the empty string
3. The subsequent `assert(process_title)` doesn't catch this in release
builds
4. `strlen(process_title)` crashes with a null pointer dereference
## Changes
Added defensive checks in `BunProcess.cpp`:
1. Initialize the title buffer to an empty string before calling
`uv_get_process_title()`
2. Check if the buffer is empty after the call returns
3. Fall back to "bun" if the title is empty or the call fails
## Testing
Added regression test in `test/regression/issue/23183.test.ts` that
verifies:
- `process.title` doesn't crash when accessed
- Returns a valid string (either the console title or "bun")
Fixes#23183🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Fixes `file:.` in root package.json or `file:../..` in workspace
package.json (if '../..' points to the root of the project)
### How did you verify your code works?
Added a test
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Replace `createJSBunRequestStructure()` call with direct access to the
cached structure in `JSBunRequest::clone()` method for better
performance.
## Changes
- Updated `JSBunRequest::clone()` to use
`m_JSBunRequestStructure.getInitializedOnMainThread()` instead of
calling `createJSBunRequestStructure()`
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
Fixes#23120
bun:test changes introduced an added 16-100ms sleep between test files.
For a test suite with many fast-running test files, this caused
significant impact. Elysia's test suite was running 2x slower (1.8s →
3.9s).
<img width="646" height="289" alt="image"
src="https://github.com/user-attachments/assets/2ecd8c3e-984c-4a9a-a988-a911576b87c4"
/>
### How did you verify your code works?
Running elysia test suite & minimized reproduction case
<details>
<summary>Minimzed reproduction case</summary>
```ts
// full2.test.ts
import { it } from 'bun:test'
it("timeout", () => {
setTimeout(() => {}, 295000);
}, 0);
// bench.ts
import {$} from "bun";
await $`rm -rf tests`;
await $`mkdir -p tests`;
for (let i = 0; i < 128; i += 1) {
await Bun.write(`tests/${i}.test.ts`, `
for (let i = 0; i < 1000; i ++) {
it("test${i}", () => {}, 0);
}
`);
}
Bun.spawnSync({
cmd: ["hyperfine", ...["bun-1.2.22", "bun-1.2.23+wakeup", "bun-1.2.23"].map(v => `${v} test ./full2.test.ts tests`)],
stdio: ["inherit", "inherit", "inherit"],
});
```
</details>
### What does this PR do?
Fix --rerun-each. Fixes#21409
### How did you verify your code works?
Test case
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Time should be represented as HH:MM:SS or HHH:MM:SS string
### How did you verify your code works?
Test
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Alistair Smith <hi@alistair.sh>
### What does this PR do?
handle socket upgrade in NodeHTTP.cpp
### How did you verify your code works?
Run the test added with asan it should catch the bug
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Previously, handleOom(anyerror!T) would return T and panic for
OutOfMemory for any error. fixes it to return anyerror!T for this case.
### How did you verify your code works?
CI
---------
Co-authored-by: taylor.fish <contact@taylor.fish>
### What does this PR do?
- **Use `Latin1Character` instead of `LChar`**
- **Fix for
0875bc8f62**
### How did you verify your code works?
---
# WebKit Update Summary (September 2025)
## Overview
This document summarizes the major changes in WebKit/JavaScriptCore from
the September 2025 update. The update includes approximately 254
JSC-related commits with significant improvements to performance,
stability, and developer experience.
## Critical Bug Fixes
### Memory Safety
- **operationMaterializeObjectInOSR fix** (5c7aadfa0a96): Fixed
uninitialized Butterfly storage during OSR exits with sunk Array
allocations. This prevents potential crashes when arrays with holes are
materialized during OSR exit.
- **FTL materialization fixes** (a72d19840714, ed1e6fe03899): Added
missing internal object type handling in FTL materialization, improving
stability during optimization bailouts.
### Promise and Async Improvements
- **JSPromiseReaction object** (a1cb5e087a46, later reverted in
b0566a4db201): Initially introduced to improve promise reaction handling
but was reverted due to compatibility issues with Bun's modifications.
- **Async stack traces enhancements**:
- Added support for `Promise.any` in async stack traces (d9a997b3edaa)
- Added empty JSValue checking for async stack trace safety
(9d26223d4bcb)
- Promise.all support was added and later reverted due to performance
concerns
## Performance Optimizations
### JIT Compiler Improvements
- **B3 Immutable Loads** (570a3530f949, 62300f8db3d9): Added
immutability annotations and CSE optimizations for loads that can look
for targets in dominators
- **BBQ JIT enhancements**:
- Fixed callee-save register handling (c7ae05719045)
- Simplified F32 copysign operations (e0651af57025)
- **DFG optimizations**:
- Fixed RegExp constant folding with materialized NewRegExp nodes
(7b53a04a5afa)
- Improved RegExp object node handling in strength reduction
(eeb65e05095b)
### WebAssembly Improvements
- **WASM SIMD Support**:
- Added v128 support for IPInt call and tail-call instructions
(73f0c9d430cb)
- Implemented v128 support in local.get, local.set, global.get,
global.set (67d7bf15139a)
- Added x86_64 SIMD integer arithmetic and float instructions
- **WASM Memory Management**:
- Introduced WasmInstanceAnchor for better instance lifecycle management
(f9f1ed183bf7)
- Attached AbstractHeap to wasm memory access for better optimization
(f183c6f7def4)
- Added signal handling for null checks in wasm (bf18b5b709f3)
- **WASM Debugging**: Added LLDB debugging infrastructure for
WebAssembly (e03c10225cc8)
## API and Language Features
### Iterator Helpers
- Merged `Iterator.prototype.sliding` into `Iterator.prototype.windows`
(1d49e823702d)
- Optimized iterator next method calls using CachedCall (5ee92514060c)
### Math Extensions
- Improved performance of `Math.sumPrecise` implementation
(602294057337)
### Error Handling
- Enhanced error messages for for-of loops without Symbol.iterator
(0051bbf2491f)
## Infrastructure Changes
### Character Type Refactoring
- **LChar to Latin1Character rename** (63b97b511366, 1424f0687876):
Major refactoring replacing the `LChar` type with `Latin1Character`
throughout the codebase for better clarity
- Additional fixes for Latin1Character usage (711eab3243f0,
50bf8e6fd4ca, 88e29ab76aec)
### Build System
- Fixed builds with GCC 15.x (e33b18bc59d6)
- Added gitattributes for JSC test files (82c4cc796da6)
- Improved test runner with comprehensive verbose logging (7ef95c177a42)
- Added memory-limited annotations for tests using excessive memory
(b991cd17d612)
### Testing Infrastructure
- Improved handling of missing test executables (db1e3bbb3be2)
- Added support for non-customized ICU 74.2 in intl tests (c922a28b6642)
- Fixed various test configuration issues and timeouts
## Bun-Specific Modifications
### Preserved Customizations
- Maintained `BUN_JSC_ADDITIONS` for Bun-specific features
- Kept async context support for AsyncLocalStorage
- Preserved V8 heap snapshot compatibility layer
- Maintained custom inspector extensions
### Conflicts Resolved
- Successfully merged upstream changes while preserving Bun's event loop
integration
- Resolved conflicts in promise handling while maintaining Bun's async
behavior
- Fixed re-declaration issues with `isAsyncFrame` for async stack traces
## Breaking Changes and Reverts
### Reverted Features
1. **JSPromiseReaction object**: Reverted due to conflicts with Bun's
promise handling
2. **Promise.all async stack trace support**: Reverted due to ~4%
performance regression in JetStream3/doxbee-async benchmark
3. **Array.prototype.flat C++ implementation**: Reverted (reason not
specified in commit)
## Security Improvements
- Type safety improvements with uncheckedDowncast for Wasm::Callee
(48425afd643d)
- Added bounds checking and validation for Wasm array operations
(b5148db1c4c1)
- Improved memory safety with proper initialization of materialized
objects
## Platform Support
- macOS: Continued support for x64/arm64
- Linux: Maintained glibc/musl compatibility
- Windows: Preserved x64 support
- Fixed platform-specific alignment issues for x86_64 (94a60eb123c5)
## Notable Debugging Enhancements
- LLDB infrastructure for WebAssembly debugging
- Improved verbose command logging in test runners
- Enhanced stack trace capabilities for async functions
- Better error reporting for missing Symbol.iterator
## Performance Metrics
- Several memory optimizations for test execution
- JIT memory reservation size adjustments for debug builds
- Optimized iterator operations with cached calls
- Improved Math.sumPrecise performance
## Future Considerations
- The JSPromiseReaction implementation may need revisiting with adjusted
architecture
- Async stack trace support for Promise.all requires performance
optimization
- Continued work on WASM SIMD support for additional operations
## Migration Notes for Bun Team
1. **LChar usage**: All references to `LChar` have been replaced with
`Latin1Character`
2. **Promise handling**: The reverted JSPromiseReaction changes indicate
potential architectural conflicts that may need addressing
3. **Test configuration**: New memory-limited annotations should be used
for memory-intensive tests
4. **Build flags**: Ensure USE_BUN_JSC_ADDITIONS and USE_BUN_EVENT_LOOP
remain enabled
### What does this PR do?
This PR enables `--useExplicitResourceManagement` JSC option by default,
to expose following builtins:
- `DisposableStack`
- `AsyncDisposableStack`
- `Iterator@@dispose`
- `AsyncIterator@@asyncDispose`
### How did you verify your code works?
These features are fully tested on JSC side.
Multiple inline snapshots from one call should be avoided because they
will cause problems if one changes but not the other, but this allows
them if they both have the same value.
### What does this PR do?
bad:
```ts
function oops(a) {
expect(a).toMatchInlineSnapshot();
}
test("whoops", () => {
oops(1);
oops(2);
});
```
```
2 | expect(a).toMatchInlineSnapshot();
^
error: Failed to update inline snapshot: Multiple inline snapshots on the same line must all have the same value:
Expected: 1
Received: 2
at /Users/pfg/Dev/Node/bun/repro.ts:2:35
```
acceptable:
```ts
function ok(a) {
expect(a).toMatchInlineSnapshot(`1`);
}
test("whokay", () => {
ok(1);
ok(1);
});
```
```
✓ whokay
1 pass
0 fail
snapshots: +1 added
2 expect() calls
```
### How did you verify your code works?
TODO: add tests
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
* Fix `memory.deinit`; the previous PR erroneously added non-comptime
code in a comptime expression, which would result in a compile error
when trying to deinit an optional
* Handle arrays (distinct from slices)
* Handle error unions
* Disallow untagged unions, as this is probably an error; usually a
manual deinit impl is needed if untagged unions are involved
* Make switch exhaustive so we know we're not missing other types
(thanks @pfgithub)
(For internal tracking: fixes STAB-1295)
### What does this PR do?
Status should reflect connect status now, making sure that js value is
alive long enough, redis still needs a refactor followup.
### How did you verify your code works?
Run valkey.test.ts duplicate tests 1k times
## Summary
This PR continues the work from #22107 to fix the `--tolerate-republish`
flag implementation in `bun publish`.
### Changes:
- **Pre-check version existence**: Before attempting to publish with
`--tolerate-republish`, check if the version already exists on the
registry
- **Improved version checking**: Use GET request to package endpoint
instead of HEAD, then parse JSON response to check if specific version
exists
- **Correct output stream**: Output warning to stderr instead of stdout
for consistency with test expectations
- **Better error handling**: Update test to accept both 403 and 409 HTTP
error codes for duplicate publish attempts
### Test fixes:
The tests were failing because:
1. The mock registry returns 409 Conflict (not 403) for duplicate
packages
2. The warning message wasn't appearing in stderr as expected
3. The version check was using HEAD request which doesn't reliably
return version info
## Test plan
- [x] Fixed failing tests for `--tolerate-republish` functionality
- [x] Tests now properly handle both 403 and 409 error responses
- [x] Warning messages appear correctly in stderr
🤖 Generated with [Claude Code](https://claude.ai/code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
### What does this PR do?
Fixes a crash related to the dev server overwriting the uws user context
pointer when setting abort callback.
Adds support for `return new Response(<jsx />, { ... })` and `return
Response.render(...)` and `return Response.redirect(...)`:
- Created a `SSRResponse` class to handle this (see
`JSBakeResponse.{h,cpp}`)
- `SSRResponse` is designed to "fake" being a React component
- This is done in JSBakeResponse::create inside of
src/bun.js/bindings/JSBakeResponse.cpp
- And `src/js/builtins/BakeSSRResponse.ts` defines a `wrapComponent`
function which wraps
the passed in component (when doing `new Response(<jsx />, ...)`). It
does
this to throw an error (in redirect()/render() case) or return the
component.
- Created a `BakeAdditionsToGlobal` struct which contains some
properties
needed for this
- Added some of the properties we need to fake to BunBuiltinNames.h
(e.g.
`$$typeof`), the rationale behind this is that we couldn't use
`structure->addPropertyTransition` because JSBakeResponse is not a final
JSObject.
- When bake and server-side, bundler rewrites `Response ->
Bun.SSRResponse` (see `src/ast/P.zig` and `src/ast/visitExpr.zig`)
- Created a new WebCore body variant (`Render: struct { path: []const u8
}`)
- Created when `return Response.render(...)`
- When handled, it re-invokes dev server to render the new path
Enables server-side sourcemaps for the dev server:
- New source providers for server-side:
(`DevServerSourceProvider.{h,cpp}`)
- IncrementalGraph and SourceMapStore are updated to support this
There are numerous other stuff:
- allow `app` configuration from Bun.serve(...)
- fix errors stopping dev server
- fix use after free related to in
RequestContext.finishRunningErrorHandler
- Request.cookies
- Make `"use client";` components work
- Fix some bugs using `require(...)` in dev server
- Fix catch-all routes not working in the dev server
- Updates `findSourceMappingURL(...)` to use `std.mem.lastIndexOf(...)`
because
the sourcemap that should be used is the last one anyway
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Alistair Smith <hi@alistair.sh>
## Summary
Fixes all oxlint `no-unused-expressions` violations across the codebase
by:
- Adding an oxlint override to disable the rule for
`src/js/builtins/**`, where special syntax markers like `$getter`,
`$constructor`, etc. are intentionally used as standalone expressions
- Converting short-circuit expressions (`condition && fn()`) to proper
if statements for improved code clarity
- Wrapping intentional property access side effects (e.g.,
`this.stdio;`, `err.stack;`) with the `void` operator
- Converting ternary expressions used for control flow to if/else
statements
## Test plan
- [x] `bun lint` passes with no errors
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
- Documents zstd compression features introduced in Bun v1.2.14
- Adds missing API documentation for zstd utilities
## Changes
- Updated `docs/api/fetch.md` to include zstd in Accept-Encoding
examples and note automatic decompression support
- Added `Bun.zstdCompress()/zstdCompressSync()` and
`Bun.zstdDecompress()/zstdDecompressSync()` documentation to
`docs/api/utils.md`
- Documented compression levels (1-22) with concise usage examples
## Note
HTTP/2 features (`maxSendHeaderBlockLength` and `setNextStreamID`) were
not added per request to avoid updating nodejs-apis.md.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
### What does this PR do?
Two things:
- we weren't adding the root package to the `pkg_map`.
- `link:` dependency paths in `"snapshots"` weren't being joined with
the top level dir.
### How did you verify your code works?
Manually and added a test.
## Summary
This PR adds concise documentation for features introduced in Bun
v1.2.23 that were missing from the docs.
## Added Documentation
- **pnpm migration**: Automatic `pnpm-lock.yaml` to `bun.lock` migration
- **Platform filtering**: `--cpu` and `--os` flags for cross-platform
dependency installation
- **Test improvements**: Chaining test qualifiers (e.g.,
`.failing.each`)
- **CLI**: `bun feedback` command
- **TLS/SSL**: `--use-system-ca` flag and `NODE_USE_SYSTEM_CA`
environment variable
- **Node.js compat**: `process.report.getReport()` Windows support
- **Bundler**: New `jsx` configuration object in `Bun.build`
- **SQL**: `sql.array` helper for PostgreSQL arrays
## Test plan
Documentation changes only - reviewed for accuracy against the v1.2.23
release notes.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
- Document automatic yarn.lock migration in lockfile docs
- Add --recursive flag documentation for bun outdated/update commands
- Document Windows long path support in installation docs
## Test plan
Documentation only - no code changes to test.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
This PR adds documentation for features introduced in Bun v1.2.19 that
were missing from the docs.
## Features Documented
### `.npmrc` Options
- `link-workspace-packages`: Controls how workspace packages are
installed when available locally
- `save-exact`: Always saves exact versions without the `^` prefix
### Node.js API Enhancements
- `vm.constants.DONT_CONTEXTIFY`: Support for making `globalThis` behave
like typical `globalThis`
- `os.networkInterfaces()`: Now returns `scopeid` property for IPv6
interfaces (not `scope_id`)
- `process.features.typescript`: Returns `"transform"`
- `process.features.require_module`: Returns `true`
- `process.features.openssl_is_boringssl`: Returns `true`
### `fs.glob` Enhancements
- Support for array of patterns as first argument
- New `exclude`/`ignore` option to filter results
### `node:module` API
- `SourceMap` class for parsing and inspecting sourcemaps
- `findSourceMap()` function to locate sourcemaps
## Changes Made
- `/docs/install/npmrc.md`: Added `link-workspace-packages` and
`save-exact` options
- `/docs/runtime/nodejs-apis.md`: Added Node.js compatibility features
- `/docs/api/glob.md`: Added Node.js fs.glob compatibility section
Documentation was kept concise with high information density as
requested.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
Updates documentation to include features released in Bun v1.2.17 that
were missing from the docs:
- ✅ HTML imports ahead-of-time bundling (already documented)
- ✅ columnTypes & declaredTypes in bun:sqlite (already documented, just
not visible in diff as it was recent)
- ✅ bun info command (already documented)
- ✅ Node.js compatibility improvements (partially documented, added
missing details)
- ✅ --unhandled-rejections flag (added)
- ✅ CLAUDE.md generation in bun init (added)
## Changes
- Document `--unhandled-rejections` CLI flag for configuring promise
rejection handling
- Document `CLAUDE.md` file generation in `bun init` when Claude CLI is
detected
- Update Node.js compatibility notes with recent improvements:
- `child_process.fork()` execArgv support
- Zstandard compression in `node:zlib`
- Optional options parameter in `fs.glob`
- `tls.getCACertificates()` implementation
## Test plan
Documentation changes only - no code changes to test.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
- Adds documentation for catalog dependency support in `bun outdated`
command
## Changes
- **`docs/cli/outdated.md`**: Added catalog dependency support section
with example output
## Test plan
- [x] Documentation is minimal and concise
- [x] Example shows clear output format with "(catalog)" labels
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
- Document missing features from Bun v1.2.15 release
- Add minimal, concise documentation updates with high information
density
## Changes
- Add `BUN_OPTIONS` environment variable to docs/runtime/env.md
- Document Cursor AI rules generation in `bun init` (docs/cli/init.md)
- Update Node.js API compatibility status for `Worker.getHeapSnapshot`
and `createHistogram` (docs/runtime/nodejs-apis.md)
- Add concise `vm.SourceTextModule` usage example
## Test plan
- [x] Documentation builds correctly
- [x] All links are valid
- [x] Code examples are accurate
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
- Added documentation for all new features from Bun v1.2.18 release
- Updates are minimal and concise with high information density
- Includes relevant code examples where helpful
## Updates made
### New features documented:
- ReadableStream convenience methods (`.text()`, `.json()`, `.bytes()`,
`.blob()`)
- WebSocket client permessage-deflate compression support
- NODE_PATH environment variable support for bundler
- bun test exits with code 1 when no tests match filter
- Math.sumPrecise for high-precision floating-point summation
### Version updates:
- Node.js compatibility version updated to v24.3.0
- SQLite version updated to 3.50.2
### Behavior changes:
- fs.glob now matches directories by default (not just files)
## Test plan
- [x] Verified all features are from the v1.2.18 release notes
- [x] Checked documentation follows existing patterns
- [x] Code examples are concise and accurate
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
- Updated test assertion to match new error message format for git clone
failures
## Details
The error message format changed from:
```
error: "git clone" for "uglify" failed
```
To:
```
error: InstallFailed cloning repository for uglify
```
This appears to be due to changes in how 404s work on the bun.sh domain.
## Test plan
- [x] Ran `bun bd test test/cli/install/bun-install.test.ts -t "should
fail on invalid Git URL"` - passes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Added documentation for 5 features introduced in Bun v1.2.21 that were
missing from the docs
- Kept updates minimal with high information density as requested
## Changes
- **bun audit filtering options** (`docs/install/audit.md`)
- `--audit-level=<low|moderate|high|critical>` - filter by severity
- `--prod` - audit only production dependencies
- `--ignore <CVE>` - ignore specific vulnerabilities
- **--compile-exec-argv flag** (`docs/bundler/executables.md`)
- Embed runtime arguments in compiled executables
- Arguments available via `process.execArgv`
- **bunx --package/-p flag** (`docs/cli/bunx.md`)
- Run binaries from specific packages when name differs
- **package.json sideEffects glob patterns** (`docs/bundler/index.md`)
- Support for `*`, `?`, `**`, `[]`, `{}` patterns
- **--user-agent CLI flag** (`docs/cli/run.md`)
- Customize User-Agent header for all fetch() requests
## Test plan
- [x] Reviewed all changes match Bun v1.2.21 blog post features
- [x] Verified documentation style is concise with code examples
- [x] Checked no existing documentation was removed
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Added documentation for worker_threads environmentData API and process
'worker' event
- Added documentation for --no-addons CLI flag
- Added documentation for RedisClient getBuffer() method
## Context
These features were released in Bun v1.2.13 but were missing from the
documentation.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
Adds minimal documentation for features introduced in Bun v1.2.22 that
were previously undocumented.
## Changes
- Add `redis.hget()` example showing direct value return vs `hmget()`
array
- Add WebSocket subprotocol negotiation example with array syntax
- Mark bundler `onEnd` hook as implemented in plugins docs
- Add `bun run --workspaces` flag documentation
- Update `perf_hooks.monitorEventLoopDelay` as implemented in Node.js
APIs
- Add async stack traces note to debugger docs
- Document TTY access pattern after stdin closes
All changes are minimal - just code snippets or single-line mentions in
existing files. No new files created.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
## Summary
- Fixed segmentation fault when calling `toContainAnyKeys`,
`toContainKeys`, and `toContainAllKeys` on non-object values (null,
undefined, numbers, strings, etc.)
- Added proper validation to check if value is an object before calling
`hasOwnPropertyValue` or `keys()`
- Added comprehensive test coverage for edge cases
## Problem
The matchers were crashing with a segmentation fault when called with
non-object values because:
1. `toContainAnyKeys` and `toContainKeys` were calling
`hasOwnPropertyValue` without checking if the value is an object first
2. `toContainAllKeys` was calling `keys()` without checking if the value
is an object first
3. The `hasOwnPropertyValue` function documentation explicitly states:
"If the object is not an object, it will crash. **You must check if the
object is an object before calling this function.**"
## Solution
- Added `value.isObject()` check in `toContainAnyKeys` before attempting
to check for properties
- Fixed `toContainKeys` by replacing the `toBoolean()` check with
`isObject()` check
- Fixed `toContainAllKeys` by adding proper object validation before
calling `keys()`
- For non-objects with empty expected arrays, the matchers return true
(matching jest-extended behavior)
## Test plan
- [x] Added comprehensive test coverage in
`test/js/bun/test/expect.test.js`
- [x] Tests cover: null, undefined, numbers, strings, booleans, symbols,
BigInt, arrays, functions
- [x] All existing jest-extended tests continue to pass
- [x] Debug build compiles and all tests pass
🤖 Generated with [Claude Code](https://claude.ai/code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
### What does this PR do?
Missing `.t_equals` and `.t_slash` checks. This matches esbuild.
```go
// Returns true if the current less-than token is considered to be an arrow
// function under TypeScript's rules for files containing JSX syntax
func (p *parser) isTSArrowFnJSX() (isTSArrowFn bool) {
oldLexer := p.lexer
p.lexer.Next()
// Look ahead to see if this should be an arrow function instead
if p.lexer.Token == js_lexer.TConst {
p.lexer.Next()
}
if p.lexer.Token == js_lexer.TIdentifier {
p.lexer.Next()
if p.lexer.Token == js_lexer.TComma || p.lexer.Token == js_lexer.TEquals {
isTSArrowFn = true
} else if p.lexer.Token == js_lexer.TExtends {
p.lexer.Next()
isTSArrowFn = p.lexer.Token != js_lexer.TEquals && p.lexer.Token != js_lexer.TGreaterThan && p.lexer.Token != js_lexer.TSlash
}
}
// Restore the lexer
p.lexer = oldLexer
return
}
```
fixes#19697
### How did you verify your code works?
Added some tests.
### What does this PR do?
Fixes code like `[(()=>{})()][''+'c']`.
We were calling `visitExpr` on a node that was already visited. This
code doesn't exist in esbuild, but we should keep it because it's an
optimization.
fixes#18629fixes#15926
### How did you verify your code works?
Manually and added a test.
### What does this PR do?
esbuild returns `left` from the inner loop. This PR matches this
behavior. Before it was breaking out of the inner loop and continuing
through the outer loop, potentially parsing too far.
fixes#22013fixes#22384
### How did you verify your code works?
Added some tests.
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Given pattern input "../." we might collapse all path components.
### How did you verify your code works?
Manually and added a test.
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
### What does this PR do?
fix#23001 by removing references to old codelens from before the native
integration which should have its own (better and) native way of
starting
### How did you verify your code works?
## Summary
- Fixes V8StackTraceIterator terminating early when encountering stack
frames without parentheses (e.g., "at unknown")
- Ensures complete stack traces are shown by `Bun.inspect()` even after
`error.stack` property is accessed
- Addresses the root cause that PR #23022 was working around
## Problem
When the V8StackTraceIterator encountered a stack frame line without
parentheses (like `at unknown`), it would:
1. Set `offset = stack.length()`
2. Return `false`, terminating the entire iteration
3. Only parse frames before the "unknown" frame
This caused `Bun.inspect()` to show incomplete stack traces after the
`error.stack` property was accessed, as documented in issue discussions
around PR #23022.
## Solution
Changed the parser to continue iterating through subsequent frames
instead of terminating. Frames without parentheses are now treated as
having a source URL but no function name or location info.
## Test plan
- [x] Added regression test
`test/regression/issue/23022-stack-trace-iterator.test.ts`
- [x] Verified existing stack trace tests still pass
- [x] Manually tested with Node.js stream errors that trigger this code
path
### Before fix:
```
error: Socket is closed
code: "ERR_SOCKET_CLOSED"
at node:net:1322:32
```
### After fix:
```
error: Socket is closed
code: "ERR_SOCKET_CLOSED"
at unknown:1:1
at _write (node:net:1322:32)
at writeOrBuffer (internal:streams/writable:381:18)
at internal:streams/writable:334:16
at testStackTrace (/workspace/bun/test.js:8:10)
...
```
🤖 Generated with [Claude Code](https://claude.ai/code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
fixes#7157, fixes#14662
migrates pnpm-workspace.yaml data to package.json & converts
pnpm-lock.yml to bun.lock
---
### How did you verify your code works?
manually, tests and real world examples
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
Currently, if you try to deinit an optional, `bun.memory.deinit` will
silently do nothing, even if the optional's payload is a struct with a
`deinit` method.
This commit makes sure the payload is deinitialized.
(For internal tracking: fixes STAB-1293)
### What does this PR do?
Previously `redis.subscribe` did not automatically connect, which was in
contrast to other Redis functions. This PR changes the necessary
`PUB/SUB` things so that `.subscribe` automatically connects.
### How did you verify your code works?
Didn't
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
it caused deploying the site to hang and `ref.ref(` isnt threadsafe. the
proper fix should latch onto the shell command instead of the generic
task queue
### What does this PR do?
Currently bundling and running projects with cyclic async module
dependencies will hang due to module promises never resolving. This PR
unblocks these projects by outputting `await Promise.all` with these
dependencies.
Before (will hang with bun, or error with unsettled top level await with
node):
```js
var __esm = (fn, res) => () => (fn && (res = fn((fn = 0))), res);
var init_mod3 = __esm(async () => {
await init_mod1();
});
var init_mod2 = __esm(async () => {
await init_mod1();
});
var init_mod1 = __esm(async () => {
await init_mod2();
await init_mod3();
});
await init_mod1();
```
After:
```js
var __esm = (fn, res) => () => (fn && (res = fn((fn = 0))), res);
var __promiseAll = Promise.all.bind(Promise);
var init_mod3 = __esm(async () => {
await init_mod1();
});
var init_mod2 = __esm(async () => {
await init_mod1();
});
var init_mod1 = __esm(async () => {
await __promiseAll([init_mod2(), init_mod3()]);
});
await init_mod1();
```
### How did you verify your code works?
Manually and tests
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
Fix tls property not being properly set
Fixes https://github.com/oven-sh/bun/issues/22186
### How did you verify your code works?
Tests + Manually test with upstash using `rediss` protocol and tls: true
options
---------
Co-authored-by: Marko Vejnovic <marko.vejnovic@hotmail.com>
Co-authored-by: Marko Vejnovic <marko@bun.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Reduce the size of `bun.webcore.Blob` from 120 bytes to 96. Also make it
ref-counted: in-progress work on improving the bindings generator
depends on this, as it means C++ can pass a pointer to the `Blob` to Zig
without risking it being destroyed if the GC collects the associated
`JSBlob`.
Note that this PR depends on #23013.
(For internal tracking: fixes STAB-1289, STAB-1290)
### What does this PR do?
Adds a max-concurrency flag to limit the amount of concurrent tests that
run at once. Defaults to 20. Jest and Vitest both default to 5.
### How did you verify your code works?
Tests
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Add a version of `ArrayList` that takes a generic `Allocator` type
parameter. This matches the interface of smart pointers like
`bun.ptr.Owned` and `bun.ptr.Shared`.
This type behaves like a managed `ArrayList` but has no overhead if
`Allocator` is a zero-sized type, like `bun.DefaultAllocator`.
(For internal tracking: fixes STAB-1267)
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Add `bun.ptr.ExternalShared`, a shared pointer whose reference count is
managed externally; e.g., by extern functions. This can be used to work
with `RefCounted` C++ objects in Zig. For example:
```cpp
// C++:
struct MyType : RefCounted<MyType> { ... };
extern "C" void MyType__ref(MyType* self) { self->ref(); }
extern "C" void MyType__ref(MyType* self) { self->deref(); }
```
```zig
// Zig:
const MyType = opaque {
extern fn MyType__ref(self: *MyType) void;
extern fn MyType__deref(self: *MyType) void;
pub const Ref = bun.ptr.ExternalShared(MyType);
// This enables `ExternalShared` to work.
pub const external_shared_descriptor = struct {
pub const ref = MyType__ref;
pub const deref = MyType__deref;
};
};
// Now `MyType.Ref` behaves just like `Ref<MyType>` in C++:
var some_ref: MyType.Ref = someFunctionReturningMyTypeRef();
const ptr: *MyType = some_ref.get(); // gets the inner pointer
var some_other_ref = some_ref.clone(); // increments the ref count
some_ref.deinit(); // decrements the ref count
// decrements the ref count again; if no other refs exist, the object
// is destroyed
some_other_ref.deinit();
```
This commit also adds `RawRefCount`, a simple wrapper around an integer
reference count that can be used to implement the interface required by
`ExternalShared`. Generally, for reference-counted Zig types,
`bun.ptr.Shared` is preferred, but occasionally it is useful to have an
“intrusive” reference-counted type where the ref count is stored in the
type itself. For this purpose, `ExternalShared` + `RawRefCount` is more
flexible and less error-prone than the deprecated `bun.ptr.RefCounted`
type.
(For internal tracking: fixes STAB-1287, STAB-1288)
## Summary
Improves server stability when handling certain request edge cases.
## Test plan
- Added regression test in `test/regression/issue/22353.test.ts`
- Test verifies server continues operating normally after handling edge
case requests
- All existing HTTP server tests pass
Fixes#22353🤖 Generated with [Claude Code](https://claude.ai/code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
fixes an issue where fetch requests with `Content-Type:
application/x-www-form-urlencoded` would not include the request body in
curl logs when `BUN_CONFIG_VERBOSE_FETCH=curl` is enabled
previously, only JSON and text-based content types were recognized as
safe-to-print in the curl formatter. This change updates the allow-list
to also handle `application/x-www-form-urlencoded`, ensuring bodies for
common form submissions are shown in logs
### How did you verify your code works?
- added `Content-Type: application/x-www-form-urlencoded` to a fetch
request and confirmed that `BUN_CONFIG_VERBOSE_FETCH=curl` now outputs a
`--data-raw` section with the encoded body
- verified the fix against the reproduction script provided in issue
#12042
- created and ran a regression test
- checked that existing content types (JSON, text, etc.) continue to
print correctly
fixes#12042
### What does this PR do?
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
**This PR is created because [the previous PR I
opened](https://github.com/oven-sh/bun/pull/21728) had some concerning
issues.** Thanks @Jarred-Sumner for the help.
The goal of this PR is to introduce PUB/SUB functionality to the
built-in Redis client. Based on the fact that the current Redis API does
not appear to have compatibility with `io-redis` or `redis-node`, I've
decided to do away with existing APIs and API compatibility with these
existing libraries.
I have decided to base my implementation on the [`redis-node` pub/sub
API](https://github.com/redis/node-redis/blob/master/docs/pub-sub.md).
#### Random Things That Happened
- [x] Refactored the build scripts so that `valgrind` can be disabled.
- [x] Added a `numeric` namespace in `harness.ts` with useful
mathematical libraries.
- [x] Added a mechanism in `cppbind.ts` to disable static assertions
(specifically to allow `check_slow` even when returning a `JSValue`).
Implemented via `// NOLINT[NEXTLINE]?\(.*\)` macros.
- [x] Fixed inconsistencies in error handling of `JSMap`.
### How did you verify your code works?
I've written a set of unit tests to hopefully catch the major use-cases
of this feature. They all appear to pass.
#### Future Improvements
I would have a lot more confidence in our Redis implementation if we
tested it with a test suite running over a network which emulates a high
network failure rate. There are large amounts of edge cases that are
worthwhile to grab, but I think we can roll that out in a future PR.
### Future Tasks
- [ ] Tests over flaky network
- [ ] Use the custom private members over `_<member>`.
---------
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
### What does this PR do?
### How did you verify your code works?
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
## Summary
- Fixed a double-free bug in the `createArgv` function in
`node_process.zig`
## Details
The `createArgv` function had two `defer allocator.free(args)`
statements:
- One on line 164
- Another on line 192 (now removed)
This would cause the same memory to be freed twice when the function
returned, leading to undefined behavior.
Fixes#22975
## Test plan
The existing process.argv tests should continue to pass with this fix.
🤖 Generated with [Claude Code](https://claude.ai/code)
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Outputs the seed when randomizing. Adds --seed flag to reproduce a
random order. Seeds might not produce the same order across operating
systems / bun versions.
Fixes#11847
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
### How did you verify your code works?
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
This assertion is occasionally incorrect, and was originally added as a
workaround for lack of proper error handling in zig's std library. We've
seen fixed that so this assertion is no longer needed.
### How did you verify your code works?
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### What does this PR do?
Adds a `bun run build:debug:noasan` run script and deletes the `bun run
build:debug:asan` rule.
### How did you verify your code works?
Ran the change locally.
## Summary
Implements authenticode signature stripping for Windows PE files when
using `bun build --compile`, ensuring that generated executables can be
properly signed with external tools after Bun embeds its data section.
## What Changed
### Core Implementation
- **Authenticode stripping**: Removes digital signatures from PE files
before adding the .bun section
- **Safe memory access**: Replaced all `@alignCast` operations with safe
unaligned access helpers to prevent crashes
- **Hardened PE parsing**: Added comprehensive bounds checking and
validation throughout
- **PE checksum recalculation**: Properly updates checksums after
modifications
### Key Features
- Always strips authenticode signatures when using `--compile` for
Windows (uses `.strip_always` mode)
- Validates PE file structure according to PE/COFF specification
- Handles overlapping memory regions safely during certificate removal
- Clears `IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY` flag when stripping
signatures
- Ensures no unexpected overlay data remains after stripping
### Bug Fixes
- Fixed memory corruption bug using `copyBackwards` for overlapping
regions
- Fixed checksum calculation skipping 6 bytes instead of 4
- Added integer overflow protection in payload size calculations
- Fixed double alignment bug in `size_of_image` calculation
## Technical Details
The implementation follows the Windows PE/COFF specification and
includes:
- `StripMode` enum to control when signatures are stripped
(none/strip_if_signed/strip_always)
- Safe unaligned memory access helpers (`viewAtConst`, `viewAtMut`)
- Proper alignment helpers with overflow protection (`alignUpU32`,
`alignUpUsize`)
- Comprehensive error types for all failure cases
## Testing
- Passes all existing PE tests in
`test/regression/issue/pe-codesigning-integrity.test.ts`
- Compiles successfully with `bun run zig:check-windows`
- Properly integrated with StandaloneModuleGraph for Windows compilation
## Impact
This ensures Windows users can:
1. Use `bun build --compile` to create standalone executables
2. Sign the resulting executables with their own certificates
3. Distribute properly signed Windows binaries
Fixes issues where previously signed executables would have invalid
signatures after Bun added its embedded data.
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
## Summary
- Fixes unnecessary regeneration of `bun_dependency_versions.h` on every
CMake run
- Only writes the header file when content actually changes
## Test plan
Tested locally by running CMake configuration multiple times:
1. First run generates the file (shows "Updated dependency versions
header")
2. Subsequent runs skip writing (shows "Dependency versions header
unchanged")
3. File modification timestamp remains unchanged when content is the
same
4. File is properly regenerated when deleted or when content changes
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
### What does this PR do?
When we added "happy eyeballs" support to fetch(), it meant that
`onOpen` would not be called potentially for awhile. If the AbortSignal
is aborted between `connect()` and the socket becoming
readable/writable, then we would delay closing the connection until the
connection opens. Fixing that fixes#18536.
Separately, the `isHTTPS()` function used in abort and in request body
streams was not thread safe. This caused a crash when many redirects
happen simultaneously while either AbortSignal or request body messages
are in-flight.
This PR fixes https://github.com/oven-sh/bun/issues/14137
### How did you verify your code works?
There are tests
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Ciro Spaciari <ciro.spaciari@gmail.com>
## Summary
This PR adds a `--randomize` flag to `bun test` that shuffles test
execution order. This helps developers catch test interdependencies and
identify flaky tests that may depend on execution order.
## Changes
- ✨ Added `--randomize` CLI flag to test command
- 🔀 Implemented test shuffling using `bun.fastRandom()` as PRNG seed
- 🧪 Added comprehensive tests to verify randomization behavior
- 📝 Tests are shuffled at the scheduling phase, properly handling
describe blocks and hooks
## Usage
```bash
# Run tests in random order
bun test --randomize
# Works with other test flags
bun test --randomize --bail
bun test mytest.test.ts --randomize
```
## Implementation Details
The randomization happens in `Order.zig`'s `generateOrderDescribe`
function, which shuffles the `current.entries.items` array when the
randomize flag is set. This ensures:
- All tests still run (just in different order)
- Hooks (beforeAll, afterAll, beforeEach, afterEach) maintain proper
relationships
- Describe blocks and their children are shuffled independently
- Each run uses a different random seed for varied execution orders
## Test Coverage
Added tests in `test/cli/test/test-randomize.test.ts` that verify:
- Tests run in random order with the flag
- All tests execute (none are skipped)
- Without the flag, tests run in consistent order
- Randomization works with describe blocks
## Example Output
```bash
# Without --randomize (consistent order)
$ bun test mytest.js
Running test 1
Running test 2
Running test 3
Running test 4
Running test 5
# With --randomize (different order each run)
$ bun test mytest.js --randomize
Running test 3
Running test 5
Running test 1
Running test 4
Running test 2
$ bun test mytest.js --randomize
Running test 2
Running test 4
Running test 5
Running test 1
Running test 3
```
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: pfg <pfg@pfg.pw>
2025-09-25 14:20:47 -07:00
2213 changed files with 154778 additions and 59008 deletions
Find up to 3 likely duplicate issues for a given GitHub issue.
To do this, follow these steps precisely:
1. Use an agent to check if the GitHub issue (a) is closed, (b) does not need to be deduped (eg. because it is broad product feedback without a specific solution, or positive feedback), or (c) already has a duplicate detection comment (check for the exact HTML marker `<!-- dedupe-bot:marker -->` in the issue comments - ignore other bot comments). If so, do not proceed.
2. Use an agent to view a GitHub issue, and ask the agent to return a summary of the issue
3. Then, launch 5 parallel agents to search GitHub for duplicates of this issue, using diverse keywords and search approaches, using the summary from Step 2. **IMPORTANT**: Always scope searches with `repo:owner/repo` to constrain results to the current repository only.
4. Next, feed the results from Steps 2 and 3 into another agent, so that it can filter out false positives, that are likely not actually duplicates of the original issue. If there are no duplicates remaining, do not proceed.
5. Finally, comment back on the issue with a list of up to three duplicate issues (or zero, if there are no likely duplicates)
Notes (be sure to tell this to your agents, too):
- Use `gh` to interact with GitHub, rather than web fetch
- Do not use other tools, beyond `gh` (eg. don't use other MCP servers, file edit, etc.)
- Make a todo list first
- Always scope searches with `repo:owner/repo` to prevent cross-repo false positives
- For your comment, follow the following format precisely (assuming for this example that you found 3 suspected duplicates):
---
Found 3 possible duplicate issues:
1. <link to issue>
2. <link to issue>
3. <link to issue>
This issue will be automatically closed as a duplicate in 3 days.
- If your issue is a duplicate, please close it and 👍 the existing issue instead
- To prevent auto-closure, add a comment or 👎 this comment
🤖 Generated with [Claude Code](https://claude.ai/code)
@@ -23,28 +23,51 @@ Tip: Bun is already installed and in $PATH. The `bd` subcommand is a package.jso
### Test Organization
If a test is for a specific numbered GitHub Issue, it should be placed in `test/regression/issue/${issueNumber}.test.ts`. Ensure the issue number is **REAL** and not a placeholder!
If no valid issue number is provided, find the best existing file to modify instead, such as;
-`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.)
// Assert the exit code last. This gives you a more useful error message on test failure.
expect(exitCode).toBe(0);
});
```
- Always use `port: 0`. Do not hardcode ports. Do not use your own random port number function.
- Use `normalizeBunSnapshot` to normalize snapshot output of the test.
- NEVER write tests that check for no "panic" or "uncaught exception" or similar in the test output. That is NOT a valid test.
- Use `tempDir` from `"harness"` to create a temporary directory. **Do not** use `tmpdirSync` or `fs.mkdtempSync` to create temporary directories.
- When spawning processes, tests should expect(stdout).toBe(...) BEFORE expect(exitCode).toBe(0). This gives you a more useful error message on test failure.
- **CRITICAL**: Do not write flaky tests. Do not use `setTimeout` in tests. Instead, `await` the condition to be met. You are not testing the TIME PASSING, you are testing the CONDITION.
- **CRITICAL**: Verify your test fails with `USE_SYSTEM_BUN=1 bun test <file>` and passes with `bun bd test <file>`. Your test is NOT VALID if it passes with `USE_SYSTEM_BUN=1`.
- **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
- **Generated code**: Many files are auto-generated from `.classes.ts` and other sources. Bun will automatically rebuild these files when you make changes to them.
### Core Source Organization
@@ -143,19 +172,6 @@ When implementing JavaScript classes in C++:
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:
@@ -177,47 +193,6 @@ Built-in JavaScript modules use special syntax and are organized as:
-`internal/` - Internal modules not exposed to users
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.
@@ -229,19 +204,8 @@ bun ci
7.**Avoid shell commands** - Don't use `find` or `grep` in tests; use Bun's Glob and built-in tools
8.**Memory management** - In Zig code, be careful with allocators and use defer for cleanup
9.**Cross-platform** - Run `bun run zig:check-all` to compile the Zig code on all platforms when making platform-specific changes
10.**Debug builds** - Use `BUN_DEBUG_QUIET_LOGS=1` to disable debug logging, or `BUN_DEBUG_<scope>=1` to enable specific scopes
10. **Debug builds** - Use `BUN_DEBUG_QUIET_LOGS=1` to disable debug logging, or `BUN_DEBUG_<scopeName>=1` to enable specific `Output.scoped(.${scopeName}, .visible)`s
11.**Be humble & honest** - NEVER overstate what you got done or what actually works in commits, PRs or in messages to the user.
12.**Branch names must start with `claude/`** - This is a requirement for the CI to work.
## 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.
sccache is used to cache compilation artifacts, significantly speeding up builds. It must be installed with S3 support:
```bash
# For macOS
$ brew install sccache
# For Linux. Note that the version in your package manager may not have S3 support.
$ cargo install sccache --features=s3
```
This will install `sccache` with S3 support. Our build scripts will automatically detect and use `sccache` with our shared S3 cache. **Note**: Not all versions of `sccache` are compiled with S3 support, hence we recommend installing it via `cargo`.
#### Registering AWS Credentials for `sccache` (Core Developers Only)
Core developers have write access to the shared S3 cache. To enable write access, you must log in with AWS credentials. The easiest way to do this is to use the [`aws` CLI](https://aws.amazon.com/cli/) and invoke [`aws configure` to provide your AWS security info](https://docs.aws.amazon.com/cli/latest/reference/configure/).
The `cmake` scripts should automatically detect your AWS credentials from the environment or the `~/.aws/credentials` file.
<details>
<summary>Logging in to the `aws` CLI</summary>
1. Install the AWS CLI by following [the official guide](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).
2. Log in to your AWS account console. A team member should provide you with your credentials.
3. Click your name in the top right > Security credentials.
4. Scroll to "Access keys" and create a new access key.
5. Run `aws configure` in your terminal and provide the access key ID and secret access key when prompted.
</details>
<details>
<summary>Common Issues You May Encounter</summary>
- To confirm that the cache is being used, you can use the `sccache --show-stats` command right after a build. This will expose very useful statistics, including cache hits/misses.
- If you have multiple AWS profiles configured, ensure that the correct profile is set in the `AWS_PROFILE` environment variable.
- `sccache` follows a server-client model. If you run into weird issues where `sccache` refuses to use S3, even though you have AWS credentials configured, try killing any running `sccache` servers with `sccache --stop-server` and then re-running the build.
</details>
## Install LLVM
Bun requires LLVM 19 (`clang` is part of LLVM). This version requirement is to match WebKit (precompiled), as mismatching versions will cause memory allocation failures at runtime. In most cases, you can install LLVM through your system package manager:
@@ -149,7 +201,7 @@ Bun generally takes about 2.5 minutes to compile a debug build when there are Zi
- 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.
- Use debug logs. `BUN_DEBUG_<scope>=1` will enable debug logging for the corresponding `Output.scoped(.<scope>, .hidden)` logs. You can also set `BUN_DEBUG_QUIET_LOGS=1` to disable all debug logging that isn't explicitly enabled. To dump debug logs 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
@@ -317,15 +369,6 @@ $ bun run build -DUSE_STATIC_LIBATOMIC=OFF
The built version of Bun may not work on other systems if compiled this way.
### ccache conflicts with building TinyCC on macOS
If you run into issues with `ccache` when building TinyCC, try reinstalling ccache
Requires [`hyperfine`](https://github.com/sharkdp/hyperfine). The goal of this benchmark is to compare installation performance of Bun with other package managers _when caches are hot_.
This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`.
### With lockfile, online mode
## What's next? How do I make an app with this?
To run the benchmark with the standard "install" command for each package manager:
We try to keep this project as simple as possible, so you can start with just the scaffolding we set up for you, and add additional things later when they become necessary.
If you are not familiar with the different technologies used in this project, please refer to the respective docs. If you still are in the wind, please join our [Discord](https://t3.gg/discord) and ask for help.
### With lockfile, offline mode
- [Next.js](https://nextjs.org)
- [NextAuth.js](https://next-auth.js.org)
- [Prisma](https://prisma.io)
- [Drizzle](https://orm.drizzle.team)
- [Tailwind CSS](https://tailwindcss.com)
- [tRPC](https://trpc.io)
Even though all packages are cached, some tools may hit the npm API during the version resolution step. (This is not the same as re-downloading a package.) To entirely avoid network calls, the other package managers require `--prefer-offline/--offline` flag. To run the benchmark using "offline" mode:
Then visit [http://localhost:3000](http://localhost:3000).
Follow our deployment guides for [Vercel](https://create.t3.gg/en/deployment/vercel), [Netlify](https://create.t3.gg/en/deployment/netlify) and [Docker](https://create.t3.gg/en/deployment/docker) for more information.
Bun.js has fast paths for common use cases that make Web APIs live up to the performance demands of servers and CLIs.
`Bun.file(path)` returns a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) that represents a lazily-loaded file.
When you pass a file blob to `Bun.write`, Bun automatically uses a faster system call:
```js
constblob=Bun.file("input.txt");
awaitBun.write("output.txt",blob);
```
On Linux, this uses the [`copy_file_range`](https://man7.org/linux/man-pages/man2/copy_file_range.2.html) syscall and on macOS, this becomes `clonefile` (or [`fcopyfile`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/copyfile.3.html)).
`Bun.write` also supports [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects. It automatically converts to a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
```js
// Eventually, this will stream the response to disk but today it buffers
- Also [`ErrorEvent`](https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent) [`CloseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent) [`MessageEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent).
The `import.meta` object is a way for a module to access information about itself. It's part of the JavaScript language, but its contents are not standardized. Each "host" (browser, runtime, etc) is free to implement any properties it wishes on the `import.meta` object.
- Absolute path to the directory containing the current file, e.g. `/path/to/project`. Equivalent to `__dirname` in CommonJS modules (and Node.js)
---
- `import.meta.dirname`
- An alias to `import.meta.dir`, for Node.js compatibility
---
- `import.meta.env`
- An alias to `process.env`.
---
- `import.meta.file`
- The name of the current file, e.g. `index.tsx`
---
- `import.meta.path`
- Absolute path to the current file, e.g. `/path/to/project/index.ts`. Equivalent to `__filename` in CommonJS modules (and Node.js)
---
- `import.meta.filename`
- An alias to `import.meta.path`, for Node.js compatibility
---
- `import.meta.main`
- Indicates whether the current file is the entrypoint to the current `bun` process. Is the file being directly executed by `bun run` or is it being imported?
---
- `import.meta.resolve`
- Resolve a module specifier (e.g. `"zod"` or `"./file.tsx"`) to a url. Equivalent to [`import.meta.resolve` in browsers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta#resolve)
- A `string` url to the current file, e.g. `file:///path/to/project/index.ts`. Equivalent to [`import.meta.url` in browsers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta#url)
There are some more examples in the [examples](./examples) folder.
PRs adding more examples are very welcome!
## Fast paths for Web APIs
Bun.js has fast paths for common use cases that make Web APIs live up to the performance demands of servers and CLIs.
`Bun.file(path)` returns a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) that represents a lazily-loaded file.
When you pass a file blob to `Bun.write`, Bun automatically uses a faster system call:
```js
constblob=Bun.file("input.txt");
awaitBun.write("output.txt",blob);
```
On Linux, this uses the [`copy_file_range`](https://man7.org/linux/man-pages/man2/copy_file_range.2.html) syscall and on macOS, this becomes `clonefile` (or [`fcopyfile`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/copyfile.3.html)).
`Bun.write` also supports [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects. It automatically converts to a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
```js
// Eventually, this will stream the response to disk but today it buffers
description: Speed up JavaScript execution with bytecode caching in Bun's bundler
---
Bytecode caching is a build-time optimization that dramatically improves application startup time by pre-compiling your JavaScript to bytecode. For example, when compiling TypeScript's `tsc` with bytecode enabled, startup time improves by **2x**.
## Usage
### Basic usage
Enable bytecode caching with the `--bytecode` flag:
```bash terminal icon="terminal"
bun build ./index.ts --target=bun --bytecode --outdir=./dist
```
This generates two files:
- `dist/index.js` - Your bundled JavaScript
- `dist/index.jsc` - The bytecode cache file
At runtime, Bun automatically detects and uses the `.jsc` file:
```bash terminal icon="terminal"
bun ./dist/index.js # Automatically uses index.jsc
```
### With standalone executables
When creating executables with `--compile`, bytecode is embedded into the binary:
```bash terminal icon="terminal"
bun build ./cli.ts --compile --bytecode --outfile=mycli
```
The resulting executable contains both the code and bytecode, giving you maximum performance in a single file.
### Combining with other optimizations
Bytecode works great with minification and source maps:
```bash terminal icon="terminal"
bun build --compile --bytecode --minify --sourcemap ./cli.ts --outfile=mycli
```
- `--minify` reduces code size before generating bytecode (less code -> less bytecode)
- `--sourcemap` preserves error reporting (errors still point to original source)
- `--bytecode` eliminates parsing overhead
## Performance impact
The performance improvement scales with your codebase size:
- Users notice the difference between 90ms and 45ms startup
- Example: TypeScript compiler, Prettier, ESLint
#### Build tools and task runners
- Run hundreds or thousands of times during development
- Milliseconds saved per run compound quickly
- Developer experience improvement
- Example: Build scripts, test runners, code generators
#### Standalone executables
- Distributed to users who care about snappy performance
- Single-file distribution is convenient
- File size less important than startup time
- Example: CLIs distributed via npm or as binaries
### Skip it for:
- ❌ **Small scripts**
- ❌ **Code that runs once**
- ❌ **Development builds**
- ❌ **Size-constrained environments**
- ❌ **Code with top-level await** (not supported)
## Limitations
### CommonJS only
Bytecode caching currently works with CommonJS output format. Bun's bundler automatically converts most ESM code to CommonJS, but **top-level await** is the exception:
```js
// This prevents bytecode caching
const data = await fetch("https://api.example.com");
export default data;
```
**Why**: Top-level await requires async module evaluation, which can't be represented in CommonJS. The module graph becomes asynchronous, and the CommonJS wrapper function model breaks down.
**Workaround**: Move async initialization into a function:
```js
async function init() {
const data = await fetch("https://api.example.com");
return data;
}
export default init;
```
Now the module exports a function that the consumer can await when needed.
### Version compatibility
Bytecode is **not portable across Bun versions**. The bytecode format is tied to JavaScriptCore's internal representation, which changes between versions.
When you update Bun, you must regenerate bytecode:
```bash terminal icon="terminal"
# After updating Bun
bun build --bytecode ./index.ts --outdir=./dist
```
If bytecode doesn't match the current Bun version, it's automatically ignored and your code falls back to parsing the JavaScript source. Your app still runs - you just lose the performance optimization.
**Best practice**: Generate bytecode as part of your CI/CD build process. Don't commit `.jsc` files to git. Regenerate them whenever you update Bun.
### Source code still required
- The `.js` file (your bundled source code)
- The `.jsc` file (the bytecode cache)
At runtime:
1. Bun loads the `.js` file, sees a `@bytecode` pragma, and checks the `.jsc` file
2. Bun loads the `.jsc` file
3. Bun validates the bytecode hash matches the source
4. If valid, Bun uses the bytecode
5. If invalid, Bun falls back to parsing the source
### Bytecode is not obfuscation
Bytecode **does not obscure your source code**. It's an optimization, not a security measure.
## Production deployment
### Docker
Include bytecode generation in your Dockerfile:
```dockerfile Dockerfile icon="docker"
FROM oven/bun:1 AS builder
WORKDIR /app
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun build --bytecode --minify --sourcemap \
--target=bun \
--outdir=./dist \
--compile \
./src/server.ts --outfile=./dist/server
FROM oven/bun:1 AS runner
WORKDIR /app
COPY --from=builder /dist/server /app/server
CMD ["./server"]
```
The bytecode is architecture-independent.
### CI/CD
Generate bytecode during your build pipeline:
```yaml workflow.yml icon="file-code"
# GitHub Actions
- name: Build with bytecode
run: |
bun install
bun build --bytecode --minify \
--outdir=./dist \
--target=bun \
./src/index.ts
```
## Debugging
### Verify bytecode is being used
Check that the `.jsc` file exists:
```bash terminal icon="terminal"
ls -lh dist/
```
```txt
-rw-r--r-- 1 user staff 245K index.js
-rw-r--r-- 1 user staff 1.1M index.jsc
```
The `.jsc` file should be 2-8x larger than the `.js` file.
To log if bytecode is being used, set `BUN_JSC_verboseDiskCache=1` in your environment.
On success, it will log something like:
```txt
[Disk cache] cache hit for sourceCode
```
If you see a cache miss, it will log something like:
```txt
[Disk cache] cache miss for sourceCode
```
It's normal for it it to log a cache miss multiple times since Bun doesn't currently bytecode cache JavaScript code used in builtin modules.
### Common issues
**Bytecode silently ignored**: Usually caused by a Bun version update. The cache version doesn't match, so bytecode is rejected. Regenerate to fix.
**File size too large**: This is expected. Consider:
- Using `--minify` to reduce code size before bytecode generation
- Compressing `.jsc` files for network transfer (gzip/brotli)
- Evaluating if the startup performance gain is worth the size increase
**Top-level await**: Not supported. Refactor to use async initialization functions.
## What is bytecode?
When you run JavaScript, the JavaScript engine doesn't execute your source code directly. Instead, it goes through several steps:
1. **Parsing**: The engine reads your JavaScript source code and converts it into an Abstract Syntax Tree (AST)
2. **Bytecode compilation**: The AST is compiled into bytecode - a lower-level representation that's faster to execute
3. **Execution**: The bytecode is executed by the engine's interpreter or JIT compiler
Bytecode is an intermediate representation - it's lower-level than JavaScript source code, but higher-level than machine code. Think of it as assembly language for a virtual machine. Each bytecode instruction represents a single operation like "load this variable," "add two numbers," or "call this function."
This happens **every single time** you run your code. If you have a CLI tool that runs 100 times a day, your code gets parsed 100 times. If you have a serverless function with frequent cold starts, parsing happens on every cold start.
With bytecode caching, Bun moves steps 1 and 2 to the build step. At runtime, the engine loads the pre-compiled bytecode and jumps straight to execution.
### Why lazy parsing makes this even better
Modern JavaScript engines use a clever optimization called **lazy parsing**. They don't parse all your code upfront - instead, functions are only parsed when they're first called:
```js
// Without bytecode caching:
function rarely_used() {
// This 500-line function is only parsed
// when it's actually called
}
function main() {
console.log("Starting app");
// rarely_used() is never called, so it's never parsed
}
```
This means parsing overhead isn't just a startup cost - it happens throughout your application's lifetime as different code paths execute. With bytecode caching, **all functions are pre-compiled**, even the ones that are lazily parsed. The parsing work happens once at build time instead of being distributed throughout your application's execution.
## The bytecode format
### Inside a .jsc file
A `.jsc` file contains a serialized bytecode structure. Understanding what's inside helps explain both the performance benefits and the file size tradeoff.
**Header section** (validated on every load):
- **Cache version**: A hash tied to the JavaScriptCore framework version. This ensures bytecode generated with one version of Bun only runs with that exact version.
- **Code block type tag**: Identifies whether this is a Program, Module, Eval, or Function code block.
- **Source code hash**: A hash of the original JavaScript source code. Bun verifies this matches before using the bytecode.
- **Source code length**: The exact length of the source, for additional validation.
- **Compilation flags**: Critical compilation context like strict mode, whether it's a script vs module, eval context type, etc. The same source code compiled with different flags produces different bytecode.
**Bytecode instructions**:
- **Instruction stream**: The actual bytecode opcodes - the compiled representation of your JavaScript. This is a variable-length sequence of bytecode instructions.
- **Metadata table**: Each opcode has associated metadata - things like profiling counters, type hints, and execution counts (even if not yet populated).
- **Jump targets**: Pre-computed addresses for control flow (if/else, loops, switch statements).
- **Switch tables**: Optimized lookup tables for switch statements.
**Constants and identifiers**:
- **Constant pool**: All literal values in your code - numbers, strings, booleans, null, undefined. These are stored as actual JavaScript values (JSValues) so they don't need to be parsed from source at runtime.
- **Identifier table**: All variable and function names used in the code. Stored as deduplicated strings.
- **Source code representation markers**: Flags indicating how constants should be represented (as integers, doubles, big ints, etc.).
**Function metadata** (for each function in your code):
- **Register allocation**: How many registers (local variables) the function needs - `thisRegister`, `scopeRegister`, `numVars`, `numCalleeLocals`, `numParameters`.
- **Code features**: A bitmask of function characteristics: is it a constructor? an arrow function? does it use `super`? does it have tail calls? These affect how the function is executed.
- **Lexically scoped features**: Strict mode and other lexical context.
- **Parse mode**: The mode in which the function was parsed (normal, async, generator, async generator).
**Nested structures**:
- **Function declarations and expressions**: Each nested function gets its own bytecode block, recursively. A file with 100 functions has 100 separate bytecode blocks, all nested in the structure.
- **Exception handlers**: Try/catch/finally blocks with their boundaries and handler addresses pre-computed.
- **Expression info**: Maps bytecode positions back to source code locations for error reporting and debugging.
### What bytecode does NOT contain
Importantly, **bytecode does not embed your source code**. Instead:
- The JavaScript source is stored separately (in the `.js` file)
- The bytecode only stores a hash and length of the source
- At load time, Bun validates the bytecode matches the current source code
This is why you need to deploy both the `.js` and `.jsc` files. The `.jsc` file is useless without its corresponding `.js` file.
## The tradeoff: file size
Bytecode files are significantly larger than source code - typically 2-8x larger.
### Why is bytecode so much larger?
**Bytecode instructions are verbose**:
A single line of minified JavaScript might compile to dozens of bytecode instructions. For example:
```js
const sum = arr.reduce((a, b) => a + b, 0);
```
Compiles to bytecode that:
- Loads the `arr` variable
- Gets the `reduce` property
- Creates the arrow function (which itself has bytecode)
- Loads the initial value `0`
- Sets up the call with the right number of arguments
- Actually performs the call
- Stores the result in `sum`
Each of these steps is a separate bytecode instruction with its own metadata.
**Constant pools store everything**:
Every string literal, number, property name - everything gets stored in the constant pool. Even if your source code has `"hello"` a hundred times, the constant pool stores it once, but the identifier table and constant references add overhead.
**Per-function metadata**:
Each function - even small one-line functions - gets its own complete metadata:
- Register allocation info
- Code features bitmask
- Parse mode
- Exception handlers
- Expression info for debugging
A file with 1,000 small functions has 1,000 sets of metadata.
**Profiling data structures**:
Even though profiling data isn't populated yet, the _structures_ to hold profiling data are allocated. This includes:
- Value profile slots (tracking what types flow through each operation)
- Binary arithmetic profile slots (tracking number types in math operations)
- Unary arithmetic profile slots
These take up space even when empty.
**Pre-computed control flow**:
Jump targets, switch tables, and exception handler boundaries are all pre-computed and stored. This makes execution faster but increases file size.
### Mitigation strategies
**Compression**:
Bytecode compresses extremely well with gzip/brotli (60-70% compression). The repetitive structure and metadata compress efficiently.
**Minification first**:
Using `--minify` before bytecode generation helps:
- Shorter identifiers → smaller identifier table
- Dead code elimination → less bytecode generated
- Constant folding → fewer constants in the pool
**The tradeoff**:
You're trading 2-4x larger files for 2-4x faster startup. For CLIs, this is usually worth it. For long-running servers where a few megabytes of disk space don't matter, it's even less of an issue.
## Versioning and portability
### Cross-architecture portability: ✅
Bytecode is **architecture-independent**. You can:
- Build on macOS ARM64, deploy to Linux x64
- Build on Linux x64, deploy to AWS Lambda ARM64
- Build on Windows x64, deploy to macOS ARM64
The bytecode contains abstract instructions that work on any architecture. Architecture-specific optimizations happen during JIT compilation at runtime, not in the cached bytecode.
### Cross-version portability: ❌
Bytecode is **not stable across Bun versions**. Here's why:
**Bytecode format changes**:
JavaScriptCore's bytecode format evolves. New opcodes get added, old ones get removed or changed, metadata structures change. Each version of JavaScriptCore has a different bytecode format.
**Version validation**:
The cache version in the `.jsc` file header is a hash of the JavaScriptCore framework. When Bun loads bytecode:
1. It extracts the cache version from the `.jsc` file
2. It computes the current JavaScriptCore version
3. If they don't match, the bytecode is **silently rejected**
4. Bun falls back to parsing the `.js` source code
Your application still runs - you just lose the performance optimization.
**Graceful degradation**:
This design means bytecode caching "fails open" - if anything goes wrong (version mismatch, corrupted file, missing file), your code still runs normally. You might see slower startup, but you won't see errors.
## Unlinked vs. linked bytecode
JavaScriptCore makes a crucial distinction between "unlinked" and "linked" bytecode. This separation is what makes bytecode caching possible:
### Unlinked bytecode (what's cached)
The bytecode saved in `.jsc` files is **unlinked bytecode**. It contains:
- The compiled bytecode instructions
- Structural information about the code
- Constants and identifiers
- Control flow information
But it **doesn't** contain:
- Pointers to actual runtime objects
- JIT-compiled machine code
- Profiling data from previous runs
- Call link information (which functions call which)
Unlinked bytecode is **immutable and shareable**. Multiple executions of the same code can all reference the same unlinked bytecode.
### Linked bytecode (runtime execution)
When Bun runs bytecode, it "links" it - creating a runtime wrapper that adds:
- **Call link information**: As your code runs, the engine learns which functions call which and optimizes those call sites.
- **Profiling data**: The engine tracks how many times each instruction executes, what types of values flow through the code, array access patterns, etc.
- **JIT compilation state**: References to baseline JIT or optimizing JIT (DFG/FTL) compiled versions of hot code.
- **Runtime objects**: Pointers to actual JavaScript objects, prototypes, scopes, etc.
This linked representation is created fresh every time you run your code. This allows:
1. **Caching the expensive work** (parsing and compilation to unlinked bytecode)
2. **Still collecting runtime profiling data** to guide optimizations
3. **Still applying JIT optimizations** based on actual execution patterns
Bytecode caching moves expensive work (parsing and compiling to bytecode) from runtime to build time. For applications that start frequently, this can halve your startup time at the cost of larger files on disk.
For production CLIs and serverless deployments, the combination of `--bytecode --minify --sourcemap` gives you the best performance while maintaining debuggability.
description: Bun's bundler has built-in support for CSS with modern features
---
Bun's bundler has built-in support for CSS with the following features:
- Transpiling modern/future features to work on all browsers (including vendor prefixing)
@@ -9,11 +14,11 @@ Bun's bundler has built-in support for CSS with the following features:
Bun's CSS bundler lets you use modern/future CSS features without having to worry about browser compatibility — all thanks to its transpiling and vendor prefixing features which are enabled by default.
Bun's CSS parser and bundler is a direct Rust → Zig port of [LightningCSS](https://lightningcss.dev/), with a bundling approach inspired by esbuild. The transpiler converts modern CSS syntax into backwards-compatible equivalents that work across browsers.
Bun's CSS parser and bundler is a direct Rust → Zig port of LightningCSS, with a bundling approach inspired by esbuild. The transpiler converts modern CSS syntax into backwards-compatible equivalents that work across browsers.
A huge thanks goes to the amazing work from the authors of [LightningCSS](https://lightningcss.dev/) and [esbuild](https://esbuild.github.io/).
<Note>A huge thanks goes to the amazing work from the authors of LightningCSS and esbuild.</Note>
### Browser Compatibility
## Browser Compatibility
By default, Bun's CSS bundler targets the following browsers:
@@ -23,13 +28,13 @@ By default, Bun's CSS bundler targets the following browsers:
- Chrome 87+
- Safari 14+
### Syntax Lowering
## Syntax Lowering
#### Nesting
### Nesting
The CSS Nesting specification allows you to write more concise and intuitive stylesheets by nesting selectors inside one another. Instead of repeating parent selectors across your CSS file, you can write child styles directly within their parent blocks.
```css
```scss title="styles.css" icon="file-code"
/* With nesting */
.card {
background: white;
@@ -48,7 +53,7 @@ The CSS Nesting specification allows you to write more concise and intuitive sty
Bun's CSS bundler automatically converts this nested syntax into traditional flat CSS that works in all browsers:
```css
```css title="styles.css" icon="file-code"
/* Compiled output */
.card {
background: white;
@@ -67,7 +72,7 @@ Bun's CSS bundler automatically converts this nested syntax into traditional fla
You can also nest media queries and other at-rules inside selectors, eliminating the need to repeat selector patterns:
```css
```scss title="styles.css" icon="file-code"
.responsive-element {
display: block;
@@ -79,7 +84,7 @@ You can also nest media queries and other at-rules inside selectors, eliminating
This compiles to:
```css
```css title="styles.css" icon="file-code"
.responsive-element {
display: block;
}
@@ -91,11 +96,11 @@ This compiles to:
}
```
#### Color mix
### Color mix
The `color-mix()` function gives you an easy way to blend two colors together according to a specified ratio in a chosen color space. This powerful feature lets you create color variations without manually calculating the resulting values.
```css
```scss title="styles.css" icon="file-code"
.button {
/* Mix blue and red in the RGB color space with a 30/70 proportion */
background-color: color-mix(in srgb, blue 30%, red);
@@ -109,7 +114,7 @@ The `color-mix()` function gives you an easy way to blend two colors together ac
Bun's CSS bundler evaluates these color mixes at build time when all color values are known (not CSS variables), generating static color values that work in all browsers:
```css
```css title="styles.css" icon="file-code"
.button {
/* Computed to the exact resulting color */
background-color: #b31a1a;
@@ -122,11 +127,11 @@ Bun's CSS bundler evaluates these color mixes at build time when all color value
This feature is particularly useful for creating color systems with programmatically derived shades, tints, and accents without needing preprocessors or custom tooling.
#### Relative colors
### Relative colors
CSS now allows you to modify individual components of a color using relative color syntax. This powerful feature lets you create color variations by adjusting specific attributes like lightness, saturation, or individual channels without having to recalculate the entire color.
```css
```css title="styles.css" icon="file-code"
.theme-color {
/* Start with a base color and increase lightness by 15% */
--accent: lch(from purple calc(l + 15%) c h);
@@ -147,27 +152,23 @@ Bun's CSS bundler computes these relative color modifications at build time (whe
This approach is extremely useful for theme generation, creating accessible color variants, or building color scales based on mathematical relationships instead of hard-coding each value.
#### LAB colors
### LAB colors
Modern CSS supports perceptually uniform color spaces like LAB, LCH, OKLAB, and OKLCH that offer significant advantages over traditional RGB. These color spaces can represent colors outside the standard RGB gamut, resulting in more vibrant and visually consistent designs.
```css
```css title="styles.css" icon="file-code"
.vibrant-element {
/* A vibrant red that exceeds sRGB gamut boundaries */
color: lab(55% 78 35);
/* A smooth gradient using perceptual color space */
This layered approach ensures optimal color rendering across all browsers while allowing you to use the latest color technologies in your designs.
#### Color function
### Color function
The `color()` function provides a standardized way to specify colors in various predefined color spaces, expanding your design options beyond the traditional RGB space. This allows you to access wider color gamuts and create more vibrant designs.
```css
```css title="styles.css" icon="file-code"
.vivid-element {
/* Using the Display P3 color space for wider gamut colors */
color: color(display-p3 1 0.1 0.3);
@@ -203,7 +200,7 @@ The `color()` function provides a standardized way to specify colors in various
For browsers that don't support these advanced color functions yet, Bun's CSS bundler provides appropriate RGB fallbacks:
```css
```css title="styles.css" icon="file-code"
.vivid-element {
/* RGB fallback first for maximum compatibility */
color: #fa1a4c;
@@ -217,11 +214,11 @@ For browsers that don't support these advanced color functions yet, Bun's CSS bu
This functionality lets you use modern color spaces immediately while ensuring your designs remain functional across all browsers, with optimal colors displayed in supporting browsers and reasonable approximations elsewhere.
#### HWB colors
### HWB colors
The HWB (Hue, Whiteness, Blackness) color model provides an intuitive way to express colors based on how much white or black is mixed with a pure hue. Many designers find this approach more natural for creating color variations compared to manipulating RGB or HSL values.
```css
```css title="styles.css" icon="file-code"
.easy-theming {
/* Pure cyan with no white or black added */
--primary: hwb(180 0% 0%);
@@ -239,7 +236,7 @@ The HWB (Hue, Whiteness, Blackness) color model provides an intuitive way to exp
Bun's CSS bundler automatically converts HWB colors to RGB for compatibility with all browsers:
```css
```css title="styles.css" icon="file-code"
.easy-theming {
--primary: #00ffff;
--primary-light: #33ffff;
@@ -250,11 +247,11 @@ Bun's CSS bundler automatically converts HWB colors to RGB for compatibility wit
The HWB model makes it particularly easy to create systematic color variations for design systems, providing a more intuitive approach to creating consistent tints and shades than working directly with RGB or HSL values.
#### Color notation
### Color notation
Modern CSS has introduced more intuitive and concise ways to express colors. Space-separated color syntax eliminates the need for commas in RGB and HSL values, while hex colors with alpha channels provide a compact way to specify transparency.
```css
```css title="styles.css" icon="file-code"
.modern-styling {
/* Space-separated RGB notation (no commas) */
color: rgb(50 100 200);
@@ -272,7 +269,7 @@ Modern CSS has introduced more intuitive and concise ways to express colors. Spa
Bun's CSS bundler automatically converts these modern color formats to ensure compatibility with older browsers:
```css
```css title="styles.css" icon="file-code"
.modern-styling {
/* Converted to comma format for older browsers */
color: rgb(50, 100, 200);
@@ -289,11 +286,11 @@ Bun's CSS bundler automatically converts these modern color formats to ensure co
This conversion process lets you write cleaner, more modern CSS while ensuring your styles work correctly across all browsers.
#### light-dark() color function
### light-dark() color function
The `light-dark()` function provides an elegant solution for implementing color schemes that respect the user's system preference without requiring complex media queries. This function accepts two color values and automatically selects the appropriate one based on the current color scheme context.
```css
```css title="styles.css" icon="file-code"
:root {
/* Define color scheme support */
color-scheme: light dark;
@@ -318,7 +315,7 @@ The `light-dark()` function provides an elegant solution for implementing color
For browsers that don't support this feature yet, Bun's CSS bundler converts it to use CSS variables with proper fallbacks:
```css
```css title="styles.css" icon="file-code"
:root {
--lightningcss-light: initial;
--lightningcss-dark: ;
@@ -345,21 +342,19 @@ For browsers that don't support this feature yet, Bun's CSS bundler converts it
This approach gives you a clean way to handle light and dark themes without duplicating styles or writing complex media queries, while maintaining compatibility with browsers that don't yet support the feature natively.
#### Logical properties
### Logical properties
CSS logical properties let you define layout, spacing, and sizing relative to the document's writing mode and text direction rather than physical screen directions. This is crucial for creating truly international layouts that automatically adapt to different writing systems.
```css
```css title="styles.css" icon="file-code"
.multilingual-component {
/* Margin that adapts to writing direction */
margin-inline-start: 1rem;
@@ -378,7 +373,7 @@ CSS logical properties let you define layout, spacing, and sizing relative to th
For browsers that don't fully support logical properties, Bun's CSS bundler compiles them to physical properties with appropriate directional adjustments:
```css
```css title="styles.css" icon="file-code"
/* For left-to-right languages */
.multilingual-component:dir(ltr) {
margin-left: 1rem;
@@ -402,11 +397,11 @@ For browsers that don't fully support logical properties, Bun's CSS bundler comp
If the `:dir()` selector isn't supported, additional fallbacks are automatically generated to ensure your layouts work properly across all browsers and writing systems. This makes creating internationalized designs much simpler while maintaining compatibility with older browsers.
#### :dir() selector
### :dir() selector
The `:dir()` pseudo-class selector allows you to style elements based on their text direction (RTL or LTR), providing a powerful way to create direction-aware designs without JavaScript. This selector matches elements based on their directionality as determined by the document or explicit direction attributes.
```css
```css title="styles.css" icon="file-code"
/* Apply different styles based on text direction */
.nav-arrow:dir(ltr) {
transform: rotate(0deg);
@@ -428,7 +423,7 @@ The `:dir()` pseudo-class selector allows you to style elements based on their t
For browsers that don't support the `:dir()` selector yet, Bun's CSS bundler converts it to the more widely supported `:lang()` selector with appropriate language mappings:
```css
```css title="styles.css" icon="file-code"
/* Converted to use language-based selectors as fallback */
.nav-arrow:lang(en, fr, de, es, it, pt, nl) {
transform: rotate(0deg);
@@ -449,11 +444,11 @@ For browsers that don't support the `:dir()` selector yet, Bun's CSS bundler con
This conversion lets you write direction-aware CSS that works reliably across browsers, even those that don't yet support the `:dir()` selector natively. If multiple arguments to `:lang()` aren't supported, further fallbacks are automatically provided.
#### :lang() selector
### :lang() selector
The `:lang()` pseudo-class selector allows you to target elements based on the language they're in, making it easy to apply language-specific styling. Modern CSS allows the `:lang()` selector to accept multiple language codes, letting you group language-specific rules more efficiently.
```css
```css title="styles.css" icon="file-code"
/* Typography adjustments for CJK languages */
:lang(zh, ja, ko) {
line-height: 1.8;
@@ -472,7 +467,7 @@ blockquote:lang(de, nl, da, sv) {
For browsers that don't support multiple arguments in the `:lang()` selector, Bun's CSS bundler converts this syntax to use the `:is()` selector to maintain the same behavior:
```css
```css title="styles.css" icon="file-code"
/* Multiple languages grouped with :is() for better browser support */
If needed, Bun can provide additional fallbacks for `:is()` as well, ensuring your language-specific styles work across all browsers. This approach simplifies creating internationalized designs with distinct typographic and styling rules for different language groups.
#### :is() selector
### :is() selector
The `:is()` pseudo-class function (formerly `:matches()`) allows you to create more concise and readable selectors by grouping multiple selectors together. It accepts a selector list as its argument and matches if any of the selectors in that list match, significantly reducing repetition in your CSS.
```css
```css title="styles.css" icon="file-code"
/* Instead of writing these separately */
/*
.article h1,
@@ -547,13 +542,17 @@ For browsers that don't support `:is()`, Bun's CSS bundler provides fallbacks us
}
```
It's worth noting that the vendor-prefixed versions have some limitations compared to the standardized `:is()` selector, particularly with complex selectors. Bun handles these limitations intelligently, only using prefixed versions when they'll work correctly.
<Warning>
The vendor-prefixed versions have some limitations compared to the standardized `:is()` selector, particularly with
complex selectors. Bun handles these limitations intelligently, only using prefixed versions when they'll work
correctly.
</Warning>
#### :not() selector
### :not() selector
The `:not()` pseudo-class allows you to exclude elements that match a specific selector. The modern version of this selector accepts multiple arguments, letting you exclude multiple patterns with a single, concise selector.
```css
```css title="styles.css" icon="file-code"
/* Select all buttons except primary and secondary variants */
For browsers that don't support multiple arguments in `:not()`, Bun's CSS bundler converts this syntax to a more compatible form while preserving the same behavior:
```css
```css title="styles.css" icon="file-code"
/* Converted to use :not with :is() for compatibility */
This conversion ensures your negative selectors work correctly across all browsers while maintaining the correct specificity and behavior of the original selector.
#### Math functions
### Math functions
CSS now includes a rich set of mathematical functions that let you perform complex calculations directly in your stylesheets. These include standard math functions (`round()`, `mod()`, `rem()`, `abs()`, `sign()`), trigonometric functions (`sin()`, `cos()`, `tan()`, `asin()`, `acos()`, `atan()`, `atan2()`), and exponential functions (`pow()`, `sqrt()`, `exp()`, `log()`, `hypot()`).
```css
```css title="styles.css" icon="file-code"
.dynamic-sizing {
/* Clamp a value between minimum and maximum */
width: clamp(200px, 50%, 800px);
@@ -625,7 +624,7 @@ CSS now includes a rich set of mathematical functions that let you perform compl
Bun's CSS bundler evaluates these mathematical expressions at build time when all values are known constants (not variables), resulting in optimized output:
```css
```css title="styles.css" icon="file-code"
.dynamic-sizing {
width: clamp(200px, 50%, 800px);
padding: 15px;
@@ -637,11 +636,11 @@ Bun's CSS bundler evaluates these mathematical expressions at build time when al
This approach lets you write more expressive and maintainable CSS with meaningful mathematical relationships, which then gets compiled to optimized values for maximum browser compatibility and performance.
#### Media query ranges
### Media query ranges
Modern CSS supports intuitive range syntax for media queries, allowing you to specify breakpoints using comparison operators like `<`, `>`, `<=`, and `>=` instead of the more verbose `min-` and `max-` prefixes. This syntax is more readable and matches how we normally think about values and ranges.
```css
```css title="styles.css" icon="file-code"
/* Modern syntax with comparison operators */
@media (width >= 768px) {
.container {
@@ -666,7 +665,7 @@ Modern CSS supports intuitive range syntax for media queries, allowing you to sp
Bun's CSS bundler converts these modern range queries to traditional media query syntax for compatibility with all browsers:
```css
```css title="styles.css" icon="file-code"
/* Converted to traditional min/max syntax */
@media (min-width: 768px) {
.container {
@@ -689,11 +688,11 @@ Bun's CSS bundler converts these modern range queries to traditional media query
This lets you write more intuitive and mathematical media queries while ensuring your stylesheets work correctly across all browsers, including those that don't support the modern range syntax.
#### Shorthands
### Shorthands
CSS has introduced several modern shorthand properties that improve code readability and maintainability. Bun's CSS bundler ensures these convenient shorthands work on all browsers by converting them to their longhand equivalents when needed.
```css
```css title="styles.css" icon="file-code"
/* Alignment shorthands */
.flex-container {
/* Shorthand for align-items and justify-items */
@@ -729,7 +728,7 @@ CSS has introduced several modern shorthand properties that improve code readabi
For browsers that don't support these modern shorthands, Bun converts them to their component longhand properties:
```css
```css title="styles.css" icon="file-code"
.flex-container {
/* Expanded alignment properties */
align-items: center;
@@ -766,11 +765,11 @@ For browsers that don't support these modern shorthands, Bun converts them to th
This conversion ensures your stylesheets remain clean and maintainable while providing the broadest possible browser compatibility.
#### Double position gradients
### Double position gradients
The double position gradient syntax is a modern CSS feature that allows you to create hard color stops in gradients by specifying the same color at two adjacent positions. This creates a sharp transition rather than a smooth fade, which is useful for creating stripes, color bands, and other multi-color designs.
```css
```css title="styles.css" icon="file-code"
.striped-background {
/* Creates a sharp transition from green to red at 30%-40% */
background: linear-gradient(
@@ -799,7 +798,7 @@ The double position gradient syntax is a modern CSS feature that allows you to c
For browsers that don't support this syntax, Bun's CSS bundler automatically converts it to the traditional format by duplicating color stops:
```css
```css title="styles.css" icon="file-code"
.striped-background {
background: linear-gradient(
to right,
@@ -830,11 +829,11 @@ For browsers that don't support this syntax, Bun's CSS bundler automatically con
This conversion lets you use the cleaner double position syntax in your source code while ensuring gradients display correctly in all browsers.
#### system-ui font
### system-ui font
The `system-ui` generic font family lets you use the device's native UI font, creating interfaces that feel more integrated with the operating system. This provides a more native look and feel without having to specify different font stacks for each platform.
```css
```css title="styles.css" icon="file-code"
.native-interface {
/* Use the system's default UI font */
font-family: system-ui;
@@ -848,7 +847,7 @@ The `system-ui` generic font family lets you use the device's native UI font, cr
For browsers that don't support `system-ui`, Bun's CSS bundler automatically expands it to a comprehensive cross-platform font stack:
```css
```css title="styles.css" icon="file-code"
.native-interface {
/* Expanded to support all major platforms */
font-family:
@@ -883,7 +882,7 @@ This approach gives you the simplicity of writing just `system-ui` in your sourc
## CSS Modules
Bun's bundler also supports bundling [CSS modules](https://css-tricks.com/css-modules-part-1-need/) in addition to [regular CSS](/docs/bundler/css) with support for the following features:
Bun's bundler also supports bundling CSS modules in addition to regular CSS with support for the following features:
- Automatically detecting CSS module files (`.module.css`) with zero configuration
- Composition (`composes` property)
@@ -894,17 +893,17 @@ A CSS module is a CSS file (with the `.module.css` extension) where are all clas
Under the hood, Bun's bundler transforms locally scoped class names into unique identifiers.
## Getting started
### Getting started
Create a CSS file with the `.module.css` extension:
composes: background from "./background.module.css";
color: red;
}
```
{% callout %}
<Warning>
When composing classes from separate files, be sure that they do not contain the same properties.
The CSS module spec says that composing classes from separate files with conflicting properties is
undefined behavior, meaning that the output may differ and be unreliable.
{% /callout %}
The CSS module spec says that composing classes from separate files with conflicting properties is undefined behavior, meaning that the output may differ and be unreliable.
Bun's bundler also supports bundling [CSS modules](https://css-tricks.com/css-modules-part-1-need/) in addition to [regular CSS](/docs/bundler/css) with support for the following features:
- Automatically detecting CSS module files (`.module.css`) with zero configuration
- Composition (`composes` property)
- Importing CSS modules into JSX/TSX
- Warnings/errors for invalid usages of CSS modules
A CSS module is a CSS file (with the `.module.css` extension) where are all class names and animations are scoped to the file. This helps you avoid class name collisions as CSS declarations are globally scoped by default.
Under the hood, Bun's bundler transforms locally scoped class names into unique identifiers.
## Getting started
Create a CSS file with the `.module.css` extension:
```css
/* styles.module.css */
.button{
color:red;
}
/* other-styles.module.css */
.button{
color:blue;
}
```
You can then import this file, for example into a TSX file:
description: Migration guide from esbuild to Bun's bundler
---
Bun's bundler API is inspired heavily by esbuild. Migrating to Bun's bundler from esbuild should be relatively painless. This guide will briefly explain why you might consider migrating to Bun's bundler and provide a side-by-side API comparison reference for those who are already familiar with esbuild's API.
There are a few behavioral differences to note.
<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`.
</Note>
<Note>
**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.
</Note>
## Performance
With a performance-minded API coupled with the extensively optimized Zig-based JS/TS parser, Bun's bundler is 1.75x faster than esbuild on esbuild's three.js benchmark.
<Info>Bundling 10 copies of three.js from scratch, with sourcemaps and minification</Info>
## CLI API
Bun and esbuild both provide a command-line interface.
```bash terminal icon="terminal"
# esbuild
esbuild <entrypoint> --outdir=out --bundle
# bun
bun build <entrypoint> --outdir=out
```
In Bun's CLI, simple boolean flags like `--minify` do not accept an argument. Other flags like `--outdir <path>` do accept an argument; these flags can be written as `--outdir out` or `--outdir=out`. Some flags like `--define` can be specified several times: `--define foo=bar --define bar=baz`.
| `--bundle` | n/a | Bun always bundles, use `--no-bundle` to disable this behavior. |
| `--define:K=V` | `--define K=V` | Small syntax difference; no colon.<br/>`esbuild --define:foo=bar`<br/>`bun build --define foo=bar` |
| `--external:<pkg>` | `--external <pkg>` | Small syntax difference; no colon.<br/>`esbuild --external:react`<br/>`bun build --external react` |
| `--format` | `--format` | Bun supports `"esm"` and `"cjs"` currently, but more module formats are planned. esbuild defaults to `"iife"`. |
| `--loader:.ext=loader` | `--loader .ext:loader` | Bun supports a different set of built-in loaders than esbuild; see Bundler > Loaders for a complete reference. The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not yet implemented.<br/><br/>The syntax for `--loader` is slightly different.<br/>`esbuild app.ts --bundle --loader:.svg=text`<br/>`bun build app.ts --loader .svg:text` |
| `--minify` | `--minify` | No differences |
| `--outdir` | `--outdir` | No differences |
| `--outfile` | `--outfile` | No differences |
| `--packages` | `--packages` | No differences |
| `--platform` | `--target` | Renamed to `--target` for consistency with tsconfig. Does not support `neutral`. |
| `--serve` | n/a | Not applicable |
| `--sourcemap` | `--sourcemap` | No differences |
| `--splitting` | `--splitting` | No differences |
| `--target` | n/a | Not supported. Bun's bundler performs no syntactic down-leveling at this time. |
| `--watch` | `--watch` | No differences |
| `--allow-overwrite` | n/a | Overwriting is never allowed |
| `--analyze` | n/a | Not supported |
| `--asset-names` | `--asset-naming` | Renamed for consistency with naming in JS API |
| `--banner` | `--banner` | Only applies to js bundles |
| `--footer` | `--footer` | Only applies to js bundles |
| `--certfile` | n/a | Not applicable |
| `--charset=utf8` | n/a | Not supported |
| `--chunk-names` | `--chunk-naming` | Renamed for consistency with naming in JS API |
| `--color` | n/a | Always enabled |
| `--drop` | `--drop` | |
| `--entry-names` | `--entry-naming` | Renamed for consistency with naming in JS API |
| `--global-name` | n/a | Not applicable, Bun does not support `iife` output at this time |
| `--jsx-dev` | n/a | Bun reads `compilerOptions.jsx` from `tsconfig.json` to determine a default. If `compilerOptions.jsx` is `"react-jsx"`, or if `NODE_ENV=production`, Bun will use the jsx transform. Otherwise, it uses `jsxDEV`. The bundler does not support `preserve`. |
| `absWorkingDir` | n/a | Always set to `process.cwd()` |
| `alias` | n/a | Not supported |
| `allowOverwrite` | n/a | Always false |
| `assetNames` | `naming.asset` | Uses same templating syntax as esbuild, but `[ext]` must be included explicitly.<br/><br/>`ts<br/>Bun.build({<br/> entrypoints: ["./index.tsx"],<br/> naming: {<br/> asset: "[name].[ext]",<br/> },<br/>});<br/>` |
| `banner` | n/a | Not supported |
| `bundle` | n/a | Always true. Use `Bun.Transpiler` to transpile without bundling. |
| `charset` | n/a | Not supported |
| `chunkNames` | `naming.chunk` | Uses same templating syntax as esbuild, but `[ext]` must be included explicitly.<br/><br/>`ts<br/>Bun.build({<br/> entrypoints: ["./index.tsx"],<br/> naming: {<br/> chunk: "[name].[ext]",<br/> },<br/>});<br/>` |
| `color` | n/a | Bun returns logs in the `logs` property of the build result. |
| `conditions` | n/a | Not supported. Export conditions priority is determined by `target`. |
| `define` | `define` | |
| `drop` | n/a | Not supported |
| `entryNames` | `naming` or `naming.entry` | Bun supports a `naming` key that can either be a string or an object. Uses same templating syntax as esbuild, but `[ext]` must be included explicitly.<br/><br/>`ts<br/>Bun.build({<br/> entrypoints: ["./index.tsx"],<br/> // when string, this is equivalent to entryNames<br/> naming: "[name].[ext]",<br/><br/> // granular naming options<br/> naming: {<br/> entry: "[name].[ext]",<br/> asset: "[name].[ext]",<br/> chunk: "[name].[ext]",<br/> },<br/>});<br/>` |
| `format` | `format` | Only supports `"esm"` currently. Support for `"cjs"` and `"iife"` is planned. |
| `globalName` | n/a | Not supported |
| `ignoreAnnotations` | n/a | Not supported |
| `inject` | n/a | Not supported |
| `jsx` | `jsx` | Not supported in JS API, configure in `tsconfig.json` |
| `jsxDev` | `jsxDev` | Not supported in JS API, configure in `tsconfig.json` |
| `jsxFactory` | `jsxFactory` | Not supported in JS API, configure in `tsconfig.json` |
| `jsxFragment` | `jsxFragment` | Not supported in JS API, configure in `tsconfig.json` |
| `jsxImportSource` | `jsxImportSource` | Not supported in JS API, configure in `tsconfig.json` |
| `jsxSideEffects` | `jsxSideEffects` | Not supported in JS API, configure in `tsconfig.json` |
| `keepNames` | n/a | Not supported |
| `legalComments` | n/a | Not supported |
| `loader` | `loader` | Bun supports a different set of built-in loaders than esbuild; see Bundler > Loaders for a complete reference. The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not yet implemented. |
| `logLevel` | n/a | Not supported |
| `logLimit` | n/a | Not supported |
| `logOverride` | n/a | Not supported |
| `mainFields` | n/a | Not supported |
| `mangleCache` | n/a | Not supported |
| `mangleProps` | n/a | Not supported |
| `mangleQuoted` | n/a | Not supported |
| `metafile` | n/a | Not supported |
| `minify` | `minify` | In Bun, `minify` can be a boolean or an object.<br/><br/>`ts<br/>await Bun.build({<br/> entrypoints: ['./index.tsx'],<br/> // enable all minification<br/> minify: true<br/><br/> // granular options<br/> minify: {<br/> identifiers: true,<br/> syntax: true,<br/> whitespace: true<br/> }<br/>})<br/>` |
| `minifyIdentifiers` | `minify.identifiers` | See `minify` |
| `minifySyntax` | `minify.syntax` | See `minify` |
| `minifyWhitespace` | `minify.whitespace` | See `minify` |
| `nodePaths` | n/a | Not supported |
| `outExtension` | n/a | Not supported |
| `outbase` | `root` | Different name |
| `outdir` | `outdir` | No differences |
| `outfile` | `outfile` | No differences |
| `packages` | n/a | Not supported, use `external` |
| `platform` | `target` | Supports `"bun"`, `"node"` and `"browser"` (the default). Does not support `"neutral"`. |
| `plugins` | `plugins` | Bun's plugin API is a subset of esbuild's. Some esbuild plugins will work out of the box with Bun. |
| `target` | n/a | No support for syntax downleveling |
| `treeShaking` | n/a | Always true |
| `tsconfig` | n/a | Not supported |
| `write` | n/a | Set to true if `outdir`/`outfile` is set, otherwise false |
## Plugin API
Bun's plugin API is designed to be esbuild compatible. Bun doesn't support esbuild's entire plugin API surface, but the core functionality is implemented. Many third-party esbuild plugins will work out of the box with Bun.
<Note>
Long term, we aim for feature parity with esbuild's API, so if something doesn't work please file an issue to help us
prioritize.
</Note>
Plugins in Bun and esbuild are defined with a builder object.
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` (same thing but with Bun's `BuildConfig` format) instead.
description: "Generate standalone executables from TypeScript or JavaScript files with Bun"
---
Bun's bundler implements a `--compile` flag for generating a standalone binary from a TypeScript or JavaScript file.
{% codetabs %}
<CodeGroup>
```bash
$ bun build ./cli.ts --compile --outfile mycli
```bash terminal icon="terminal"
bun build ./cli.ts --compile --outfile mycli
```
```ts#cli.ts
```tscli.ts icon="/icons/typescript.svg"
console.log("Hello world!");
```
{% /codetabs %}
</CodeGroup>
This bundles `cli.ts` into an executable that can be executed directly:
```bash terminal icon="terminal"
./mycli
```
$ ./mycli
```txt
Hello world!
```
All imported files and packages are bundled into the executable, along with a copy of the Bun runtime. All built-in Bun and Node.js APIs are supported.
---
## Cross-compile to other platforms
The `--target` flag lets you compile your standalone executable for a different operating system, architecture, or version of Bun than the machine you're running `bun build` on.
To build for Linux x64 (most servers):
```sh
```bash icon="terminal" terminal
bun build --compile --target=bun-linux-x64 ./index.ts --outfile myapp
# To support CPUs from before 2013, use the baseline version (nehalem)
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.
<Warning>
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.
</Warning>
---
## Build-time constants
Use the `--define` flag to inject build-time constants into your executable, such as version numbers, build timestamps, or configuration values:
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 %}
<Note>
For comprehensive examples and advanced patterns, see the [Build-time constants
guide](/guides/runtime/build-time-constants).
</Note>
---
## Deploying to production
@@ -112,7 +133,7 @@ With compiled executables, you can move that cost from runtime to build-time.
When deploying to production, we recommend the following:
```sh
```bash icon="terminal" terminal
bun build --compile --minify --sourcemap ./path/to/my/app.ts --outfile myapp
Bytecode compilation moves parsing overhead for large input files from runtime to bundle time. Your app starts faster, in exchange for making the `bun build` command a little slower. It doesn't obscure source code.
**Experimental:** Bytecode compilation is an experimental feature introduced in Bun v1.1.30. Only `cjs` format is supported (which means no top-level-await). Let us know if you run into any issues!
<Warning>
**Experimental:** Bytecode compilation is an experimental feature. Only `cjs` format is supported (which means no
top-level-await). Let us know if you run into any issues!
</Warning>
### What do these flags do?
@@ -140,55 +166,106 @@ 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.
---
## Embedding runtime arguments
**`--compile-exec-argv="args"`** - Embed runtime arguments that are available via `process.execArgv`:
```bash icon="terminal" terminal
bun build --compile --compile-exec-argv="--smol --user-agent=MyBot" ./app.ts --outfile myapp
By default, standalone executables look for `.env` and `bunfig.toml` files in the directory where the executable is run. You can disable this behavior at build time for deterministic execution regardless of the user's working directory.
```bash icon="terminal" terminal
# Disable .env loading
bun build --compile --no-compile-autoload-dotenv ./app.ts --outfile myapp
# Disable bunfig.toml loading
bun build --compile --no-compile-autoload-bunfig ./app.ts --outfile myapp
# Disable both
bun build --compile --no-compile-autoload-dotenv --no-compile-autoload-bunfig ./app.ts --outfile myapp
```
You can also configure this via the JavaScript API:
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");
```bash icon="terminal" terminal
echo "console.log(\"you shouldn't see this\");" > such-bun.js
bun build --compile ./such-bun.js
```
$ bun build --compile ./such-bun.js
[3ms] bundle 1 modules
```txt
[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:
Normally, running `./such-bun` with arguments would execute the script.
```sh
```bash icon="terminal" terminal
# Executable runs its own entrypoint by default
$ ./such-bun install
you shouldn't see this
./such-bun install
```
```txt
you shouldn't see this
```
However, with the `BUN_BE_BUN=1` environment variable, it acts just like the `bun` binary:
```bash icon="terminal" terminal
# With the env var, the executable acts like the `bun` CLI
$ BUN_BE_BUN=1 ./such-bun install
BUN_BE_BUN=1 ./such-bun install
```
```txt
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 %}
<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 %}
<CodeGroup>
```ts#server.ts
```tsserver.ts icon="/icons/typescript.svg"
import { serve } from "bun";
import index from "./index.html";
@@ -202,35 +279,35 @@ const server = serve({
console.log(`Server running at http://localhost:${server.port}`);
```
```html#index.html
```htmlindex.html icon="file-code"
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link rel="stylesheet" href="./styles.css">
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<h1>Hello World</h1>
<script src="./app.js"></script>
<script src="./app.ts"></script>
</body>
</html>
```
```js#app.js
```ts app.ts icon="file-code"
console.log("Hello from the client!");
```
```css#styles.css
```cssstyles.css icon="file-code"
body {
background-color: #f0f0f0;
}
```
{% /codetabs %}
</CodeGroup>
To build this into a single executable:
```sh
```bash terminal icon="terminal"
bun build --compile ./server.ts --outfile myapp
```
@@ -243,25 +320,27 @@ This creates a self-contained binary that includes:
The result is a single file that can be deployed anywhere without needing Node.js, Bun, or any dependencies installed. Just run:
```sh
```bash terminal icon="terminal"
./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).
For more details on building full-stack applications with Bun, see the [full-stack guide](/bundler/fullstack).
---
## Worker
To use workers in a standalone executable, add the worker's entrypoint to the CLI arguments:
```sh
$ bun build --compile ./index.ts ./my-worker.ts --outfile myapp
```bash terminal icon="terminal"
bun build --compile ./index.ts ./my-worker.ts --outfile myapp
```
Then, reference the worker in your code:
```ts
```ts index.ts icon="/icons/typescript.svg"
console.log("Hello from Bun!");
// Any of these will work:
@@ -270,19 +349,21 @@ new Worker(new URL("./my-worker.ts", import.meta.url));
new Worker(new URL("./my-worker.ts", import.meta.url).href);
```
As of Bun v1.1.25, when you add multiple entrypoints to a standalone executable, they will be bundled separately into the executable.
When you add multiple entrypoints to a standalone executable, they will be bundled separately into the executable.
In the future, we may automatically detect usages of statically-known paths in `new Worker(path)` and then bundle those into the executable, but for now, you'll need to add it to the shell command manually like the above example.
If you use a relative path to a file not included in the standalone executable, it will attempt to load that path from disk relative to the current working directory of the process (and then error if it doesn't exist).
---
## SQLite
You can use `bun:sqlite` imports with `bun build --compile`.
By default, the database is resolved relative to the current working directory of the process.
```js
```ts index.ts icon="/icons/typescript.svg"
import db from "./my.db" with { type: "sqlite" };
console.log(db.query("select * from users LIMIT 1").get());
@@ -290,10 +371,12 @@ console.log(db.query("select * from users LIMIT 1").get());
That means if the executable is located at `/usr/bin/hello`, the user's terminal is located at `/home/me/Desktop`, it will look for `/home/me/Desktop/my.db`.
```bash terminal icon="terminal"
cd /home/me/Desktop
./hello
```
$ cd /home/me/Desktop
$ ./hello
```
---
## Embed assets & files
@@ -301,7 +384,7 @@ Standalone executables support embedding files.
To embed files into an executable with `bun build --compile`, import the file in your code.
```ts
```ts index.ts icon="/icons/typescript.svg"
// this becomes an internal file path
import icon from "./icon.png" with { type: "file" };
import { file } from "bun";
@@ -318,7 +401,7 @@ Embedded files can be read using `Bun.file`'s functions or the Node.js `fs.readF
For example, to read the contents of the embedded file:
```js
```ts index.ts icon="/icons/typescript.svg"
import icon from "./icon.png" with { type: "file" };
If your application wants to embed a SQLite database, set `type: "sqlite"` in the import attribute and the `embed` attribute to `"true"`.
```js
```ts index.ts icon="/icons/typescript.svg"
import myEmbeddedDb from "./my.db" with { type: "sqlite", embed: "true" };
console.log(myEmbeddedDb.query("select * from users LIMIT 1").get());
@@ -341,9 +424,9 @@ This database is read-write, but all changes are lost when the executable exits
### Embed N-API Addons
As of Bun v1.0.23, you can embed `.node` files into executables.
You can embed `.node` files into executables.
```js
```ts index.ts icon="/icons/typescript.svg"
const addon = require("./addon.node");
console.log(addon.hello());
@@ -355,13 +438,13 @@ Unfortunately, if you're using `@mapbox/node-pre-gyp` or other similar tools, yo
To embed a directory with `bun build --compile`, use a shell glob in your `bun build` command:
```sh
$ bun build --compile ./index.ts ./public/**/*.png
```bash terminal icon="terminal"
bun build --compile ./index.ts ./public/**/*.png
```
Then, you can reference the files in your code:
```ts
```ts index.ts icon="/icons/typescript.svg"
import icon from "./public/assets/icon.png" with { type: "file" };
import { file } from "bun";
@@ -379,7 +462,7 @@ This is honestly a workaround, and we expect to improve this in the future with
To get a list of all embedded files, use `Bun.embeddedFiles`:
```js
```ts index.ts icon="/icons/typescript.svg"
import "./icon.png" with { type: "file" };
import { embeddedFiles } from "bun";
@@ -400,141 +483,40 @@ By default, embedded files have a content hash appended to their name. This is u
To disable the content hash, pass `--asset-naming` to `bun build --compile` like this:
```sh
$ bun build --compile --asset-naming="[name].[ext]" ./index.ts
```bash terminal icon="terminal"
bun build --compile --asset-naming="[name].[ext]" ./index.ts
```
---
## Minification
To trim down the size of the executable a little, pass `--minify` to `bun build --compile`. This uses Bun's minifier to reduce the code size. Overall though, Bun's binary is still way too big and we need to make it smaller.
## Using Bun.build() API
You can also generate standalone executables using the `Bun.build()` JavaScript API. This is useful when you need programmatic control over the build process.
### Basic usage
```js
await Bun.build({
entrypoints: ["./app.ts"],
outdir: "./dist",
compile: {
target: "bun-windows-x64",
outfile: "myapp.exe",
},
});
```
### Windows metadata with Bun.build()
When targeting Windows, you can specify metadata through the `windows` object:
```js
await Bun.build({
entrypoints: ["./app.ts"],
outdir: "./dist",
compile: {
target: "bun-windows-x64",
outfile: "myapp.exe",
windows: {
title: "My Application",
publisher: "My Company Inc",
version: "1.2.3.4",
description: "A powerful application built with Bun",
When compiling a standalone executable for Windows, there are several platform-specific options that can be used to customize the generated `.exe` file:
When compiling a standalone executable on Windows, there are two platform-specific options that can be used to customize metadata on the generated `.exe` file:
### Visual customization
- `--windows-icon=path/to/icon.ico` to customize the executable file icon.
- `--windows-hide-console` to disable the background terminal, which can be used for applications that do not need a TTY.
- `--windows-icon=path/to/icon.ico` - Set the executable file icon
- `--windows-hide-console` - Disable the background terminal window (useful for GUI applications)
<Warning>These flags currently cannot be used when cross-compiling because they depend on Windows APIs.</Warning>
### Metadata customization
You can embed version information and other metadata into your Windows executable:
- `--windows-title <STR>` - Set the product name (appears in file properties)
- `--windows-publisher <STR>` - Set the company name
- `--windows-version <STR>` - Set the version number (e.g. "1.2.3.4")
- `--windows-description <STR>` - Set the file description
- `--windows-copyright <STR>` - Set the copyright information
#### Example with all metadata flags:
```sh
bun build --compile ./app.ts \
--outfile myapp.exe \
--windows-title "My Application" \
--windows-publisher "My Company Inc" \
--windows-version "1.2.3.4" \
--windows-description "A powerful application built with Bun" \
This metadata will be visible in Windows Explorer when viewing the file properties:
1. Right-click the executable in Windows Explorer
2. Select "Properties"
3. Go to the "Details" tab
#### Version string format
The `--windows-version` flag accepts version strings in the following formats:
- `"1"` - Will be normalized to "1.0.0.0"
- `"1.2"` - Will be normalized to "1.2.0.0"
- `"1.2.3"` - Will be normalized to "1.2.3.0"
- `"1.2.3.4"` - Full version format
Each version component must be a number between 0 and 65535.
{% callout %}
These flags currently cannot be used when cross-compiling because they depend on Windows APIs. They are only available when building on Windows itself.
{% /callout %}
---
## Code signing on macOS
To codesign a standalone executable on macOS (which fixes Gatekeeper warnings), use the `codesign` command.
To get started, import HTML files and pass them to the `routes` option in `Bun.serve()`.
```ts
import{sql,serve}from"bun";
importdashboardfrom"./dashboard.html";
importhomepagefrom"./index.html";
constserver=serve({
routes:{
// ** HTML imports **
// Bundle & route index.html to "/". This uses HTMLRewriter to scan the HTML for `<script>` and `<link>` tags, run's Bun's JavaScript & CSS bundler on them, transpiles any TypeScript, JSX, and TSX, downlevels CSS with Bun's CSS parser and serves the result.
"/":homepage,
// Bundle & route dashboard.html to "/dashboard"
"/dashboard":dashboard,
// ** API endpoints ** (Bun v1.2.3+ required)
"/api/users":{
asyncGET(req){
constusers=awaitsql`SELECT * FROM users`;
returnResponse.json(users);
},
asyncPOST(req){
const{name,email}=awaitreq.json();
const[user]=
awaitsql`INSERT INTO users (name, email) VALUES (${name}, ${email})`;
returnResponse.json(user);
},
},
"/api/users/:id":asyncreq=>{
const{id}=req.params;
const[user]=awaitsql`SELECT * FROM users WHERE id = ${id}`;
returnResponse.json(user);
},
},
// Enable development mode for:
// - Detailed error messages
// - Hot reloading (Bun v1.2.3+ required)
development: true,
// Prior to v1.2.3, the `fetch` option was used to handle all API requests. It is now optional.
// async fetch(req) {
// // Return 404 for unmatched routes
// return new Response("Not Found", { status: 404 });
// },
});
console.log(`Listening on ${server.url}`);
```
```bash
$ bun run app.ts
```
## HTML imports are routes
The web starts with HTML, and so does Bun's fullstack dev server.
To specify entrypoints to your frontend, import HTML files into your JavaScript/TypeScript/TSX/JSX files.
```ts
importdashboardfrom"./dashboard.html";
importhomepagefrom"./index.html";
```
These HTML files are used as routes in Bun's dev server you can pass to `Bun.serve()`.
```ts
Bun.serve({
routes:{
"/":homepage,
"/dashboard":dashboard,
}
fetch(req){
// ... api requests
},
});
```
When you make a request to `/dashboard` or `/`, Bun automatically bundles the `<script>` and `<link>` tags in the HTML files, exposes them as static routes, and serves the result.
When building locally, enable development mode by setting `development: true` in `Bun.serve()`.
```js-diff
import homepage from "./index.html";
import dashboard from "./dashboard.html";
Bun.serve({
routes: {
"/": homepage,
"/dashboard": dashboard,
}
+ development: true,
fetch(req) {
// ... api requests
},
});
```
When `development` is `true`, Bun will:
- Include the `SourceMap` header in the response so that devtools can show the original source code
- Disable minification
- Re-bundle assets on each request to a .html file
- Enable hot module reloading (unless `hmr: false` is set)
#### Echo console logs from browser to terminal
Bun.serve() supports echoing console logs from the browser to the terminal.
To enable this, pass `console: true` in the `development` object in `Bun.serve()`.
```ts
import homepage from "./index.html";
Bun.serve({
// development can also be an object.
development: {
// Enable Hot Module Reloading
hmr: true,
// Echo console logs from the browser to the terminal
console: true,
},
routes: {
"/": homepage,
},
});
```
When `console: true` is set, Bun will stream console logs from the browser to the terminal. This reuses the existing WebSocket connection from HMR to send the logs.
#### 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()`.
- 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
- Minifies JavaScript/TypeScript/TSX/JSX files
## Plugins
Bun's [bundler plugins](https://bun.com/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`.
### Using TailwindCSS in HTML routes
For example, enable TailwindCSS on your routes by installing and adding the `bun-plugin-tailwind` plugin:
```sh
$ bun add bun-plugin-tailwind
```
```toml#bunfig.toml
[serve.static]
plugins = ["bun-plugin-tailwind"]
```
This will allow you to use TailwindCSS utility classes in your HTML and CSS files. All you need to do is import `tailwindcss` somewhere:
```html#index.html
<!doctype html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="tailwindcss" />
</head>
<body>
<!-- the rest of your HTML... -->
</body>
</html>
```
Or in your CSS:
```css#style.css
@import "tailwindcss";
```
### 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:
```toml#bunfig.toml
[serve.static]
plugins = ["./my-plugin-implementation.ts"]
```
Bun will lazily resolve and load each plugin and use them to bundle your routes.
Note: this is currently in `bunfig.toml` to make it possible to know statically which plugins are in use when we eventually integrate this with the `bun build` CLI. These plugins work in `Bun.build()`'s JS API, but are not yet supported in the CLI.
## How this works
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
- Minifies when `development` is not `true` in `Bun.serve()`
- Rewrites `url` and asset paths to include content-addressable hashes in URLs
```html
<link rel="stylesheet" href="./styles.css" />
```
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).
## This is a work in progress
- This doesn't support `bun build` yet. It also will in the future.
Hot Module Replacement (HMR) allows you to update modules in a running
application without needing a full page reload. This preserves the application
state and improves the development experience.
HMR is enabled by default when using Bun's full-stack development server.
## `import.meta.hot` API Reference
Bun implements a client-side HMR API modeled after [Vite's `import.meta.hot` API](https://vitejs.dev/guide/api-hmr.html). It can be checked for with `if (import.meta.hot)`, tree-shaking it in production
```ts
if(import.meta.hot){
// HMR APIs are available.
}
```
However, **this check is often not needed** as Bun will dead-code-eliminate
calls to all of the HMR APIs in production builds.
```ts
// This entire function call will be removed in production!
import.meta.hot.dispose(()=>{
console.log("dispose");
});
```
For this to work, Bun forces these APIs to be called without indirection. That means the following do not work:
```ts#invalid-hmr-usage.ts
// INVALID: Assigning `hot` to a variable
const hot = import.meta.hot;
hot.accept();
// INVALID: Assigning `import.meta` to a variable
const meta = import.meta;
meta.hot.accept();
console.log(meta.hot.data);
// INVALID: Passing to a function
doSomething(import.meta.hot.dispose);
// OK: The full phrase "import.meta.hot.<API>" must be called directly:
import.meta.hot.accept();
// OK: `data` can be passed to functions:
doSomething(import.meta.hot.data);
```
{% callout %}
**Note** — The HMR API is still a work in progress. Some features are missing. HMR can be disabled in `Bun.serve` by setting the `development` option to `{ hmr: false }`.
// newModules is an array where each item corresponds to the updated module
// or undefined if that module had a syntax error
});
```
Indicates that multiple dependencies' modules can be accepted. This variant accepts an array of dependencies, where the callback will receive the updated modules, and `undefined` for any that had errors.
### `import.meta.hot.data`
`import.meta.hot.data` maintains state between module instances during hot
replacement, enabling data transfer from previous to new versions. When
`import.meta.hot.data` is written into, Bun will also mark this module as
capable of self-accepting (equivalent of calling `import.meta.hot.accept()`).
In production, `data` is inlined to be `{}`, meaning it cannot be used as a state holder.
The above pattern is recommended for stateful modules because Bun knows it can minify `{}.prop ??= value` into `value` in production.
### `import.meta.hot.dispose()`
Attaches an on-dispose callback. This is called:
- Just before the module is replaced with another copy (before the next is loaded)
- After the module is detached (removing all imports to this module, see `import.meta.hot.prune()`)
```ts
const sideEffect = setupSideEffect();
import.meta.hot.dispose(() => {
sideEffect.cleanup();
});
```
This callback is not called on route navigation or when the browser tab closes.
Returning a promise will delay module replacement until the module is disposed.
All dispose callbacks are called in parallel.
### `import.meta.hot.prune()`
Attaches an on-prune callback. This is called when all imports to this module
are removed, but the module was previously loaded.
This can be used to clean up resources that were created when the module was
loaded. Unlike `import.meta.hot.dispose()`, this pairs much better with `accept`
and `data` to manage stateful resources. A full example managing a `WebSocket`:
```ts
import { something } from "./something";
// Initialize or re-use a WebSocket connection
export const ws = (import.meta.hot.data.ws ??= new WebSocket(location.origin));
// If the module's import is removed, clean up the WebSocket connection.
import.meta.hot.prune(() => {
ws.close();
});
```
If `dispose` was used instead, the WebSocket would close and re-open on every
hot update. Both versions of the code will prevent page reloads when imported
files are updated.
### `import.meta.hot.on()` and `off()`
`on()` and `off()` are used to listen for events from the HMR runtime. Event names are prefixed with a prefix so that plugins do not conflict with each other.
```ts
import.meta.hot.on("bun:beforeUpdate", () => {
console.log("before a hot update");
});
```
When a file is replaced, all of its event listeners are automatically removed.
description: Hot Module Replacement (HMR) for Bun's development server
---
Hot Module Replacement (HMR) allows you to update modules in a running application without needing a full page reload. This preserves the application state and improves the development experience.
<Note>HMR is enabled by default when using Bun's full-stack development server.</Note>
## `import.meta.hot` API Reference
Bun implements a client-side HMR API modeled after [Vite's `import.meta.hot` API](https://vite.dev/guide/api-hmr). It can be checked for with `if (import.meta.hot)`, tree-shaking it in production.
// OK: The full phrase "import.meta.hot.<API>" must be called directly:
import.meta.hot.accept();
// OK: `data` can be passed to functions:
doSomething(import.meta.hot.data);
```
</Warning>
<Note>
The HMR API is still a work in progress. Some features are missing. HMR can be disabled in `Bun.serve` by setting the development option to `{ hmr: false }`.
| `hot.accept()` | ✅ | Indicate that a hot update can be replaced gracefully. |
| `hot.data` | ✅ | Persist data between module evaluations. |
| `hot.dispose()` | ✅ | Add a callback function to run when a module is about to be replaced. |
| `hot.invalidate()` | ❌ | |
| `hot.on()` | ✅ | Attach an event listener |
| `hot.off()` | ✅ | Remove an event listener from `on`. |
| `hot.send()` | ❌ | |
| `hot.prune()` | 🚧 | NOTE: Callback is currently never called. |
| `hot.decline()` | ✅ | No-op to match Vite's `import.meta.hot` |
## import.meta.hot.accept()
The `accept()` method indicates that a module can be hot-replaced. When called without arguments, it indicates that this module can be replaced simply by re-evaluating the file. After a hot update, importers of this module will be automatically patched.
This creates a hot-reloading boundary for all of the files that `index.ts` imports. That means whenever `foo.ts` or any of its dependencies are saved, the update will bubble up to `index.ts` will re-evaluate. Files that import `index.ts` will then be patched to import the new version of `getNegativeCount()`. If only `index.ts` is updated, only the one file will be re-evaluated, and the counter in `foo.ts` is reused.
This may be used in combination with `import.meta.hot.data` to transfer state from the previous module to the new one.
<Info>
When no modules call `import.meta.hot.accept()` (and there isn't React Fast Refresh or a plugin calling it for you),
the page will reload when the file updates, and a console warning shows which files were invalidated. This warning is
safe to ignore if it makes more sense to rely on full page reloads.
</Info>
### With callback
When provided one callback, `import.meta.hot.accept` will function how it does in Vite. Instead of patching the importers of this module, it will call the callback with the new module.
// newModules is an array where each item corresponds to the updated module
// or undefined if that module had a syntax error
});
```
Indicates that multiple dependencies' modules can be accepted. This variant accepts an array of dependencies, where the callback will receive the updated modules, and `undefined` for any that had errors.
## import.meta.hot.data
`import.meta.hot.data` maintains state between module instances during hot replacement, enabling data transfer from previous to new versions. When `import.meta.hot.data` is written into, Bun will also mark this module as capable of self-accepting (equivalent of calling `import.meta.hot.accept()`).
<Warning>This callback is not called on route navigation or when the browser tab closes.</Warning>
Returning a promise will delay module replacement until the module is disposed. All dispose callbacks are called in parallel.
## import.meta.hot.prune()
Attaches an on-prune callback. This is called when all imports to this module are removed, but the module was previously loaded.
This can be used to clean up resources that were created when the module was loaded. Unlike `import.meta.hot.dispose()`, this pairs much better with `accept` and `data` to manage stateful resources. A full example managing a WebSocket:
export const ws = (import.meta.hot.data.ws ??= new WebSocket(location.origin));
// If the module's import is removed, clean up the WebSocket connection.
import.meta.hot.prune(() => {
ws.close();
});
```
<Info>
If `dispose` was used instead, the WebSocket would close and re-open on every hot update. Both versions of the code
will prevent page reloads when imported files are updated.
</Info>
## import.meta.hot.on() and off()
`on()` and `off()` are used to listen for events from the HMR runtime. Event names are prefixed with a prefix so that plugins do not conflict with each other.
description: Build static sites, landing pages, and web applications with Bun's bundler
---
Bun's bundler has first-class support for HTML. Build static sites, landing pages, and web applications with zero configuration. Just point Bun at your HTML file and it handles everything else.
```html title="index.html" icon="file-code"
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="./styles.css" />
<script src="./app.ts" type="module"></script>
</head>
<body>
<img src="./logo.png" />
</body>
</html>
```
To get started, pass HTML files to `bun`.
```bash terminal icon="terminal"
bun ./index.html
```
```
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Press h + Enter to show shortcuts
```
Bun's development server provides powerful features with zero configuration:
- **Automatic Bundling** - Bundles and serves your HTML, JavaScript, and CSS
- **Multi-Entry Support** - Handles multiple HTML entry points and glob entry points
- **Modern JavaScript** - TypeScript & JSX support out of the box
- **Smart Configuration** - Reads `tsconfig.json` for paths, JSX options, experimental decorators, and more
- **Plugins** - Plugins for TailwindCSS and more
- **ESM & CommonJS** - Use ESM and CommonJS in your JavaScript, TypeScript, and JSX files
- **CSS Bundling & Minification** - Bundles CSS from `<link>` tags and `@import` statements
- **Asset Management** - Automatic copying & hashing of images and assets; Rewrites asset paths in JavaScript, CSS, and HTML
## Single Page Apps (SPA)
When you pass a single `.html` file to Bun, Bun will use it as a fallback route for all paths. This makes it perfect for single page apps that use client-side routing:
```bash terminal icon="terminal"
bun index.html
```
```
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Press h + Enter to show shortcuts
```
Your React or other SPA will work out of the box — no configuration needed. All routes like `/about`, `/users/123`, etc. will serve the same HTML file, letting your client-side router handle the navigation.
```html title="index.html" icon="file-code"
<!doctype html>
<html>
<head>
<title>My SPA</title>
<script src="./app.tsx" type="module"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
```
## Multi-page apps (MPA)
Some projects have several separate routes or HTML files as entry points. To support multiple entry points, pass them all to `bun`:
```bash terminal icon="terminal"
bun ./index.html ./about.html
```
```txt
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Routes:
/ ./index.html
/about ./about.html
Press h + Enter to show shortcuts
```
This will serve:
- `index.html` at `/`
- `about.html` at `/about`
### Glob patterns
To specify multiple files, you can use glob patterns that end in `.html`:
```bash terminal icon="terminal"
bun ./**/*.html
```
```
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Routes:
/ ./index.html
/about ./about.html
Press h + Enter to show shortcuts
```
### Path normalization
The base path is chosen from the longest common prefix among all the files.
```bash terminal icon="terminal"
bun ./index.html ./about/index.html ./about/foo/index.html
```
```
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Routes:
/ ./index.html
/about ./about/index.html
/about/foo ./about/foo/index.html
Press h + Enter to show shortcuts
```
## JavaScript, TypeScript, and JSX
Bun's transpiler natively implements JavaScript, TypeScript, and JSX support. Learn more about loaders in Bun.
<Note>Bun's transpiler is also used at runtime.</Note>
### ES Modules & CommonJS
You can use ESM and CJS in your JavaScript, TypeScript, and JSX files. Bun will handle the transpilation and bundling automatically.
There is no pre-build or separate optimization step. It's all done at the same time.
Learn more about module resolution in Bun.
## CSS
Bun's CSS parser is also natively implemented (clocking in around 58,000 lines of Zig).
It's also a CSS bundler. You can use `@import` in your CSS files to import other CSS files.
For example:
<CodeGroup>
```css styles.css icon="file-code"
@import "./abc.css";
.container {
background-color: blue;
}
```
```css abc.css icon="file-code"
body {
background-color: red;
}
```
</CodeGroup>
This outputs:
```css styles.css icon="file-code"
body {
background-color: red;
}
.container {
background-color: blue;
}
```
### Referencing local assets in CSS
You can reference local assets in your CSS files.
```css styles.css icon="file-code"
body {
background-image: url("./logo.png");
}
```
This will copy `./logo.png` to the output directory and rewrite the path in the CSS file to include a content hash.
```css styles.css icon="file-code"
body {
background-image: url("./logo-[ABC123].png");
}
```
### Importing CSS in JavaScript
To associate a CSS file with a JavaScript file, you can import it in your JavaScript file.
```ts app.ts icon="/icons/typescript.svg"
import "./styles.css";
import "./more-styles.css";
```
This generates `./app.css` and `./app.js` in the output directory. All CSS files imported from JavaScript will be bundled into a single CSS file per entry point. If you import the same CSS file from multiple JavaScript files, it will only be included once in the output CSS file.
## Plugins
The dev server supports plugins.
### Tailwind CSS
To use TailwindCSS, install the `bun-plugin-tailwind` plugin:
```bash terminal icon="terminal"
# Or any npm client
bun install --dev bun-plugin-tailwind
```
Then, add the plugin to your `bunfig.toml`:
```toml title="bunfig.toml" icon="settings"
[serve.static]
plugins = ["bun-plugin-tailwind"]
```
Then, reference TailwindCSS in your HTML via `<link>` tag, `@import` in CSS, or import in JavaScript.
<Tabs>
<Tab title="index.html">
```html title="index.html" icon="file-code"
<!-- Reference TailwindCSS in your HTML -->
<link rel="stylesheet" href="tailwindcss" />
```
</Tab>
<Tab title="styles.css">
```css title="styles.css" icon="file-code"
@import "tailwindcss";
```
</Tab>
<Tab title="app.ts">
```ts title="app.ts" icon="/icons/typescript.svg"
import "tailwindcss";
```
</Tab>
</Tabs>
<Info>Only one of those are necessary, not all three.</Info>
## Inline environment variables
Bun can replace `process.env.*` references in your JavaScript and TypeScript with their actual values at build time. This is useful for injecting configuration like API URLs or feature flags into your frontend code.
### Dev server (runtime)
To inline environment variables when using `bun ./index.html`, configure the `env` option in your `bunfig.toml`:
```toml title="bunfig.toml" icon="settings"
[serve.static]
env = "PUBLIC_*" # only inline env vars starting with PUBLIC_ (recommended)
# env = "inline" # inline all environment variables
# env = "disable" # disable env var replacement (default)
```
<Note>
This only works with literal `process.env.FOO` references, not `import.meta.env` or indirect access like `const env =
process.env; env.FOO`.
If an environment variable is not set, you may see runtime errors like `ReferenceError: process
is not defined` in the browser.
</Note>
Then run the dev server:
```bash terminal icon="terminal"
PUBLIC_API_URL=https://api.example.com bun ./index.html
```
### Build for production
When building static HTML for production, use the `env` option to inline environment variables:
<Tabs>
<Tab title="CLI">
```bash terminal icon="terminal"
# Inline all environment variables
bun build ./index.html --outdir=dist --env=inline
# Only inline env vars with a specific prefix (recommended)
bun build ./index.html --outdir=dist --env=PUBLIC_*
Bun's dev server supports streaming console logs from the browser to the terminal.
To enable, pass the `--console` CLI flag.
```bash terminal icon="terminal"
bun ./index.html --console
```
```
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Press h + Enter to show shortcuts
```
Each call to `console.log` or `console.error` will be broadcast to the terminal that started the server. This is useful to see errors from the browser in the same place you run your server. This is also useful for AI agents that watch terminal output.
Internally, this reuses the existing WebSocket connection from hot module reloading to send the logs.
## Edit files in the browser
Bun's frontend dev server has support for Automatic Workspace Folders in Chrome DevTools, which lets you save edits to files in the browser.
## Keyboard Shortcuts
While the server is running:
- `o + Enter` - Open in browser
- `c + Enter` - Clear console
- `q + Enter` (or `Ctrl+C`) - Quit server
## Build for Production
When you're ready to deploy, use `bun build` to create optimized production bundles:
// Bun's bundler will scan the HTML for <script> tags, <link rel="stylesheet"> tags, and other assets
// and bundle them automatically
contents: rewriter.transform(html),
loader: "html",
};
});
},
},
],
});
```
## What Gets Processed?
Bun automatically handles all common web assets:
- **Scripts** (`<script src>`) are run through Bun's JavaScript/TypeScript/JSX bundler
- **Stylesheets** (`<link rel="stylesheet">`) are run through Bun's CSS parser & bundler
- **Images** (`<img>`, `<picture>`) are copied and hashed
- **Media** (`<video>`, `<audio>`, `<source>`) are copied and hashed
- Any `<link>` tag with an `href` attribute pointing to a local file is rewritten to the new path, and hashed
All paths are resolved relative to your HTML file, making it easy to organize your project however you want.
<Warning>
**This is a work in progress**
- Need more plugins
- Need more configuration options for things like asset handling
- Need a way to configure CORS, headers, etc.
{/* todo: find the correct link to link to as this 404's and there isn't any similar files */}
{/* If you want to submit a PR, most of the code is [here](https://github.com/oven-sh/bun/blob/main/src/bun.js/api/bun/html-rewriter.ts). You could even copy paste that file into your project and use it as a starting point. */}
</Warning>
## How this works
This is a small wrapper around Bun's support for HTML imports in JavaScript.
## Adding a backend to your frontend
To add a backend to your frontend, you can use the "routes" option in `Bun.serve`.
Bun's bundler has first-class support for HTML. Build static sites, landing pages, and web applications with zero configuration. Just point Bun at your HTML file and it handles everything else.
Bun's development server provides powerful features with zero configuration:
- **Automatic Bundling** - Bundles and serves your HTML, JavaScript, and CSS
- **Multi-Entry Support** - Handles multiple HTML entry points and glob entry points
- **Modern JavaScript** - TypeScript & JSX support out of the box
- **Smart Configuration** - Reads `tsconfig.json` for paths, JSX options, experimental decorators, and more
- **Plugins** - Plugins for TailwindCSS and more
- **ESM & CommonJS** - Use ESM and CommonJS in your JavaScript, TypeScript, and JSX files
- **CSS Bundling & Minification** - Bundles CSS from `<link>` tags and `@import` statements
- **Asset Management**
- Automatic copying & hashing of images and assets
- Rewrites asset paths in JavaScript, CSS, and HTML
## Single Page Apps (SPA)
When you pass a single .html file to Bun, Bun will use it as a fallback route for all paths. This makes it perfect for single page apps that use client-side routing:
Your React or other SPA will work out of the box — no configuration needed. All routes like `/about`, `/users/123`, etc. will serve the same HTML file, letting your client-side router handle the navigation.
```html#index.html
<!doctype html>
<html>
<head>
<title>My SPA</title>
<script src="./app.tsx" type="module"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
```
## Multi-page apps (MPA)
Some projects have several separate routes or HTML files as entry points. To support multiple entry points, pass them all to `bun`
Bun's transpiler natively implements JavaScript, TypeScript, and JSX support. [Learn more about loaders in Bun](/docs/bundler/loaders).
Bun's transpiler is also used at runtime.
### ES Modules & CommonJS
You can use ESM and CJS in your JavaScript, TypeScript, and JSX files. Bun will handle the transpilation and bundling automatically.
There is no pre-build or separate optimization step. It's all done at the same time.
Learn more about [module resolution in Bun](/docs/runtime/modules).
## CSS
Bun's CSS parser is also natively implemented (clocking in around 58,000 lines of Zig).
It's also a CSS bundler. You can use `@import` in your CSS files to import other CSS files.
For example:
```css#styles.css
@import "./abc.css";
.container {
background-color: blue;
}
```
```css#abc.css
body {
background-color: red;
}
```
This outputs:
```css#styles.css
body {
background-color: red;
}
.container {
background-color: blue;
}
```
### Referencing local assets in CSS
You can reference local assets in your CSS files.
```css#styles.css
body {
background-image: url("./logo.png");
}
```
This will copy `./logo.png` to the output directory and rewrite the path in the CSS file to include a content hash.
```css#styles.css
body {
background-image: url("./logo-[ABC123].png");
}
```
### Importing CSS in JavaScript
To associate a CSS file with a JavaScript file, you can import it in your JavaScript file.
```ts#app.ts
import "./styles.css";
import "./more-styles.css";
```
This generates `./app.css` and `./app.js` in the output directory. All CSS files imported from JavaScript will be bundled into a single CSS file per entry point. If you import the same CSS file from multiple JavaScript files, it will only be included once in the output CSS file.
## Plugins
The dev server supports plugins.
### Tailwind CSS
To use TailwindCSS, install the `bun-plugin-tailwind` plugin:
```bash
# Or any npm client
$ bun install --dev bun-plugin-tailwind
```
Then, add the plugin to your `bunfig.toml`:
```toml
[serve.static]
plugins = ["bun-plugin-tailwind"]
```
Then, reference TailwindCSS in your HTML via `<link>` tag, `@import` in CSS, or `import` in JavaScript.
{% codetabs %}
```html#index.html
<!-- Reference TailwindCSS in your HTML -->
<link rel="stylesheet" href="tailwindcss" />
```
```css#styles.css
/* Import TailwindCSS in your CSS */
@import "tailwindcss";
```
```ts#app.ts
/* Import TailwindCSS in your JavaScript */
import "tailwindcss";
```
{% /codetabs %}
Only one of those are necessary, not all three.
### Echo console logs from browser to terminal
Bun's dev server supports streaming console logs from the browser to the terminal.
Each call to `console.log` or `console.error` will be broadcast to the terminal that started the server. This is useful to see errors from the browser in the same place you run your server. This is also useful for AI agents that watch terminal output.
Internally, this reuses the existing WebSocket connection from hot module reloading to send the logs.
### Edit files in the browser
Bun's frontend dev server has support for [Automatic Workspace Folders](https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md) in Chrome DevTools, which lets you save edits to files in the browser.
{% image src="/images/bun-chromedevtools.gif" alt="Bun's frontend dev server has support for Automatic Workspace Folders in Chrome DevTools, which lets you save edits to files in the browser." /%}
{% details summary="How it works" %}
Bun's dev server automatically adds a `/.well-known/appspecific/com.chrome.devtools.json` route to the server.
This route returns a JSON object with the following shape:
```json
{
"workspace": {
"root": "/path/to/your/project",
"uuid": "a-unique-identifier-for-this-workspace"
}
}
```
For security reasons, this is only enabled when:
1. The request is coming from localhost, 127.0.0.1, or ::1.
2. Hot Module Reloading is enabled.
3. The `chromeDevToolsAutomaticWorkspaceFolders` flag is set to `true` or `undefined`.
4. There are no other routes that match the request.
You can disable this by passing `development: { chromeDevToolsAutomaticWorkspaceFolders: false }` in `Bun.serve`'s options.
{% /details %}
## Keyboard Shortcuts
While the server is running:
- `o + Enter` - Open in browser
- `c + Enter` - Clear console
- `q + Enter` (or Ctrl+C) - Quit server
## Build for Production
When you're ready to deploy, use `bun build` to create optimized production bundles:
{% codetabs %}
```bash#CLI
$ bun build ./index.html --minify --outdir=dist
```
```ts#API
Bun.build({
entrypoints: ["./index.html"],
outdir: "./dist",
minify: {
whitespace: true,
identifiers: true,
syntax: true,
}
});
```
{% /codetabs %}
Currently, plugins are only supported through `Bun.build`'s API or through `bunfig.toml` with the frontend dev server - not yet supported in `bun build`'s CLI.
### Watch Mode
You can run `bun build --watch` to watch for changes and rebuild automatically. This works nicely for library development.
You've never seen a watch mode this fast.
### Plugin API
Need more control? Configure the bundler through the JavaScript API and use Bun's builtin `HTMLRewriter` to preprocess HTML.
```ts
await Bun.build({
entrypoints: ["./index.html"],
outdir: "./dist",
minify: true,
plugins: [
{
// A plugin that makes every HTML tag lowercase
name: "lowercase-html-plugin",
setup({ onLoad }) {
const rewriter = new HTMLRewriter().on("*", {
element(element) {
element.tagName = element.tagName.toLowerCase();
},
text(element) {
element.replace(element.text.toLowerCase());
},
});
onLoad({ filter: /\.html$/ }, async args => {
const html = await Bun.file(args.path).text();
return {
// Bun's bundler will scan the HTML for <script> tags, <link rel="stylesheet"> tags, and other assets
// and bundle them automatically
contents: rewriter.transform(html),
loader: "html",
};
});
},
},
],
});
```
## What Gets Processed?
Bun automatically handles all common web assets:
- Scripts (`<script src>`) are run through Bun's JavaScript/TypeScript/JSX bundler
- Stylesheets (`<link rel="stylesheet">`) are run through Bun's CSS parser & bundler
- Images (`<img>`, `<picture>`) are copied and hashed
- Media (`<video>`, `<audio>`, `<source>`) are copied and hashed
- Any `<link>` tag with an `href` attribute pointing to a local file is rewritten to the new path, and hashed
All paths are resolved relative to your HTML file, making it easy to organize your project however you want.
## This is a work in progress
- Need more plugins
- Need more configuration options for things like asset handling
- Need a way to configure CORS, headers, etc.
If you want to submit a PR, most of the [code is here](https://github.com/oven-sh/bun/blob/main/src/js/internal/html.ts). You could even copy paste that file into your project and use it as a starting point.
## How this works
This is a small wrapper around Bun's support for HTML imports in JavaScript.
### Adding a backend to your frontend
To add a backend to your frontend, you can use the `"routes"` option in `Bun.serve`.
Learn more in [the full-stack docs](/docs/bundler/fullstack).
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.