new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · all subjects

guides

347 notes in this subject, read out of this brain and free to use. This is page 4 of 6.

Configure JFrog Artifactory with bunfig.toml

To use JFrog Artifactory as a private npm registry with bun install, add a bunfig.toml file to the project root with the [install.registry] section. Set the url field to the Artifactory npm endpoint in the format: https://MY_SUBDOMAIN.jfrog.io/artifactory/api/npm/npm/_auth=MY_TOKEN. Replace MY_SUBDOMAIN with your JFrog Artifactory subdomain (for example, jarred1234) and MY_TOKEN with your JFrog Artifactory API token.

Use environment variable for Artifactory registry URL in bunfig.toml

In bunfig.toml, the install.registry.url field can use an environment variable reference. You can set url = "$NPM_CONFIG_REGISTRY" to use the NPM_CONFIG_REGISTRY environment variable instead of hardcoding the registry URL.

Configure JFrog Artifactory with NPM_CONFIG_REGISTRY environment variable

Similar to npm, bun install supports the NPM_CONFIG_REGISTRY environment variable to configure JFrog Artifactory as the package registry. This allows configuring the registry without editing bunfig.toml.

Specify Bun version in setup-bun

To specify which version of Bun to install, add a `with` section to the `oven-sh/setup-bun@v2` action and set `bun-version` to a specific version number (e.g. 1.3.3), "latest", "canary", or a commit SHA.

setup-bun GitHub Action for installing Bun

The official GitHub Action to install Bun in GitHub Actions runners is `oven-sh/setup-bun`. Use `oven-sh/setup-bun@v2` in your workflow steps.

Using setup-bun in GitHub Actions workflow

In a GitHub Actions workflow, use the checkout action followed by the setup-bun action, then run any `bun` or `bunx` commands. Example: use `actions/checkout@v4`, then `oven-sh/setup-bun@v2`, then run commands like `bun install`, `bun index.ts`, or `bun run build`.

setup-bun action example with version specification

To install a specific version of Bun in GitHub Actions, use the following configuration: ```yaml - uses: oven-sh/setup-bun@v2 with: bun-version: 1.3.3 ``` The `bun-version` parameter accepts a version number, "latest", "canary", or a commit SHA.

Cross-platform builds with --define

When building for multiple platforms, build-time constants work the same way across platforms. Use the --target flag to specify the platform and --define to inject platform-specific constants. Example: `bun build --compile --target=bun-linux-x64 --define PLATFORM='"linux"' src/app.ts --outfile app-linux`

--define flag for bun build

The --define flag is passed to `bun build` or `bun build --compile` to inject build-time constants into your application. Build-time constants are embedded directly into compiled code with zero runtime overhead, making them immutable and optimizable through dead code elimination. Example: `bun build --compile --define BUILD_VERSION='"1.2.3"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/index.ts --outfile myapp`

--define value format requirements

Values for --define must be valid JSON and are inlined as JavaScript expressions. Strings must be JSON-quoted: `--define VERSION='"1.0.0"'`. Numbers are JSON literals: `--define PORT=3000`. Booleans are JSON literals: `--define DEBUG=true`. Objects and arrays require single quotes to wrap the JSON: `--define 'CONFIG={"host":"localhost","port":3000}'` or `--define 'FEATURES=["auth","billing","analytics"]'`. Missing quotes around strings will not work.

--define property access patterns

Keys in --define can be property access patterns, not just simple identifiers. This allows replacing nested properties at build time. Examples: `--define 'process.env.NODE_ENV="production"'` replaces process.env.NODE_ENV with "production", `--define 'process.env.API_KEY="abc123"'` replaces the API_KEY, and `--define 'window.myApp.version="1.0.0"'` replaces nested properties. This enables inlining environment variables at build time.

TypeScript declarations for build-time constants

For TypeScript projects, declare build-time constants in a declaration file to avoid type errors. Example: create `types/build-constants.d.ts` with declarations like `declare const BUILD_VERSION: string;`, `declare const BUILD_TIME: string;`, `declare const NODE_ENV: "development" | "staging" | "production";`, and `declare const DEBUG: boolean;`

Dead code elimination with build-time constants

When using build-time constants in conditional branches, the bundler can perform dead code elimination. For example, if a branch checks `if (ENABLE_ANALYTICS)` and ENABLE_ANALYTICS is defined as false, the entire block inside the condition can be removed during optimization, reducing binary size.

Using shell commands for dynamic build-time constants

Shell commands can be used to generate build-time constant values. Example: `bun build --compile --define BUILD_VERSION="\"$(git describe --tags --always)\"" --define BUILD_TIME="\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"" --define GIT_COMMIT="\"$(git rev-parse HEAD)\"" src/cli.ts --outfile mycli` uses git and date commands to inject version, build time, and commit information.

Build automation script with build-time constants

A build script can use Bun's $ command to execute shell commands and inject their output as build-time constants. Example: `const version = await $\`git describe --tags --always\`.text(); const buildTime = new Date().toISOString(); const gitCommit = await $\`git rev-parse HEAD\`.text(); await Bun.build({ entrypoints: ["./src/cli.ts"], outdir: "./dist", define: { BUILD_VERSION: JSON.stringify(version.trim()), BUILD_TIME: JSON.stringify(buildTime), GIT_COMMIT: JSON.stringify(gitCommit.trim()) } });`

Bun.build define option

The Bun.build() JavaScript API accepts a `define` object option where keys are constant names and values are their JSON-serialized replacements. Example: `await Bun.build({ entrypoints: ["./src/index.ts"], outdir: "./dist", define: { BUILD_VERSION: '"1.0.0"', BUILD_TIME: '"2024-01-15T10:30:00Z"', DEBUG: "false" } });`

List macOS signing identities

To see available code signing identities on macOS, run: security find-identity -v -p codesigning. This outputs a list of identities with their IDs and descriptions.

entitlements.plist for JavaScript engine on macOS

Create an entitlements.plist file with the following keys to allow the Bun JavaScript engine to function correctly on macOS: com.apple.security.cs.allow-jit (true), com.apple.security.cs.allow-unsigned-executable-memory (true), com.apple.security.cs.disable-executable-page-protection (true), com.apple.security.cs.allow-dyld-environment-variables (true), com.apple.security.cs.disable-library-validation (true).

Codesign executable on macOS

Sign a compiled executable using: codesign --entitlements entitlements.plist -vvvv --deep --sign "SIGNING_IDENTITY" ./myapp --force. Replace SIGNING_IDENTITY with the identity from security find-identity output.

Verify codesigned executable on macOS

After codesigning, verify the signature is valid by running: codesign -vvv --verify ./myapp

macOS codesigning guide requires Bun v1.2.4 or newer

The macOS codesigning process for Bun executables requires Bun version 1.2.4 or newer.

Compile executable with --compile flag

To create a single-file JavaScript executable, use the bun build command with the --compile flag, specifying an entry file and output file. Example: bun build --compile ./path/to/entry.ts --outfile myapp

Load heap snapshots in Chrome DevTools Memory tab

To view V8 heap snapshots in Chrome DevTools, open DevTools with F12 or right-click and select "Inspect", go to the "Memory" tab, click the "Load" button (folder icon), and select your .heapsnapshot file.

Default import from JSON5

To import a JSON5 file with a default import, use `import config from "./config.json5";` and access properties normally like `config.database.host`.

JSON5 file imports

Bun natively supports importing `.json5` files. JSON5 files can contain comments and unquoted keys. Files can be imported as default imports or using named imports to destructure top-level properties.

Named imports from JSON5

Top-level properties of a JSON5 file can be imported as named exports using destructuring syntax like `import { database, server, features } from "./config.json5";`.

Bun.JSON5.parse() runtime parsing

For parsing JSON5 strings at runtime, use the `Bun.JSON5.parse()` method. This accepts a JSON5-formatted string and returns the parsed object.

JSON5 format features

JSON5 format allows comments, unquoted keys, and trailing commas in objects and arrays. For example: `{ database: { host: "localhost", }, }` is valid JSON5.

.env files Bun loads automatically

Bun automatically reads environment variable files in the following order of increasing precedence: .env, .env.production/.env.development/.env.test (depending on NODE_ENV value), and .env.local (which is not loaded when NODE_ENV=test).

.env file format

Environment variables in .env files use KEY=VALUE format with one variable per line, such as FOO=hello and BAR=world.

Set environment variables on command line for bun run

Environment variables can be set inline before the bun run command. On Linux/macOS use: FOO=helloworld bun run dev. On Windows CMD use: set FOO=helloworld && bun run dev. On Windows PowerShell use: $env:FOO="helloworld"; bun run dev.

tsconfig.json paths remapping syntax and examples

In `tsconfig.json` under `compilerOptions.paths`, define path mappings as key-value pairs where the key is the import pattern and the value is an array of file paths. Example: `"my-custom-name": ["./node_modules/zod"]` remaps imports of `my-custom-name` to `./node_modules/zod`. Wildcard patterns like `"@components/*": ["./src/components/*"]` remap `@components/Button` to `./src/components/Button`.

Bun reads tsconfig.json paths field for import remapping

Bun reads the `paths` field in `tsconfig.json` to re-write import paths. This is useful for aliasing package names or avoiding long relative paths.

tsconfig.json enables top-level await and extensionless imports

With the recommended tsconfig.json configuration, you can use top-level await, extensioned or extensionless imports, and JSX in your Bun project.

Bun implements WebKit Inspector Protocol for debugging

Bun speaks the WebKit Inspector Protocol, which allows debugging code with an interactive debugger.

Install Bun VS Code extension from marketplace

The Bun for Visual Studio Code extension can be installed from the VS Code marketplace website at https://marketplace.visualstudio.com/items?itemName=oven.bun-vscode by clicking Install. Alternatively, search for 'bun-vscode' in the Extensions tab of VS Code. Verify that the extension is published by the official Oven organization.

Command Palette access shortcuts

Open the Command Palette in VS Code by clicking View > Command Palette, or typing Ctrl+Shift+P on Windows and Linux, or Cmd+Shift+P on Mac.

VS Code debugger extension is buggy, web debugger recommended

The Bun VS Code extension is buggy. Bun recommends using the web debugger instead of the VS Code extension for debugging.

Bun: Debug File command with breakpoint support

The 'Bun: Debug File' command executes code and prints the output to the Debug Console in VS Code. You can set breakpoints by clicking to the left of a line number (a red dot appears). When the file runs with 'Bun: Debug File', execution pauses at breakpoints. You can inspect variables in scope and step through code line-by-line using VS Code controls.

Bun: Run File command runs code without breakpoints

The 'Bun: Run File' command executes code and prints the output to the Debug Console in VS Code. Breakpoints are ignored. This is similar to executing the file with 'bun <file>' from the command line.

Convert Node.js Readable stream to ArrayBuffer

To convert a Node.js Readable stream to an ArrayBuffer in Bun, create a Response object with the stream as the body, then call the arrayBuffer() method on the Response. Example: const stream = Readable.from(["Hello, ", "world!"]); const buf = await new Response(stream).arrayBuffer();

Bun Inspector Protocol and WebKit compatibility

Bun speaks the WebKit Inspector Protocol. Bun hosts a web-based debugger at debug.bun.sh, which is a modified version of WebKit's Web Inspector Interface and will look familiar to Safari users.

Enable web debugging with --inspect flag

To enable debugging when running code with Bun, use the --inspect flag. This starts a WebSocket server on an available port that debugging tools connect to in order to introspect the running Bun process.

WebSocket server port and debugging URL

When running bun --inspect, it starts a WebSocket server on an available port (commonly localhost:6499) and provides a debug.bun.sh URL with a session token for connecting to the debugger in a browser.

Web debugger features

The web-based debugger at debug.bun.sh allows you to view the source code of the running file, view and set breakpoints, execute code with the built-in console, inspect local variables in scope, and drill down to see their properties and methods.

Debugger control flow buttons

The debugger provides four control flow buttons: (1) Continue script execution — runs the program until the next breakpoint or exception. (2) Step over — continues to the next line. (3) Step into — if the current statement contains a function call, steps into the called function. (4) Step out — if the current statement is a function call, finishes executing it, then steps out of the function to the location where it was called.

Setting breakpoints in the debugger

To set a breakpoint in the Bun debugger, open the Sources tab which shows the code of the running file, and click on a line number to set a breakpoint at that location.

Debugging console context

The console at the bottom of the debugger allows you to run arbitrary code in the context of the paused program, with full access to the variables in scope at the breakpoint.

Convert Node.js Readable stream to string

To convert a Node.js Readable stream to a string in Bun, create a Response with the stream as the body, then call response.text(). Example: const stream = Readable.from([Buffer.from('Hello, world!')]); const text = await new Response(stream).text();

Convert Node.js Readable stream to JSON

To convert a Node.js Readable stream to a JSON object in Bun, create a Response with the stream as the body, then call response.json(). Example: pass a Readable stream to the Response constructor, then await the json() method.

Convert Node.js Readable stream to Uint8Array

To convert a Node.js Readable stream to a Uint8Array in Bun, create a Response with the stream as the body, then call bytes(). The example shows importing Readable from 'stream', creating a stream with Readable.from(), passing it to a Response constructor, and calling the bytes() method which returns a Promise<Uint8Array>.

Example test with @testing-library/svelte

Import the Svelte component and use `render` from `@testing-library/svelte` to render it. The render function returns an object with `getByText` for querying elements and `component` for accessing component state via `component.$$ctx[index]`. Use `fireEvent.click()` to simulate user interactions.

Test Svelte components with bun test using Plugin API

To test Svelte components with Bun, use the Plugin API to add a custom loader for `.svelte` files and the `test.preload` option in `bunfig.toml` to load the plugin before tests run. First install `@testing-library/svelte`, `svelte`, and `@happy-dom/global-registrator` with `bun add @testing-library/svelte svelte@4 @happy-dom/global-registrator`.

Svelte loader plugin for test.preload

Create a Svelte loader plugin using the Plugin API. The plugin registers an `onLoad` handler for files matching `/\.svelte(\?[^.]+)?$/`. For each matched file, it reads the source as UTF-8, compiles it with `svelte/compiler` using options `{ filetitle: path, generate: "client", dev: false }`, and returns an object with `contents` set to `result.js.code` and `loader` set to `"js"`. The plugin should also import and use `beforeEach` and `afterEach` from `bun:test` to register and unregister `GlobalRegistrator` from `@happy-dom/global-registrator` around each test.

Import and require Svelte files in tests

After loading the Svelte plugin via `test.preload`, Bun will load each `.svelte` file as a JavaScript module when imported or required in test files. The compiled component can then be used with testing libraries like `@testing-library/svelte`.

Happy DOM preload script for Bun tests

Create a preload script file (e.g., happydom.ts) that imports and registers Happy DOM's global registrator: `import { GlobalRegistrator } from "@happy-dom/global-registrator"; GlobalRegistrator.register();`

Testing Library setup with Bun test runner

To use Testing Library with Bun's test runner, install Happy DOM via `bun add -D @happy-dom/global-registrator`, then install the Testing Library packages for your framework. For React, run `bun add -D @testing-library/react @testing-library/dom @testing-library/jest-dom`.

Testing Library preload script with expect matchers

Create a preload script file (e.g., testing-library.ts) that extends Bun's expect function with Testing Library matchers: `import { afterEach, expect } from "bun:test"; import { cleanup } from "@testing-library/react"; import * as matchers from "@testing-library/jest-dom/matchers"; expect.extend(matchers); afterEach(() => { cleanup(); });`

Bun test preload configuration in bunfig.toml

Add preload scripts to bunfig.toml under the [test] section. Specify multiple preload files as an array: `[test]` `preload = ["./happydom.ts", "./testing-library.ts"]`

TypeScript type declaration merging for Testing Library matchers

To make Testing Library matcher types available in TypeScript, create a declaration file (e.g., matchers.d.ts) that extends the Matchers interface: `import { TestingLibraryMatchers } from "@testing-library/jest-dom/matchers"; import { Matchers, AsymmetricMatchers } from "bun:test"; declare module "bun:test" { interface Matchers<T> extends TestingLibraryMatchers<typeof expect.stringContaining, T> {} interface AsymmetricMatchers extends TestingLibraryMatchers {} }`

Give your agent this brain