### Global Test Setup with preload Script Source: https://github.com/oven-sh/bun/blob/main/docs/test/configuration.mdx Example `test-setup.ts` script demonstrating global `beforeAll` and `afterAll` hooks for test database management. ```ts // Global test setup import { beforeAll, afterAll } from "bun:test"; beforeAll(() => { // Set up test database setupTestDatabase(); }); afterAll(() => { // Clean up cleanupTestDatabase(); }); ``` -------------------------------- ### Setup commands Source: https://github.com/oven-sh/bun/blob/main/packages/bun-lambda/README.md Commands to clone the repository, set up sparse checkout, install dependencies, and publish the layer. ```sh git clone --filter=blob:none --sparse https://github.com/oven-sh/bun.git git -C bun sparse-checkout set packages/bun-lambda cd bun/packages/bun-lambda bun install bun run publish-layer ``` -------------------------------- ### Render Build and Start Commands for Bun Source: https://github.com/oven-sh/bun/blob/main/docs/guides/deployment/render.mdx Specifies the build and start commands for a Bun application deployed on Render. `bun install` installs dependencies, and `bun app.ts` starts the application. ```sh bun install ``` ```sh bun app.ts ``` -------------------------------- ### Install SolidStart Project Dependencies Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/solidstart.mdx Navigate into the newly created project directory and install its dependencies using `bun install`. ```sh cd my-app bun install ``` -------------------------------- ### Manual CI Setup - Install packages Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/secrets-ci-setup.md Commands to manually install required packages and then run the tests. ```bash apt-get update && apt-get install -y libsecret-1-dev gnome-keyring dbus-x11 bun test test/js/bun/secrets.test.ts ``` -------------------------------- ### Benchmark setup commands Source: https://github.com/oven-sh/bun/blob/main/bench/test/README.md Commands to navigate to the benchmark directory and install dependencies for Vitest, then set up the test suites. ```sh cd bench/test bun install # for vitest bun parallel/setup.ts bun isolate-cache/setup.ts ``` -------------------------------- ### Install All Project Dependencies Source: https://github.com/oven-sh/bun/blob/main/docs/pm/cli/install.mdx Run `bun install` without arguments to install all dependencies defined in the project's `package.json`. ```bash bun install ``` -------------------------------- ### Initialize a Remix Project with Bun Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/remix.mdx Use `bun create remix` to scaffold a new Remix application, handling project setup and dependency installation. The output shows the interactive prompts and successful initialization. ```sh bun create remix ``` ```txt remix v1.19.3 ๐Ÿ’ฟ Let's build a better website... dir Where should we create your new project? ./my-app โ—ผ Using basic template See https://remix.run/docs/en/main/guides/templates#templates for more โœ” Template copied git Initialize a new git repository? Yes deps Install dependencies with bun? Yes โœ” Dependencies installed โœ” Git initialized done That's it! Enter your project directory using cd ./my-app Check out README.md for development and deploy instructions. ``` -------------------------------- ### Start the TanStack Start dev server with Bun Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/tanstack-start.mdx Navigate to the project directory and start the Vite development server using Bun. ```sh cd my-tanstack-app bun --bun run dev ``` -------------------------------- ### Install Bun (Native) Source: https://github.com/oven-sh/bun/blob/main/CONTRIBUTING.md Install a release build of Bun using the native installer script. ```bash $ curl -fsSL https://bun.com/install | bash ``` -------------------------------- ### Install Bun using the install script Source: https://github.com/oven-sh/bun/blob/main/README.md This is the recommended method for installing Bun on Linux and macOS systems. ```sh # with install script (recommended) curl -fsSL https://bun.com/install | bash ``` -------------------------------- ### Putting it all together Source: https://github.com/oven-sh/bun/blob/main/packages/bun-uws/misc/READMORE.md A complete example demonstrating route definition, listening on a port, and running the event loop with `App.run`. ```c++ int main() { uWS::App().get("/*", [](auto *res, auto *req) { res->end("Hello World!"); }).listen(9001, [](auto *listenSocket) { if (listenSocket) { std::cout << "Listening for connections..." << std::endl; } }).run(); std::cout << "Shoot! We failed to listen and the App fell through, exiting now!" << std::endl; } ``` -------------------------------- ### GitHub Actions (Explicit Package Installation) Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/secrets-ci-setup.md Example of running Bun secrets tests in GitHub Actions with explicit installation of keyring packages. ```yaml - name: Install keyring packages run: | sudo apt-get update sudo apt-get install -y libsecret-1-dev gnome-keyring dbus-x11 - name: Run secrets tests run: bun test test/js/bun/secrets.test.ts ``` -------------------------------- ### Navigate to project and install dependencies Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/hono.mdx Change into the newly created project directory and install its dependencies using Bun. ```sh cd myapp bun install ``` -------------------------------- ### Required Packages Installation Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/secrets-ci-setup.md Command to install necessary packages on Ubuntu/Debian systems. ```bash apt-get install -y \ libsecret-1-dev \ gnome-keyring \ dbus-x11 ``` -------------------------------- ### Initialize a new Bun project Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/prisma-postgres.mdx Use `mkdir` and `bun init` to set up a new project directory. ```bash mkdir prisma-postgres-app cd prisma-postgres-app bun init ``` -------------------------------- ### GitHub Actions (Auto-Setup) Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/secrets-ci-setup.md Example of running Bun secrets tests in GitHub Actions with automatic setup. ```yaml - name: Run secrets tests (auto-setup) run: bun test test/js/bun/secrets.test.ts ``` -------------------------------- ### Initialize Bun Project and Install Neon Serverless Driver Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/neon-serverless-postgres.mdx Use these commands to create a new project directory, initialize it with Bun, and add the Neon serverless driver as a dependency. ```sh mkdir bun-neon-postgres cd bun-neon-postgres bun init -y bun add @neondatabase/serverless ``` -------------------------------- ### BuildKite Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/secrets-ci-setup.md Example of running Bun secrets tests in BuildKite. ```yaml steps: - command: bun test test/js/bun/secrets.test.ts label: "๐Ÿ” Secrets API Tests" ``` -------------------------------- ### Install Source: https://github.com/oven-sh/bun/blob/main/test/js/node/test/fixtures/postject-copy/node_modules/postject/README.markdown Command to install postject globally. ```sh npm i -g postject ``` -------------------------------- ### Docker Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/secrets-ci-setup.md Example of a Dockerfile for running Bun secrets tests, including optional pre-installation of packages. ```dockerfile # Optional: pre-install packages for faster test startup RUN apt-get update && apt-get install -y \ libsecret-1-dev \ gnome-keyring \ dbus-x11 # Run test normally - setup is automatic RUN bun test test/js/bun/secrets.test.ts ``` -------------------------------- ### Set credential with unrestricted access for CI Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/secrets-ci-setup.md Example of using allowUnrestrictedAccess: true for Bun.secrets.set in CI environments on macOS. ```ts // For CI environments where user interaction is not possible await Bun.secrets.set({ service: "ci-deployment", name: "api-key", value: process.env.API_KEY, allowUnrestrictedAccess: true // Bypass macOS keychain user prompts }); ``` -------------------------------- ### Local Template `package.json` with Setup Scripts Source: https://github.com/oven-sh/bun/blob/main/docs/runtime/templating/create.mdx Define `preinstall` and `postinstall` scripts within the `bun-create` section of a local template's `package.json` to automate setup tasks. ```json { "name": "@bun-examples/simplereact", "version": "0.0.1", "main": "index.js", "dependencies": { "react": "^17.0.2", "react-dom": "^17.0.2" }, "bun-create": { "preinstall": "echo 'Installing...'", // a single command "postinstall": ["echo 'Done!'"], // an array of commands "start": "bun run echo 'Hello world!'" } } ``` -------------------------------- ### Delete credential with empty string Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/secrets-ci-setup.md Examples showing how to delete a credential using Bun.secrets.delete or by setting an empty string with Bun.secrets.set. ```ts // These are equivalent: await Bun.secrets.delete({ service: "myapp", name: "token" }); await Bun.secrets.set({ service: "myapp", name: "token", value: "" }); ``` -------------------------------- ### Qwik App Initialization Output with Bun Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/qwik.mdx This output shows the interactive prompts and successful creation of a new Qwik project using `bun create qwik`, including dependency installation with Bun. ```txt ............ .::: :--------:. .:::: .:-------:. .:::::. .:-------. ::::::. .:------. ::::::. :-----: ::::::. .:-----. :::::::. .-----. ::::::::.. ---:. .:::::::::. :-:. ..:::::::::::: ...:::: โ”Œ Let's create a Qwik App โœจ (v1.2.10) โ”‚ โ—‡ Where would you like to create your new project? (Use '.' or './' for current directory) โ”‚ ./my-app โ”‚ โ— Creating new project in /path/to/my-app ... ๐Ÿ‡ โ”‚ โ—‡ Select a starter โ”‚ Basic App โ”‚ โ—‡ Would you like to install bun dependencies? โ”‚ Yes โ”‚ โ—‡ Initialize a new git repository? โ”‚ No โ”‚ โ—‡ Finishing the install. Wanna hear a joke? โ”‚ Yes โ”‚ โ—‹ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚ โ”‚ How do you know if thereโ€™s an elephant under your bed? โ”‚ โ”‚ Your head hits the ceiling! โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ โ—‡ App Created ๐Ÿฐ โ”‚ โ—‡ Installed bun dependencies ๐Ÿ“‹ โ”‚ โ—‹ Result โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚ โ”‚ Success! Project created in my-app directory โ”‚ โ”‚ โ”‚ โ”‚ Integrations? Add Netlify, Cloudflare, Tailwind... โ”‚ โ”‚ bun qwik add โ”‚ โ”‚ โ”‚ Relevant docs: โ”‚ https://qwik.dev/docs/getting-started/ โ”‚ โ”‚ Questions? Start the conversation at: โ”‚ https://qwik.dev/chat โ”‚ https://twitter.com/QwikDev โ”‚ โ”‚ Presentations, Podcasts and Videos: โ”‚ https://qwik.dev/media/ โ”‚ โ”‚ Next steps: โ”‚ cd my-app โ”‚ bun start โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ โ”” Happy coding! ๐ŸŽ‰ ``` -------------------------------- ### Run Bun with an HTML Entry Point Source: https://github.com/oven-sh/bun/blob/main/docs/bundler/html-static.mdx Use the `bun` command to start the development server, pointing it directly to an HTML file for automatic bundling and serving. ```bash bun ./index.html ``` -------------------------------- ### Run Downloaded Release Build Source: https://github.com/oven-sh/bun/blob/main/CONTRIBUTING.md Example of running a specific release build downloaded via `bun-pr`. ```sh bun-1234566 --version ``` -------------------------------- ### Force Keyring Setup Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/secrets-ci-setup.md Command to force the automatic keyring setup using an environment variable. ```bash FORCE_KEYRING_SETUP=1 bun test test/js/bun/secrets.test.ts ``` -------------------------------- ### Automatic CI Setup Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/secrets-ci-setup.md Command to run the secrets test, which automatically handles setup in CI environments. ```bash bun test test/js/bun/secrets.test.ts ``` -------------------------------- ### Initialize Project with All Defaults Source: https://github.com/oven-sh/bun/blob/main/docs/snippets/cli/init.mdx Use this command to initialize a new project, automatically accepting all default prompts without requiring user interaction. ```bash bun init -y ``` -------------------------------- ### Initialize a new NAPI-RS project Source: https://github.com/oven-sh/bun/blob/main/docs/bundler/plugins.mdx Use the NAPI-RS CLI to scaffold a new native addon project for Bun. ```bash bun add -g @napi-rs/cli napi new ``` -------------------------------- ### Add Nitro to your TanStack Start project Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/tanstack-start.mdx Install Nitro as a dependency to enable deployment of your TanStack Start app to various platforms. ```sh bun add nitro ``` -------------------------------- ### Initialize Bun Project and Install StricJS Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/stric.mdx Use these commands to set up a new Bun project and add the necessary StricJS router and utility packages. ```bash mkdir myapp cd myapp bun init bun add @stricjs/router @stricjs/utils ``` -------------------------------- ### Ordered list start number beginning with zero Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/md/spec.txt Example of an ordered list with a start number beginning with 0. ```markdown 0. ok ``` -------------------------------- ### Install LLVM 21 on Ubuntu/Debian Source: https://github.com/oven-sh/bun/blob/main/docs/project/contributing.mdx Run the official LLVM installation script to get LLVM 21 on Ubuntu or Debian systems. ```bash wget https://apt.llvm.org/llvm.sh -O - | sudo bash -s -- 21 all ``` -------------------------------- ### Set Up Local Template Directory Source: https://github.com/oven-sh/bun/blob/main/docs/runtime/templating/create.mdx Navigate to the global Bun create templates directory and create a new template folder. ```bash cd $HOME/.bun-create mkdir foo cd foo ``` -------------------------------- ### Ordered list start number with leading zeros Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/md/spec.txt Example of an ordered list with a start number containing leading zeros. ```markdown 003. ok ``` -------------------------------- ### Basic HTTP Server Setup with Bun.serve Source: https://github.com/oven-sh/bun/blob/main/docs/runtime/http/server.mdx This snippet demonstrates how to configure a basic HTTP server using `Bun.serve`, including defining various route types like static, dynamic with parameters, method-specific handlers, wildcard routes, redirects, and serving files. It also shows how to set a fallback for unmatched routes. ```ts const server = Bun.serve({ // `routes` requires Bun v1.2.3+ routes: { // Static routes "/api/status": new Response("OK"), // Dynamic routes "/users/:id": req => { return new Response(`Hello User ${req.params.id}!`); }, // Per-HTTP method handlers "/api/posts": { GET: () => new Response("List posts"), POST: async req => { const body = await req.json(); return Response.json({ created: true, ...body }); } }, // Wildcard route for all routes that start with "/api/" and aren't otherwise matched "/api/*": Response.json({ message: "Not found" }, { status: 404 }), // Redirect from /blog/hello to /blog/hello/world "/blog/hello": Response.redirect("/blog/hello/world"), // Serve a file by lazily loading it into memory "/favicon.ico": Bun.file("./favicon.ico") }, // (optional) fallback for unmatched routes: // Required if Bun's version < 1.2.3 fetch(req) { return new Response("Not Found", { status: 404 }); } }); console.log(`Server running at ${server.url}`); ``` -------------------------------- ### Valid ordered list start number Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/md/spec.txt Example of an ordered list with a valid start number (nine digits or less). ```markdown 123456789. ok ``` -------------------------------- ### Invalid ordered list start number (negative) Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/md/spec.txt Example of an ordered list with an invalid negative start number, which is not parsed as a list. ```markdown -1. not ok ``` -------------------------------- ### Start SvelteKit Development Server with Bun Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/sveltekit.mdx Navigate into the project directory and start the SvelteKit development server using Bun as the runtime. ```sh cd my-app bun --bun run dev ``` -------------------------------- ### Defining a GET route Source: https://github.com/oven-sh/bun/blob/main/packages/bun-uws/misc/READMORE.md Example of attaching behavior to a URL route using the `get` method with `uWS::App`. ```c++ uWS::App().get("/hello", [](auto *res, auto *req) { res->end("Hello World!"); }); ``` -------------------------------- ### Install Bun and run commands in GitHub Actions Source: https://github.com/oven-sh/bun/blob/main/docs/guides/runtime/cicd.mdx This workflow demonstrates how to use `oven-sh/setup-bun@v2` to install Bun and then execute various Bun commands like `bun install`, `bun index.ts`, and `bun run build`. ```yaml name: my-workflow jobs: my-job: name: my-job runs-on: ubuntu-latest steps: # ... - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 # [!code ++] # run any `bun` or `bunx` command - run: bun install # [!code ++] - run: bun index.ts # [!code ++] - run: bun run build # [!code ++] ``` -------------------------------- ### Run Mintlify Development Server Source: https://github.com/oven-sh/bun/blob/main/docs/README.md Execute this command to start the local development server for the documentation, which will be served at http://localhost:3000. ```bash mint dev ``` -------------------------------- ### Invalid ordered list start number (too many digits) Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/md/spec.txt Example of an ordered list with an invalid start number (more than nine digits), which is not parsed as a list. ```markdown 1234567890. not ok ``` -------------------------------- ### Bun PM Pkg Management Examples Source: https://github.com/oven-sh/bun/blob/main/docs/pm/cli/pm.mdx Comprehensive examples for `bun pm pkg` commands, covering `get`, `set`, `delete`, and `fix` operations on `package.json` properties. ```bash # get bun pm pkg get name # single property bun pm pkg get name version # multiple properties bun pm pkg get # entire package.json bun pm pkg get scripts.build # nested property # set bun pm pkg set name="my-package" # simple property bun pm pkg set scripts.test="jest" version=2.0.0 # multiple properties bun pm pkg set private=true --json # JSON values with --json flag # delete bun pm pkg delete description # single property bun pm pkg delete scripts.test contributors[0] # multiple/nested # fix bun pm pkg fix # auto-fix common issues ``` -------------------------------- ### Initialize React Projects with Templates Source: https://github.com/oven-sh/bun/blob/main/docs/snippets/cli/init.mdx These commands demonstrate how to scaffold a React project, including options for a baseline app, preconfigured Tailwind CSS, or Shadcn UI. ```bash bun init --react ``` ```bash bun init --react=tailwind ``` ```bash bun init --react=shadcn ``` -------------------------------- ### Windows library attribution example Source: https://github.com/oven-sh/bun/blob/main/scripts/verify-baseline-static/CLAUDE.md Example showing how to allowlist symbols attributed to a specific Windows library when PDB records are unavailable. ```text [AVX, AVX2] ``` -------------------------------- ### Complete Bun.build() Example for Executable Compilation Source: https://github.com/oven-sh/bun/blob/main/docs/bundler/executables.mdx This example demonstrates a full `Bun.build()` configuration for compiling a standalone executable, including plugin usage, target specification, output path, and other build options. ```ts import type { BunPlugin } from "bun"; const myPlugin: BunPlugin = { name: "my-plugin", setup(build) { // Plugin implementation }, }; const result = await Bun.build({ entrypoints: ["./src/cli.ts"], compile: { target: "bun-linux-x64", outfile: "./dist/mycli", execArgv: ["--smol"], autoloadDotenv: false, autoloadBunfig: false, }, minify: true, sourcemap: "linked", bytecode: true, define: { "process.env.NODE_ENV": JSON.stringify("production"), VERSION: JSON.stringify("1.0.0"), }, plugins: [myPlugin], }); if (result.success) { console.log("Build successful:", result.outputs[0].path); } ``` -------------------------------- ### Install Bun and dependencies in GitHub Actions Source: https://github.com/oven-sh/bun/blob/main/docs/guides/install/cicd.mdx Use the `setup-bun` action to install Bun and then run `bun install` to manage project dependencies within a GitHub Actions workflow. ```yaml title: my-workflow jobs: my-job: title: my-job runs-on: ubuntu-latest steps: # ... - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 # run any `bun` or `bunx` command - run: bun install ``` -------------------------------- ### Rust v0 mangling example Source: https://github.com/oven-sh/bun/blob/main/scripts/verify-baseline-static/CLAUDE.md Example showing how the tool reports a Rust symbol and how to allowlist it using the canonicalized placeholder. ```text # Tool reports: _RNvMNtNtNtNtCs5QMN7YRSXc3_6memchr4arch6x86_644avx26memchrNtB2_3One13find_raw_avx2 [AVX, AVX2] # Allowlist as: _RNvMNtNtNtNt6memchr4arch6x86_644avx26memchrNtB2_3One13find_raw_avx2 [AVX, AVX2] ``` -------------------------------- ### Text Entrypoint Input Example Source: https://github.com/oven-sh/bun/blob/main/docs/runtime/file-types.mdx Example of a `.txt` file content when used as an entrypoint. ```txt Hello, world! ``` -------------------------------- ### Verification Output Example Source: https://github.com/oven-sh/bun/blob/main/scripts/verify-baseline-static/CLAUDE.md An example of the output generated by the baseline static verification tool, showing violations, allowlisted symbols, and stale entries. ```text VIOLATIONS (would SIGILL on Nehalem): _ZN7simdutf7haswell14implementation17some_new_functionEPKcm [AVX, AVX2] (42 insns) 0x0000a1b2c3 Vpbroadcastb (AVX2) 0x0000a1b2d7 Vpshufb (AVX) 0x0000a1b2ee Vpcmpeqb (AVX) ... 39 more ALLOWLISTED (suppressed, runtime-dispatched): ... -- 550 symbols, 18234 instructions total STALE ALLOWLIST ENTRIES (no matching symbol found _ZN7simdutf7haswell14implementation13old_gone_funcEPKcm SUMMARY: violations: 1 symbols, 42 instructions allowlisted: 550 symbols stale allowlist entries: 1 FAIL ``` -------------------------------- ### Define an HTTP route and start an Elysia server Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/elysia.mdx This snippet demonstrates how to import Elysia, define a GET route for the root path, and start the server on port 8080, logging the server's port. ```ts import { Elysia } from "elysia"; const app = new Elysia().get("/", () => "Hello Elysia").listen(8080); console.log(`๐ŸฆŠ Elysia is running at on port ${app.server?.port}...`); ``` -------------------------------- ### Vite project creation output Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/vite.mdx Example output after running `bun create vite my-app` and selecting options. ```txt โœ” Select a framework: โ€บ React โœ” Select a variant: โ€บ TypeScript + SWC Scaffolding project in /path/to/my-app... ``` -------------------------------- ### Initialize a new Bun project Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/prisma.mdx Use `bun init` to create a new project directory and initialize it. ```bash mkdir prisma-app cd prisma-app bun init ``` -------------------------------- ### JSON5 Entrypoint Input Example Source: https://github.com/oven-sh/bun/blob/main/docs/runtime/file-types.mdx Example of a `.json5` file content when used as an entrypoint. ```json5 { // Configuration name: "John Doe", age: 35, email: "johndoe@example.com", } ``` -------------------------------- ### Script Profiling Source: https://github.com/oven-sh/bun/blob/main/packages/bun-inspector-protocol/README.md Example demonstrating how to start and stop script profiling and handle profiling updates and completion. ```typescript // Start script profiling with sampling await inspector.send("ScriptProfiler.startTracking", { includeSamples: true }); // Listen for profiling updates inspector.on("ScriptProfiler.trackingUpdate", event => { console.log("Profiling event:", event); }); // Stop profiling to get complete data inspector.on("ScriptProfiler.trackingComplete", data => { if (data.samples) { // Process stack traces console.log(`Collected ${data.samples.stackTraces.length} stack traces`); } }); await inspector.send("ScriptProfiler.stopTracking"); ``` -------------------------------- ### Build-then-Exec Examples for Bun Source: https://github.com/oven-sh/bun/blob/main/CLAUDE.md Demonstrates various build-then-exec commands for Bun, including debug builds, release builds, and local WebKit builds, passing arguments directly to the built executable. ```sh bun bd test foo.test.ts ``` ```sh bun run build test foo.test.ts ``` ```sh bun run build:release -p 'Bun.version' ``` ```sh bun run build:local run script.ts ``` -------------------------------- ### Memory Profiling Source: https://github.com/oven-sh/bun/blob/main/packages/bun-inspector-protocol/README.md Example demonstrating how to start and stop heap tracking and listen for garbage collection events. ```typescript // Start heap tracking await inspector.send("Heap.enable"); await inspector.send("Heap.startTracking"); // Listen for GC events inspector.on("Heap.garbageCollected", ({ collection }) => { console.log( `GC completed: ${collection.type} (${collection.endTime - collection.startTime}ms)`, ); }); // ... perform operations to analyze ... // Get heap snapshot const { snapshotData } = await inspector.send("Heap.stopTracking"); // Process snapshotData to find memory leaks ``` -------------------------------- ### Initialize a new Bun project Source: https://github.com/oven-sh/bun/blob/main/docs/quickstart.mdx Use `bun init` to create a new project directory with a basic Bun app structure. Select the 'Blank' template for this guide. ```bash bun init my-app ``` ```bash bun init my-app ``` ```txt โœ“ Select a project template: Blank + .gitignore + CLAUDE.md + .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc -> CLAUDE.md + index.ts + tsconfig.json (for editor autocomplete) + README.md ``` -------------------------------- ### Benchmark against a local Bun H3 server Source: https://github.com/oven-sh/bun/blob/main/packages/h3blast/README.md Example of starting a Bun test server and then using h3blast to benchmark it. ```sh bun test-server.js 3443 & ./h3blast -t 2 -c 4 -m 32 -d 10 https://127.0.0.1:3443/ ``` -------------------------------- ### Create a new TanStack Start app with Bun Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/tanstack-start.mdx Use the interactive CLI to initialize a new TanStack Start project. ```sh bunx @tanstack/cli create my-tanstack-app ``` -------------------------------- ### Complete bunfig.toml Configuration Example for Bun Test Source: https://github.com/oven-sh/bun/blob/main/docs/test/configuration.mdx This example demonstrates a comprehensive 'bunfig.toml' for 'bun test', covering install settings, test discovery, execution, coverage, and reporter configurations. Use this to customize various aspects of your test runner. ```toml [install] # Install settings inherited by tests registry = "https://registry.npmjs.org/" exact = true [test] # Test discovery root = "src" preload = ["./test-setup.ts", "./global-mocks.ts"] pathIgnorePatterns = ["vendor/**", "submodules/**"] # Execution settings smol = true # Coverage configuration coverage = true coverageReporter = ["text", "lcov"] coverageDir = "./coverage" coverageThreshold = { lines = 0.85, functions = 0.90, statements = 0.80 } coverageSkipTestFiles = true coveragePathIgnorePatterns = [ "**/*.spec.ts", "src/utils/**", "*.config.js", "generated/**" ] # Advanced coverage settings coverageIgnoreSourcemaps = false # Reporter configuration [test.reporter] junit = "./reports/junit.xml" ``` -------------------------------- ### Create Project using `create-remix` from npm Source: https://github.com/oven-sh/bun/blob/main/docs/runtime/templating/create.mdx Demonstrates equivalent commands for creating a Remix project using `bun create` or `bunx`. ```sh bun create remix ``` ```sh bunx create-remix ``` -------------------------------- ### WWW Autolink Example Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/md/spec-permissive-autolinks.txt Demonstrates a permissive WWW autolink, which starts with 'www.' and is implicitly converted to an HTTP URL. ```markdown www.google.com/search?q=Markdown ``` ```html

www.google.com/search?q=Markdown

``` -------------------------------- ### Build with Bun's CLI Source: https://github.com/oven-sh/bun/blob/main/docs/bundler/index.mdx Bundle your application using the `bun build` command, providing the entrypoint and output directory as arguments. ```bash bun build ./index.tsx --outdir ./build ``` -------------------------------- ### Listening on a port Source: https://github.com/oven-sh/bun/blob/main/packages/bun-uws/misc/READMORE.md Example of how to start listening for new connections on a specified port using `App.listen`. ```c++ App.listen(port, [](auto *listenSocket) { /* listenSocket is either nullptr or us_listen_socket */ }) ``` -------------------------------- ### Example pnpm-workspace.yaml for Migration Source: https://github.com/oven-sh/bun/blob/main/docs/pm/cli/install.mdx This 'pnpm-workspace.yaml' defines workspace packages and catalog dependencies. Bun migrates these settings to the root 'package.json' during installation. ```yaml packages: - "apps/*" - "packages/*" catalog: react: ^18.0.0 typescript: ^5.0.0 catalogs: build: webpack: ^5.0.0 babel: ^7.0.0 ``` -------------------------------- ### Initialize a Hono project using create-hono Source: https://github.com/oven-sh/bun/blob/main/docs/guides/ecosystem/hono.mdx Use the `create-hono` CLI tool to scaffold a new Hono project, selecting Bun as the template. ```sh bun create hono myapp ``` -------------------------------- ### CSRF Protection Example with Bun.serve() Source: https://github.com/oven-sh/bun/blob/main/docs/runtime/csrf.mdx This example shows a complete `Bun.serve()` setup for CSRF protection. It generates a unique token for each session when rendering a form and verifies the token upon form submission, using a session ID to bind the token to the user. ```ts const SECRET = process.env.CSRF_SECRET || "my-secret"; // Resolve the requester's session identifier from a session cookie. Returns // null when the visitor has no session yet โ€” never fall back to a shared // placeholder, or every session-less visitor would share one token binding. function getSessionId(req: Request): string | null { return req.headers.get("cookie")?.match(/(?:^|;\s*)session=([^;]+)/)?.[1] ?? null; } const server = Bun.serve({ routes: { "/form": req => { // Create a per-visitor session before issuing the form so the token is // bound to this visitor and no one else. let sessionId = getSessionId(req); const headers = new Headers({ "Content-Type": "text/html" }); if (!sessionId) { sessionId = crypto.randomUUID(); headers.append("Set-Cookie", `session=${sessionId}; HttpOnly; SameSite=Lax; Path=/`); } const token = Bun.CSRF.generate(SECRET, { sessionId }); return new Response( `
`, { headers }, ); }, "/submit": { POST: async req => { const sessionId = getSessionId(req); const formData = await req.formData(); const csrfToken = formData.get("_csrf"); if (!sessionId || typeof csrfToken !== "string" || !Bun.CSRF.verify(csrfToken, { secret: SECRET, sessionId })) { return new Response("Invalid CSRF token", { status: 403 }); } return new Response("OK"); }, }, }, }); console.log(`Listening on ${server.url}`); ``` -------------------------------- ### Example usage of onGC Source: https://github.com/oven-sh/bun/blob/main/test/napi/node-napi-tests/test/common/README.md Demonstrates how to install a garbage collection listener using the onGC function. ```js require('../common'); const { onGC } = require('../common/gc'); onGC({}, { ongc() { console.log('collected'); } }); ``` -------------------------------- ### Run in Deno (`Deno.serve`) Source: https://github.com/oven-sh/bun/blob/main/bench/websocket-server/README.md Command to start the websocket server using Deno. ```bash deno run -A ./chat-server.deno.mjs ``` -------------------------------- ### Basic HTML block of type 6 Source: https://github.com/oven-sh/bun/blob/main/test/js/bun/md/spec.txt A simple example of an HTML block starting with (type 6) and its parsed output. ```markdown+html
hi
okay. ``` ```markdown+html
hi

okay.

``` -------------------------------- ### Create Project from GitHub Repository Source: https://github.com/oven-sh/bun/blob/main/docs/runtime/templating/create.mdx Initialize a project by cloning a GitHub repository using `bun create` with either shorthand or full URL. ```bash bun create / ``` ```bash bun create github.com// ``` -------------------------------- ### Quick Start: Configure Security Scanner in bunfig.toml Source: https://github.com/oven-sh/bun/blob/main/docs/pm/security-scanner-api.mdx Configures Bun's package manager to use a specified security scanner as part of a quick setup. ```toml [install.security] scanner = "@oven/bun-security-scanner" # example name, replace with your scanner's package ``` -------------------------------- ### Install xwin and set up Windows sysroot Source: https://github.com/oven-sh/bun/blob/main/docs/project/building-windows.mdx Install `xwin` to download the MSVC CRT, Windows SDK, and ATL. This command sets up the necessary Windows sysroot at `/opt/winsysroot` and creates required symbolic links for `clang-cl`/`lld-link`. ```bash cargo install xwin # or download a release binary xwin --accept-license --arch x86_64,aarch64 --sdk-version 10.0.26100 --crt-version 14.44.17.14 --include-atl splat \ --use-winsysroot-style --preserve-ms-arch-notation --include-debug-libs \ --output /opt/winsysroot # clang-cl/lld-link look up SDK paths as "Include"/"Lib"; the splat writes # them lowercase, so alias both spellings (needs the same privileges as the # splat โ€” configure creates these itself when the directory is writable). ln -s include "/opt/winsysroot/Windows Kits/10/Include" ln -s lib "/opt/winsysroot/Windows Kits/10/Lib" ```