### pnpm Install Command Source: https://bun.com/blog/bun-lock-text-lockfile Illustrates the command used to run pnpm install, included in benchmarks to compare its performance against Bun's install commands. ```bash # --warmup=10 cd with-pnpm && pnpm install ``` ```bash # --warmup=2 --prepare="rm -rf ./with-{text,binary,pnpm,yarn,npm}/node_modules" cd with-pnpm && pnpm install --ignore-scripts ``` -------------------------------- ### npm Install Command Source: https://bun.com/blog/bun-lock-text-lockfile Shows the command for running npm install, included in performance benchmarks for comparison with Bun's install speed. ```bash # --warmup=10 cd with-npm && npm install ``` ```bash # --warmup=2 --prepare="rm -rf ./with-{text,binary,pnpm,yarn,npm}/node_modules" cd with-npm && npm install --ignore-scripts ``` -------------------------------- ### Bun Install with Binary Lockfile Source: https://bun.com/blog/bun-lock-text-lockfile Shows the command for running Bun install with a binary lockfile, used as a baseline for performance comparisons against the text lockfile. ```bash # --warmup=10 bun-1.1.38 install --cwd=./with-binary # Binary lockfile ``` ```bash # --warmup=2 --prepare="rm -rf ./with-{text,binary,pnpm,yarn,npm}/node_modules" bun-1.1.38 install --cwd=./with-binary --ignore-scripts # Binary lockfile ``` -------------------------------- ### yarn Install Command Source: https://bun.com/blog/bun-lock-text-lockfile Presents the command for executing yarn install, used in performance benchmarks to compare with Bun's installation process. ```bash # --warmup=10 cd with-yarn && yarn install ``` ```bash # --warmup=2 --prepare="rm -rf ./with-{text,binary,pnpm,yarn,npm}/node_modules" cd with-yarn && yarn install --ignore-scripts ``` -------------------------------- ### Bun Install with Text Lockfile Source: https://bun.com/blog/bun-lock-text-lockfile Demonstrates the command to run Bun install using a text-based lockfile, as used in performance benchmarks. This command is typically used with specific warm-up and directory settings. ```bash # --warmup=10 bun install --cwd=./with-text # Text-based lockfile ``` ```bash # --warmup=2 --prepare="rm -rf ./with-{text,binary,pnpm,yarn,npm}/node_modules" bun install --cwd=./with-text --ignore-scripts # Text-based lockfile ``` -------------------------------- ### TypeScript Glob Matching Examples Source: https://bun.com/docs/api/glob Demonstrates how to use the 'glob.match' function in TypeScript to find files matching specific patterns. It shows examples of matching '???.ts' and 'foo.ts', returning true and false respectively. This functionality is useful for file system operations and build processes. ```typescript const glob = require("glob"); glob.match("???.ts"); // => true glob.match("foo.ts"); // => false ``` -------------------------------- ### C to JavaScript Integer Conversion Example Source: https://bun.com/blog/compile-and-run-c-in-js Illustrates the conversion of a C int32 to JavaScriptCore's EncodedJSValue representation. This function is a simplified example of the type conversions handled automatically by bun:ffi. ```c static int64_t int32_to_js(int32_t input) { return 0xfffe000000000000ll | (uint32_t)input; } ``` -------------------------------- ### Bun Glob Matching Examples Source: https://bun.com/docs/api/glob Illustrates basic glob matching functionality in Bun. It shows how to match files like 'index.ts' and 'foo.ts' and provides expected boolean outputs. ```typescript const glob = new Glob("*.ts"); for await (const file of glob.iterate({ ignore: "index.ts" })) { console.log(file); } // => "foo.ts" glob.match("index.ts"); // => false glob.match("foo.ts"); // => true ``` -------------------------------- ### Glob Pattern Matching Examples (TypeScript) Source: https://bun.com/docs/api/glob Demonstrates the usage of `glob.match` for pattern matching in TypeScript. It shows how to match files like 'index.ts' and 'index.js', returning boolean results. ```typescript glob.match("index.ts"); // => true glob.match("index.js"); // => false ``` -------------------------------- ### Match Character Sets with Ranges and Negation in Glob Patterns Source: https://bun.com/docs/api/glob This example demonstrates advanced character set matching using ranges and negation. It matches filenames starting with 'ba', followed by any lowercase letter, then a digit, then any character except '4' through '9', and ending with '.ts'. ```javascript const glob = new Glob("ba[a-z][0-9][^4-9].ts"); glob.match("bar01.ts"); // => true glob.match("baz83.ts"); // => true glob.match("bat22.ts"); // => true glob.match("bat24.ts"); // => false glob.match("ba0a8.ts"); // => false ``` -------------------------------- ### Match Files with Glob Patterns (TypeScript) Source: https://bun.com/docs/api/glob Demonstrates using the 'glob' library to match files based on provided patterns. It shows examples for matching '.ts' and '.js' files, returning true if a match is found. ```typescript glob.match("src/index.ts"); // => true glob.match("src/index.js"); // => false ``` -------------------------------- ### Glob Match Example: foobar.ts Source: https://bun.com/docs/api/glob Illustrates matching a file named 'foobar.ts' using the glob.match function. This example shows how the glob pattern can match files with different names as long as they adhere to the pattern. ```typescript const result2 = glob.match("foobar.ts"); // => false ``` -------------------------------- ### TypeScript Glob Match Example Source: https://bun.com/docs/api/glob Demonstrates how to use the 'glob.match' function in TypeScript to find files. It shows a basic usage for matching files in the 'src/index.ts' path and returns a boolean indicating success. ```typescript glob.match("src/index.ts"); // => true ``` -------------------------------- ### Using fs.glob() with Patterns in Bun Source: https://bun.com/docs/api/glob Demonstrates how to use the `glob()` function from the 'node:fs' module in Bun to match files based on provided patterns. This example shows an asynchronous usage pattern. ```typescript import { glob, globSync, promises } from "node:fs"; // Array of patterns const files = await glob("*.ts"); ``` -------------------------------- ### TypeScript Glob Match All TS Files Example Source: https://bun.com/docs/api/glob Illustrates using 'glob.match' with a pattern to find all TypeScript files within any subdirectory. This example uses the '**/*.ts' pattern to achieve this. ```typescript const glob = new Glob("**/*.ts"); glob.match(); ``` -------------------------------- ### Bun Build --define Flag with TypeScript (TypeScript) Source: https://bun.com/guides/runtime/define-constant Illustrates how to use statically-defined constants within TypeScript code. The example shows a conditional check based on a defined NODE_ENV variable, which Bun can optimize. ```typescript if (process.env.NODE_ENV === "production") { // Production-specific code } ``` -------------------------------- ### Run Bun Server with Debugging Enabled Source: https://bun.com/guides/runtime/web-debugger This command starts a Bun server with the --inspect flag, which enables the Web Inspector Protocol. This flag automatically starts a WebSocket server for debugging tools to connect to. The output shows the WebSocket URL and a link to the browser-based debugger. ```shell bun --inspect server.ts ``` -------------------------------- ### Match Glob Patterns in TypeScript Source: https://bun.com/docs/api/glob Provides TypeScript examples for using the Glob library to match file patterns. It shows how to define a glob pattern and then use the `match` method to test against specific file names, returning boolean results. ```typescript const glob = new Glob("\\\"\\\\\\\\\"!index.ts\""); glob.match("!index.ts"); // => true glob.match("index.ts"); // => false ``` -------------------------------- ### TypeScript Glob File Matching Example Source: https://bun.com/docs/api/glob This TypeScript code demonstrates how to use the 'glob' library to find files matching a specific pattern. It initializes a glob object with a pattern and then uses the 'match' method to check if given file paths satisfy the pattern. ```typescript const glob = new Glob("ba[rz].ts"); glob.match("bar.ts"); // => true glob.match("baz.ts"); // => true ``` -------------------------------- ### Basic File Globbing with Bun Source: https://bun.com/docs/api/glob Shows a basic example of using `fs.glob()` to find files. This function is asynchronous and returns a Promise that resolves to an array of file paths matching the provided pattern. It supports glob patterns and an exclude option. ```javascript const fs = require('fs'); async function getFiles() { const files = await fs.glob('*.js'); console.log(files); } ``` -------------------------------- ### N-API addon optional dependencies in package.json Source: https://bun.com/blog/compile-and-run-c-in-js This JSON snippet shows the 'optionalDependencies' section of a package.json file for an N-API addon. It lists pre-built binaries for various operating system and architecture combinations to simplify installation for users. ```json { "optionalDependencies": { "@napi-rs/canvas-win32-x64-msvc": "0.1.55", "@napi-rs/canvas-darwin-x64": "0.1.55", "@napi-rs/canvas-linux-x64-gnu": "0.1.55", "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.55", "@napi-rs/canvas-linux-x64-musl": "0.1.55", "@napi-rs/canvas-linux-arm64-gnu": "0.1.55", "@napi-rs/canvas-linux-arm64-musl": "0.1.55", "@napi-rs/canvas-darwin-arm64": "0.1.55", "@napi-rs/canvas-android-arm64": "0.1.55" } } ``` -------------------------------- ### Implement fs.glob() with Bun Source: https://bun.com/docs/api/glob Demonstrates how to import and use the fs.glob() function from Node.js's built-in 'node:fs' module in Bun. This example shows asynchronous globbing with include and exclude patterns. ```typescript import { glob, globSync, promises } from "node:fs"; // Array of patterns const files = await promises.glob( ["**/*.ts", "**/\*.js"], // Exclude patterns { ignore: ["**/node_modules/**", "**/*.d.ts"] } ); ``` -------------------------------- ### Install Happy DOM Global Registrator Source: https://bun.com/guides/test/happy-dom Installs the Happy DOM global registrator package as a development dependency. This package is used to inject mocked browser APIs into the global scope for testing purposes. ```bash bun add -d @happy-dom/global-registrator ``` -------------------------------- ### Replace console.write with console.log using --define Source: https://bun.com/guides/runtime/define-constant This example demonstrates how to use the `bun --define` flag to replace all occurrences of `console.write` with `console.log` in a TypeScript file. This is useful for build-time configuration and optimization. The flag takes the form of `flag=replacement`. ```bash bun --define console.write=console.log src/index.ts ``` -------------------------------- ### TypeScript Test Setup with Bun Source: https://bun.com/guides/test/happy-dom This snippet shows how to import testing utilities from 'bun:test' and define a test case. It manipulates the DOM by setting innerHTML and then queries for an element, demonstrating a common pattern for testing UI components or interactions. ```typescript import { test, expect } from "bun:test"; test("set button text", () => { document.body.innerHTML = ``; const button = document.querySelector("button"); expect(button.textContent).toBe("My button"); }); ``` -------------------------------- ### Replace Value with JSON in Bun Source: https://bun.com/guides/runtime/define-constant This example shows how to use the 'bun --define' flag to replace a placeholder with a JSON object. This is particularly useful for injecting configuration data or complex values into your application at build time. The JSON string needs to be properly escaped. ```shellscript bun --define AWS='{"ACCESS_KEY":"abc","SECRET_KEY":"def"}' ``` -------------------------------- ### uWebSocket.js Package Definition Source: https://bun.com/blog/bun-lock-text-lockfile Defines the `uWebSocket.js` package, specifying its installation source from GitHub and providing an alias. This is part of the package management configuration. ```json { "packages": { "uWebSocket.js": ["uWebSockets.js@github:uNetworking/uWebSockets.js#6609a88", {}, "uNetworking-uWebSockets.js-6609a88"] } } ``` -------------------------------- ### Fast WebSocket Connection Setup in Bun Source: https://bun.com/discord Implements a fast WebSocket connection for the Bun application, optimizing for speed and efficiency. It checks for existing tokens and determines the appropriate encoding (ETF or JSON) based on the environment, then establishes a WebSocket connection to the Discord gateway. ```javascript !function(){if(null!=window.WebSocket){var n=function(n){try{var o=localStorage.getItem(n);if(null==o)return null;return JSON.parse(o)}catch(e){return null}};if(n("token")&&!window.__OVERLAY__){var o=n("gateway_encoding_override")||(null!=window.DiscordNative||null!=window.require?"etf":"json"),e=window.GLOBAL_ENV.GATEWAY_ENDPOINT+"/?encoding="+o+"&v="+window.GLOBAL_ENV.API_VERSION;null!=window.DiscordNative&&void 0!==window.Uint8Array&&void 0!==window.TextDecoder?e+="&compress=zstd-stream":void 0!==window.Uint8Array&&(e+="&compress=zlib-stream"),console.log("[FAST CONNECT] "+e+", encoding: "+o+", version: "+window.GLOBAL_ENV.API_VERSION);var i=new WebSocket(e);i.binaryType="arraybuffer";var r=Date.now(),w={open:!1,identify:!1,gateway:e,messages:[]};i.onopen=function(){console.log("[FAST CONNECT] connected in "+(Date.now()-r)+"ms"),w.open=!0},i.onclose=i.onerror=function(){window._ws=null},i.onmessage=function(n){w.messages.push(n)},window._ws={ws:i,state:w}}}}(); ``` -------------------------------- ### Glob Match Example: foo.ts Source: https://bun.com/docs/api/glob Demonstrates matching a specific file named 'foo.ts' using the glob.match function. This function likely returns a boolean indicating whether the provided file path matches the glob pattern. ```typescript const result1 = glob.match("foo.ts"); // => true ``` -------------------------------- ### Simple Bun Web Server for Debugging Source: https://bun.com/guides/runtime/web-debugger A basic Bun server implementation in TypeScript. This server listens for incoming requests and logs the request URL to the console. It's used as an example for demonstrating the debugging process. ```typescript Bun.serve({ fetch(req) { console.log(req.url); return new Response("Hello, world!"); }, }); ``` -------------------------------- ### Format Top Functions Summary (JavaScript) Source: https://bun.com/reference/bun/jsc This JavaScript code demonstrates how to format a summary of top functions from a sampling profile. It includes an example output format showing the sampling rate and a list of functions with their sample counts and identifiers. ```javascript document.addEventListener("DOMContentLoaded",()=>{ const clicker=document.getElementById("EebaWRgTzEgl:0:copy"); const code=document.getElementById("EebaWRgTzEgl:0"); clicker.addEventListener("click",(ev)=>{ navigator.clipboard.writeText(code.textContent).then(()=>{ clicker.querySelector(".clipboard").classList.add("hidden"); clicker.querySelector(".check").classList.remove("hidden"); setTimeout(()=>{ clicker.querySelector(".clipboard").classList.remove("hidden"); clicker.querySelector(".check").classList.add("hidden") },2500) }) }) }); ``` -------------------------------- ### Use Character Ranges and Negation in Glob Matching (TypeScript) Source: https://bun.com/docs/api/glob This example illustrates advanced file matching using character ranges and negation operators with 'glob.match' in TypeScript. It shows how to match files based on character sets and exclude specific characters. ```typescript glob.match("[bar].ts"); // => true glob.match("[^ab].ts"); // => true glob.match("[!a-z].ts"); // => true ``` -------------------------------- ### Match String Against Glob Pattern in Bun Source: https://bun.com/docs/api/glob This example demonstrates how to import and use the 'Glob' class from the 'glob' library to match a string against a glob pattern. This is a fundamental operation for filtering files or data based on specified patterns. ```typescript import { Glob } from "glob"; ``` -------------------------------- ### Match Multiple Patterns ({a,b,c}) in Glob Patterns Source: https://bun.com/docs/api/glob The '{a,b,c}' syntax allows matching any of the specified patterns. These patterns can be nested and combined with other wildcards. This example matches files named 'a.ts', 'b.ts', or 'c.ts'. ```javascript const glob = new Glob("{a,b,c}.ts"); glob.match("a.ts"); // => true glob.match("b.ts"); // => true glob.match("c.ts"); // => true glob.match("d.ts"); // => false ``` -------------------------------- ### Negate Glob Pattern Results (!) Source: https://bun.com/docs/api/glob The '!' character at the beginning of a glob pattern negates the match. Files matching the pattern after '!' will not be included. This example matches any file except 'index.ts'. ```javascript const glob = new Glob("!index.ts"); glob.match("index.ts"); // => false glob.match("foo.ts"); // => true ``` -------------------------------- ### Bun Glob Escaping Special Characters Source: https://bun.com/docs/api/glob Demonstrates how to escape special characters in glob patterns within Bun. This example shows creating a glob that specifically matches '!index.ts'. ```typescript const glob = new Glob("!index.ts"); glob.match("!index.ts"); // => true ``` -------------------------------- ### Interact with macOS Keychain API using Bun FFI (JavaScript) Source: https://bun.com/blog/compile-and-run-c-in-js This JavaScript code snippet uses Bun's Foreign Function Interface (FFI) to call C functions for interacting with the macOS Keychain. It defines the C source file, necessary frameworks, and the signatures of the functions to be exposed (setPassword, getPassword, deletePassword). It then demonstrates setting, getting, and logging a password from the keychain. ```javascript import { cc, ptr, CString } from "bun:ffi"; const { symbols: { setPassword, getPassword, deletePassword }, } = cc({ source: "./keychain.c", flags: [ "-framework", "Security", "-framework", "CoreFoundation", "-framework", "Foundation", ], symbols: { setPassword: { args: ["cstring", "cstring", "cstring"], returns: "i32", }, getPassword: { args: ["cstring", "cstring", "ptr", "ptr"], returns: "i32", }, deletePassword: { args: ["cstring", "cstring"], returns: "i32", }, }, }); var service = Buffer.from("com.bun.test.keychain\0"); var account = Buffer.from("bun\0"); var password = Buffer.alloc(1024); password.write("password\0"); var passwordPtr = new BigUint64Array(1); passwordPtr[0] = BigInt(ptr(password)); var passwordLength = new Uint32Array(1); setPassword(ptr(service), ptr(account), ptr(password)); passwordLength[0] = 1024; password.fill(0); getPassword(ptr(service), ptr(account), ptr(passwordPtr), ptr(passwordLength)); const result = new CString( Number(passwordPtr[0]), 0, passwordLength[0] ); console.log(result); ``` -------------------------------- ### Enable Text-Based Lockfile with Bun Install Source: https://bun.com/blog/bun-lock-text-lockfile This command enables the generation of a text-based `bun.lock` file instead of the default binary `bun.lockb` file. This is useful for improving pull request reviews and simplifying merge conflict resolution. The flag `--save-text-lockfile` is used to activate this feature. ```bash bun install --save-text-lockfile ``` -------------------------------- ### Node.js fs.glob() Compatibility in Bun Source: https://bun.com/docs/api/glob Illustrates Bun's compatibility with Node.js's `fs.glob()` function. This example shows how to import and use `glob` from 'node:fs' in a Bun environment, including comments indicating expected results. ```typescript import { glob, globSync, promises } from "node:fs"; // Array of patterns const files = await glob("*.ts"); // => true glob("index.ts"); // => false ``` -------------------------------- ### Bun Glob Pattern: Single Character Match (?) Source: https://bun.com/docs/api/glob Demonstrates the use of the '?' glob pattern in Bun, which matches any single character. This example shows how to create a new Glob object and use its 'match' method to find files matching the pattern '???.ts'. ```typescript const glob = new Glob("???.ts"); glob.match( // ... ); ``` -------------------------------- ### Scan Directory for Files with Bun fs.glob() (TypeScript) Source: https://bun.com/docs/api/glob This code snippet demonstrates how to use Bun's `fs.glob()` function to scan a directory for files matching a specific pattern, such as '*.ts'. It imports the necessary `Glob` class from the 'bun' module. The example shows the basic syntax for initializing and using the glob function. ```typescript import { Glob } from "bun"; const glob = new Glob("*.ts"); // Example usage (assuming you want to iterate over matches) for (const file of glob.scanSync(".")) { console.log(file); } ``` -------------------------------- ### TypeScript Console Log with Replaced Variables Source: https://bun.com/guides/runtime/define-constant Illustrates the resulting TypeScript code after Bun processes the --define flag. This example shows how a console log statement referencing AWS.ACCESS_KEY is transformed to output the defined JSON value. This transformation allows for dynamic configuration of your application at runtime. ```typescript console.log(AWS.ACCESS_KEY); // => "abc" ``` -------------------------------- ### Using Bun --define for Runtime and Build Source: https://bun.com/guides/runtime/define-constant Demonstrates how to use the --define flag with Bun for both runtime execution and building. This flag replaces specified identifiers or properties with constant values, aiding in optimizations. ```shell bun --define process.env.NODE_ENV="'production'" src/index.ts # Runtime bun build --define process.env.NODE_ENV="'production'" src/index.ts # Build ``` -------------------------------- ### Match Any Number of Characters Including Slashes (**) in Glob Patterns Source: https://bun.com/docs/api/glob The '**' wildcard matches any number of characters, including path separators ('/' or '\'). This allows for recursive matching within directories. This example matches any file ending with '.ts' in any subdirectory. ```javascript const glob = new Glob("**/*.ts"); glob.match("index.ts"); // => true glob.match("src/index.ts"); // => true glob.match("src/index.js"); // => false ``` -------------------------------- ### Bun Test Implementation Example in TypeScript Source: https://bun.com/guides/test/todo-tests This TypeScript code snippet demonstrates how to use the `test` and `expect` functions provided by the 'bun:test' module. It includes a basic test case with an unimplemented feature marked as a todo, and an assertion using `expect().toBe(true)`. ```typescript import { test, expect } from "bun:test"; test.todo("unimplemented feature", () => { expect(Bun.isAwesome()).toBe(true); }); ``` -------------------------------- ### Match Zero or More Characters (*) in Glob Patterns Source: https://bun.com/docs/api/glob The '*' wildcard matches zero or more characters, but it does not match path separators ('/' or '\'). This is commonly used for matching files within a directory. This example matches any file ending with '.ts' in the current directory. ```javascript const glob = new Glob("*.ts"); glob.match("index.ts"); // => true glob.match("src/index.ts"); // => false ``` -------------------------------- ### Match Character Sets and Ranges ([...]) in Glob Patterns Source: https://bun.com/docs/api/glob The '[...]' syntax matches any single character within the brackets. It supports individual characters, character ranges (e.g., '[a-z]', '[0-9]'), and negation ('[^...]' or '[!...])'. This example matches 'bar.ts' and 'baz.ts' but not 'bat.ts'. ```javascript const glob = new Glob("ba[rz].ts"); glob.match("bar.ts"); // => true glob.match("baz.ts"); // => true glob.match("bat.ts"); // => false ``` -------------------------------- ### Enable Dot File Matching in Options (TypeScript) Source: https://bun.com/docs/api/glob Defines the 'dot' option, a boolean flag that controls whether files starting with a period (dot files) should be included in the matching process. It defaults to false, meaning dot files are excluded unless explicitly enabled. ```typescript dot?: boolean; ``` -------------------------------- ### Bun's Optimization: Constant Folding and Dead Code Elimination Source: https://bun.com/guides/runtime/define-constant Shows the step-by-step optimization process by Bun's transpiler. It demonstrates how defining a constant like process.env.NODE_ENV leads to constant folding and subsequent dead code elimination, simplifying the final code. ```javascript if ("production" === "production") { console.log("Production mode"); } else { console.log("Development mode"); } ``` ```javascript if (true) { console.log("Production mode"); } else { console.log("Development mode"); } ``` ```javascript console.log("Production mode"); ``` -------------------------------- ### Execute C function 'hello' from JavaScript using Bun Source: https://bun.com/blog/compile-and-run-c-in-js This snippet demonstrates how to compile and execute a simple C function named 'hello' within a JavaScript environment using Bun. It requires the 'cc' utility for compilation and defines the C function's signature. ```javascript const { hello } = require("@bun/cc")({ source: "./hello.c", symbols: { hello: { returns: "void", args: [], }, }, }); hello(); ``` -------------------------------- ### JavaScript for Page Initialization and Theme Management Source: https://bun.com/guides/read-file/uint8array This JavaScript code initializes the page by setting the data-page-mode attribute and configuring the theme. It also includes logic for dynamically loading KaTeX CSS and managing various feature toggles. ```javascript self.__next_f.push([1,"2e:[\"$\",\"$L36\",null,{\"children\":[[\"$\",\"$L30\",null,{\"id\":\"_mintlify-page-mode-script\",\"strategy\":\"beforeInteractive\",\"dangerouslySetInnerHTML\":{\"__html\":\"document.documentElement.setAttribute('data-page-mode', 'center');\"}}],[\"$\",\"$L37\",null,{\"theme\":\"aspen\"}],[\"$\",\"$L38\",null,{\"docsConfig\":\"$1b:props:children:props:children:props:docsConfig\",\"pageMetadata\":\"$1b:props:children:props:value:pageMetadata\"}],[[\"$\",\"style\",\"0\",{\"data-custom-css-index\":0,\"data-custom-css-path\":\"style.css\",\"dangerouslySetInnerHTML\":{\"__html\":\"$39\"}}]],\"$L3a\",\"$L3b\"}]}]\n"]) self.__next_f.push([1,"35:[\"$\",\"$L3c\",null,{\"children\":[\"$\",\"$L3d\",null,{\"children\":[\"$\",\"$L3e\",null,{\"children\":[\"$\",\"$L3f\",null,{\"children\":[[\"$\",\"$L7\",null,{\"fonts\":\"$16:props:children:props:children:2:props:children:props:children:props:children:props:value:docsConfig:fonts\",\"theme\":\"aspen\",\"subdomain\":\"bun-1dd33a4e\"}],[[\"$\",\"$L6\",null,{\"docsConfig\":\"$16:props:children:props:children:2:props:children:props:children:props:children:props:value:docsConfig\"}],[[\"$\",\"link\",null,{\"rel\":\"preload\",\"href\":\"https://d4tuoctqmanu0.cloudfront.net/katex.min.css\",\"as\":\"style\"}],[\"$\",\"script\",null,{\"type\":\"text/javascript\",\"children\":\"\\n (function() {\\n function loadKatex() {\\n const link = document.querySelector('link[href=\\\"https://d4tuoctqmanu0.cloudfront.net/katex.min.css\\\"');\\n if (link) link.rel = 'stylesheet';\\n }\\n if (document.readyState === 'loading') {\\n document.addEventListener('DOMContentLoaded', loadKatex);\\n } else {\\n loadKatex();\\n }\\n })();\\n \"}]],\"$L8\",null,{\"theme\":\"aspen\"}],[\"$\",\"$L40\",null,{\"fonts\":\"$16:props:children:props:children:2:props:children:props:children:props:children:props:value:docsConfig:fonts\",\"children\":[\"$\",\"$L41\",null,{\"bannersByLocale\":{},\"subdomain\":\"bun-1dd33a4e\",\"children\":[[\"$\",\"$L42\",null,{\"theme\":\"aspen\"}],[\"$\",\"$L43\",null,{\"subdomain\":\"bun-1dd33a4e\",\"children\":[\"$\",\"$L44\",null,{\"toggles\":[{\"name\":\"skip-github\",\"enabled\":true,\"variant\":{\"name\":\"disabled\",\"enabled\":false,\"feature_enabled\":true},\"impressionData\":false},{\"name\":\"server-bucketing-cron\",\"enabled\":true,\"variant\":{\"name\":\"disabled\",\"enabled\":false,\"feature_enabled\":true},\"impressionData\":false},{\"name\":\"cloudflare-cache-invalidation\",\"enabled\":true,\"variant\":{\"name\":\"disabled\",\"enabled\":false,\"feature_enabled\":true},\"impressionData\":false},{\"name\":\"dashboard-bucketing\",\"enabled\":true,\"variant\":{\"name\":\"disabled\",\"enabled\":false,\"feature_enabled\":true},\"impressionData\":false},{\"name\":\"notification-settings\",\"enabled\":true,\"variant\":{\"name\":\"disabled\",\"enabled\":false,\"feature_enabled\":true},\"impressionData\":false},{\"name\":\"autopilot-dashboard\",\"enabled\":true,\"variant\":{\"name\":\"disabled\",\"enabled\":false,\"feature_enabled\":true},\"impressionData\":false},{\"name\":\"chroma-migration\",\"enabled\":true,\"variant ``` -------------------------------- ### Replace Identifier with JSON Object using Bun Source: https://bun.com/guides/runtime/define-constant This command allows replacing an identifier with a JSON object. In this example, 'AWS' is replaced with a JSON object containing 'ACCESS_KEY' and 'SECRET_KEY'. The transformation results in direct usage of the JSON values, as shown in the 'To' example. ```bash # JSON bun --define AWS='{"ACCESS_KEY":"abc","SECRET_KEY":"def"}' src/index.ts ``` ```javascript console.log(AWS.ACCESS_KEY); // => "abc" ``` ```javascript console.log("abc"); ``` -------------------------------- ### Compile and Run C Code in Bun Source: https://bun.com/blog/compile-and-run-c-in-js This snippet demonstrates how to compile and run a simple C function from a TypeScript file using Bun's `bun:ffi` module. It includes the C source code and the corresponding TypeScript code that imports and calls the C function. ```c #include void hello() { printf("You can now compile & run C in Bun!\n"); } ``` ```typescript import { cc } from "bun:ffi"; export const { ``` -------------------------------- ### JSC Profiling and Debugging Source: https://bun.com/reference/bun/jsc Functions for profiling code execution and starting a remote debugger. ```APIDOC ## Profiling and Debugging Functions ### Description Provides functions to start the sampling profiler, start a remote debugger, and retrieve compilation statistics. ### Functions - **`FstartSamplingProfiler()`** - **Description**: Starts the sampling profiler. - **Method**: `bun:jsc` - **`FstartRemoteDebugger(port)`** - **Parameters**: - **`port`** (number) - The port to listen on for the debugger. - **Description**: Starts a remote debugger on the specified port. - **Method**: `bun:jsc` - **`FtotalCompileTime()`** - **Description**: Returns the total time spent compiling JavaScript code. - **Method**: `bun:jsc` - **`FnumberOfDFGCompiles()`** - **Description**: Returns the number of times the DFG compiler has run. - **Method**: `bun:jsc` - **`FreoptimizationRetryCount()`** - **Description**: Returns the number of reoptimization retries. - **Method**: `bun:jsc` ``` -------------------------------- ### JavaScriptCore Utility Functions Source: https://bun.com/reference/bun/jsc Utility functions for managing JavaScriptCore, including setting random seeds, time zones, and starting debugging or profiling tools. ```APIDOC ## Set Random Seed ### Description Sets the seed for the random number generator in JavaScriptCore. ### Method `setRandomSeed(value: number): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **value** (number) - Required - The seed value for the random number generator. ### Request Example ```json { "value": 12345 } ``` ### Response #### Success Response (200) No content is returned on success. #### Response Example None ## Set Time Zone ### Description Sets the timezone used by Intl, Date, and other time-related functions within JavaScriptCore. ### Method `setTimeZone(timeZone: string): string` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **timeZone** (string) - Required - A string representing the time zone to use (e.g., "America/Los_Angeles"). ### Request Example ```json { "timeZone": "America/New_York" } ``` ### Response #### Success Response (200) - **string** (string) - The normalized time zone string that was set. #### Response Example ```json { "example": "America/New_York" } ``` ## Start Remote Debugger ### Description Starts a remote debugging socket server on the specified host and port. This exposes JavaScriptCore's built-in debugging server. Note: This feature is untested and may not be supported on all platforms (e.g., macOS). ### Method `startRemoteDebugger(host?: string, port?: number): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **host** (string) - Optional - The host address for the debugger server. Defaults to localhost. - **port** (number) - Optional - The port number for the debugger server. Defaults to a predefined port. ### Request Example ```json { "host": "127.0.0.1", "port": 9229 } ``` ### Response #### Success Response (200) No content is returned on success. #### Response Example None ## Start Sampling Profiler ### Description Runs JavaScriptCore's sampling profiler. The results can be optionally saved to a specified directory. ### Method `startSamplingProfiler(optionalDirectory?: string): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **optionalDirectory** (string) - Optional - The directory where the profiling results should be saved. ### Request Example ```json { "optionalDirectory": "./profiler-output" } ``` ### Response #### Success Response (200) No content is returned on success. #### Response Example None ## Get Total Compile Time ### Description Calculates the total compilation time for a given JavaScript function. ### Method `totalCompileTime(func: (...args: any[]) => any): number` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **func** (function) - Required - The JavaScript function for which to measure compilation time. ### Request Example ```javascript function myFunction() { /* ... */ } const compileTime = totalCompileTime(myFunction); ``` ### Response #### Success Response (200) - **number** (number) - The total compilation time of the function in milliseconds. #### Response Example ```json { "example": 15.75 } ``` ``` -------------------------------- ### Bun Build: Using --define Flag Source: https://bun.com/guides/runtime/define-constant This terminal command illustrates the basic usage of the --define flag in Bun's build process. It allows you to replace occurrences of a specified identifier (e.g., `process.env.NODE_ENV`) with a given value (e.g., 'production') during the build or transpilation phase. ```bash bun build --define process.env.NODE_ENV=production ```