### Basic Setup Import Example Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/EXPORTS.md Demonstrates how to import and use the main `runAction` function with basic input options. ```typescript import runAction from './action.js'; const result = await runAction({ version: '1.0.0' }); ``` -------------------------------- ### Basic Setup: Latest Bun Version Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Installs the latest available version of Bun. Useful for general testing or when the exact version is not critical. ```yaml name: Test on: [push] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 - run: bun --version - run: bun install - run: bun test ``` -------------------------------- ### Basic Setup: Specific Bun Version Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Installs a precise version of Bun. Use this when your project has strict version dependencies. ```yaml steps: - uses: oven-sh/setup-bun@v2 with: bun-version: '1.0.0' - run: bun --version # Output: 1.0.0 ``` -------------------------------- ### Log Bun Installation Details Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/configuration.md This snippet demonstrates how to access and log the outputs provided by the setup-bun action, such as the installed Bun version and its path. ```yaml - uses: oven-sh/setup-bun@v2 id: bun with: bun-version: '1.0.0' - name: Log Bun info run: | echo "Version: ${{ steps.bun.outputs.bun-version }}" echo "Path: ${{ steps.bun.outputs.bun-path }}" echo "Cache hit: ${{ steps.bun.outputs.cache-hit }}" ``` -------------------------------- ### Installation Data Flow Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/architecture.md Illustrates the sequence of operations for installing the Bun runtime, from input parsing to adding the executable to the PATH. ```text Input parsing ↓ Resolve version → Download URL ↓ Check cache → Cache hit? Return cached path ├─ No cache → Download ZIP ↓ Extract ZIP → Find executable → Verify version ↓ Move to ~/.bun/bin/bun → Create bunx symlink ↓ Add ~/.bun/bin to PATH ↓ Output: version, revision, bunPath, url, cacheHit ``` -------------------------------- ### Run Action to Install Bun Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/action.md Use this snippet to download, install, and configure Bun with optional caching and registry setup. It requires the `runAction` function and accepts an `Input` object. ```typescript import runAction from './action.js'; const result = await runAction({ version: '1.0.0', registries: [ { url: 'https://registry.npmjs.org/', scope: '' } ], noCache: false, token: process.env.GITHUB_TOKEN }); console.log(`Installed Bun ${result.revision} at ${result.bunPath}`); ``` -------------------------------- ### Setup Bun GitHub Action Architecture Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/README.md Provides a high-level overview of the Setup Bun GitHub Action's workflow, from parsing inputs to setting outputs and managing cache. ```mermaid graph TD GitHub Actions Event ↓ index.ts (Entry Point) ├─ Parse inputs via @actions/core ├─ Call runAction() ↓ action.ts (Main Orchestrator) ├─ Write bunfig.toml via bunfig.ts ├─ Resolve URL via download-url.ts ├─ Check cache via @actions/cache ├─ Download ZIP via @actions/tool-cache ├─ Extract via extractBun() ├─ Verify via getRevision() └─ Save cache state ↓ Set outputs via @actions/core ↓ cache-save.ts (Post-Action) ├─ Retrieve cache state ├─ Save to GitHub Actions cache ↓ Workflow continues with bun in PATH ``` -------------------------------- ### Import Example with Registries Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/EXPORTS.md Shows how to parse registry configurations, write them to 'bunfig.toml', and then use them with the `runAction` function. ```typescript import { parseRegistries } from './registry.js'; import { writeBunfig } from './bunfig.js'; import runAction from './action.js'; const registries = parseRegistries(` https://registry.npmjs.org/ @myorg:https://registry.myorg.com/|$TOKEN `); writeBunfig('./bunfig.toml', registries); const result = await runAction({ version: '1.0.0', registries }); ``` -------------------------------- ### runAction Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/action.md Downloads, installs, and configures Bun with optional caching and registry setup. It orchestrates the entire process of setting up the Bun runtime within a GitHub Actions environment. ```APIDOC ## runAction ### Description Downloads, installs, and configures Bun with optional caching and registry setup. It orchestrates the entire process of setting up the Bun runtime within a GitHub Actions environment. ### Method Asynchronous function call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (Input) - Required - Configuration object containing version, platform, and registry settings ### Input Properties - **customUrl** (string) - Optional - Direct download URL that bypasses version resolution and AVX2 checks - **version** (string) - Optional - Bun version to install: "latest", "canary", "action", specific version (e.g., "1.0.0"), or version range (e.g., "1.0.x") - **os** (string) - Optional - Operating system: "windows", "linux", "darwin" - **arch** (string) - Optional - CPU architecture: "x64", "arm64", "aarch64" - **avx2** (boolean) - Optional - Force AVX2 support level for x64 Linux builds - **profile** (boolean) - Optional - Include profiling symbols in downloaded binary - **registries** (Registry[]) - Optional - NPM registries configuration - **noCache** (boolean) - Optional - Disable caching of Bun executable - **token** (string) - Optional - GitHub PAT for fetching tags from oven-sh/bun repository ### Return Type Returns a Promise resolving to Output object: - **version** (string) - Semantic version of installed Bun (e.g., "1.0.0") - **revision** (string) - Full revision string including commit hash (e.g., "1.0.0+822a00c4") - **bunPath** (string) - Absolute path to Bun executable - **url** (string) - Download URL used to obtain Bun - **cacheHit** (boolean) - Whether Bun was restored from GitHub Actions cache ### Behavior The action performs the following steps: 1. **Write registry configuration**: If registries are provided, writes bunfig.toml in the current working directory 2. **Resolve download URL**: Determines URL from version string (handling "latest", "canary", semantic versioning, and range queries) 3. **Check cache**: If caching is enabled and version is pinned, attempts to restore from GitHub Actions cache 4. **Check existing installation**: If no custom URL and Bun is already at ~/.bun/bin/bun, validates it matches the requested version 5. **Download and extract**: Fetches and extracts Bun binary to ~/.bun/bin/ 6. **Configure PATH**: Adds ~/.bun/bin to GitHub Actions runner PATH 7. **Create symlinks**: Creates bunx symlink to bun executable 8. **Save cache state**: Stores cache state for post-action cache save operation ### Throws - **Error**: "Could not find executable: bun" if the downloaded archive does not contain a bun binary - **Error**: "Downloaded a new version of Bun, but failed to check its version? Try again." if version verification fails - **Error**: File system errors if unable to create directories or modify files ### Example ```typescript import runAction from './action.js'; const result = await runAction({ version: '1.0.0', registries: [ { url: 'https://registry.npmjs.org/', scope: '' } ], noCache: false, token: process.env.GITHUB_TOKEN }); console.log(`Installed Bun ${result.revision} at ${result.bunPath}`); ``` ``` -------------------------------- ### Platform Mismatch Example (Corrected) Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Shows the correct usage for native ARM64 support starting from Bun v1.3.10, addressing potential emulation issues on Windows ARM64. ```yaml # Windows ARM64 before v1.3.10 falls back to x64 emulation steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: bun-version: '1.3.10' # Use 1.3.10+ for native ARM64 ``` -------------------------------- ### Platform Mismatch Example (Incorrect) Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Illustrates an incorrect setup where the runner platform (ubuntu) mismatches the specified Bun version's intended platform (Windows). ```yaml # Wrong - runner is ubuntu but specifying windows steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: bun-version: '1.0.0' ``` -------------------------------- ### Basic Usage of setup-bun Action Source: https://github.com/oven-sh/setup-bun/blob/main/README.md Use this snippet to install the setup-bun action. By default, it attempts to detect the Bun version from package.json or falls back to 'latest'. ```yaml - uses: oven-sh/setup-bun@v2 ``` -------------------------------- ### Install Canary Bun Version Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/configuration.md Install the latest development build of Bun by setting `bun-version` to 'canary'. ```yaml - uses: oven-sh/setup-bun@v2 with: bun-version: canary ``` -------------------------------- ### Registry Configuration Examples Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/README.md Illustrates various ways to configure NPM registries, including public, scoped, and authenticated registries. ```text https://registry.npmjs.org/ @myorg:https://npm.pkg.github.com/|$GITHUB_TOKEN @internal:https://user:pass@registry.internal.com/ ``` -------------------------------- ### Basic Setup: Bun Version Range Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Installs the latest patch version within a specified minor version range (e.g., '1.0.x'). Ensures compatibility within a major/minor version. ```yaml steps: - uses: oven-sh/setup-bun@v2 with: bun-version: '1.0.x' # Latest 1.0.z - run: bun --version # Output: 1.0.25 (example) ``` -------------------------------- ### Bunfig TOML Configuration Example Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/bunfig.md Illustrates the structure of a generated bunfig.toml file, showing how global and scoped registries are configured. ```toml [install] # Global default registry (if provided) [install.registry] url = "https://registry.npmjs.org/" token = "optional_token" # Scoped registries [install.scopes] @myorg = { url = "https://registry.myorg.com/", token = "token" } ``` -------------------------------- ### Verify Bun Installation Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Verifies the Bun installation by checking its version, revision, and executable paths using standard command-line tools. ```yaml steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: bun-version: '1.0.0' - name: Verify Bun run: | bun --version bun --revision which bun which bunx ``` -------------------------------- ### Monorepo Workspace Setup Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Configures Bun for a monorepo, automatically reading the version from the root package.json and running workspace commands. ```yaml jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 # Reads version from root package.json - run: bun install - run: bun run build - run: bun run test - name: Publish packages run: | bun run publish:workspace env: NPM_TOKEN: ${{ secrets.NPM_TOKEN }} ``` -------------------------------- ### Version Matching Algorithm Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/README.md Outlines the logic for determining the Bun version to install when not explicitly specified. Prioritizes exact versions and ranges over dynamic tags. ```text 1. If no version requested → never match (always get latest) 2. If dynamic version ("latest", "canary") → never match 3. If exact version → compare semver (ignoring v prefix) 4. Else (range) → query GitHub API for matches ``` -------------------------------- ### Registry Connection Timeout Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Sets a timeout for the 'bun install' command when connecting to a slow registry to prevent the build from hanging indefinitely. ```yaml steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: registries: | @slow:https://slow-registry.example.com/|$TOKEN - name: With timeout run: timeout 120 bun install ``` -------------------------------- ### Setup ~/.bun/bin PATH in GitHub Actions Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/implementation-details.md Creates the ~/.bun/bin directory and adds it to the GitHub Actions PATH environment variable, making 'bun' and 'bunx' available in subsequent job steps. ```typescript const binPath = join(homedir(), ".bun", "bin"); mkdirSync(binPath, { recursive: true }); addPath(binPath); // GitHub Actions API ``` -------------------------------- ### Version Resolution: From package.json Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Automatically detects and installs the Bun version specified in the `packageManager` or `engines.bun` field of your `package.json`. ```yaml steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 # Reads from package.json - run: bun install ``` ```json { "packageManager": "bun@1.0.0" } ``` ```json { "engines": { "bun": "1.0.0" } } ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Enables debug logging for the setup-bun action by setting the RUNNER_DEBUG environment variable. Useful for diagnosing installation issues. ```yaml steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: bun-version: '1.0.0' env: RUNNER_DEBUG: '1' # Enable debug logging ``` -------------------------------- ### Version Resolution: From Version File Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Installs Bun from a specified version file (e.g., `.bun-version`, `.tool-versions`, `package.json`, `.bumrc`). Supports plain text versions and asdf format. ```yaml steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: bun-version-file: '.bun-version' - run: bun install ``` -------------------------------- ### Specify Exact Bun Version Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/configuration.md Install a specific version of Bun by providing the exact version number to the `bun-version` input. ```yaml - uses: oven-sh/setup-bun@v2 with: bun-version: '1.0.0' ``` -------------------------------- ### Handle Non-existent Version Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Demonstrates the error message received when attempting to install a non-existent Bun version and suggests using an existing version or 'latest'. ```yaml steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: bun-version: '1.99.0' # Non-existent token: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------- ### Platform-Specific Builds: Windows ARM64 Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Installs Bun on Windows ARM64 runners. Requires Bun version 1.3.10 or later for native ARM64 support on Windows. ```yaml jobs: test-windows-arm64: runs-on: windows-latest-arm64 steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: bun-version: '1.3.10' # Required for native ARM64 - run: bun test ``` -------------------------------- ### Specify Bun Version Range Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/configuration.md Install a Bun version within a specified range using semantic versioning in the `bun-version` input. ```yaml - uses: oven-sh/setup-bun@v2 with: bun-version: '1.0.x' ``` -------------------------------- ### Get Download URL Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/EXPORTS.md Fetches the download URL for a specific Bun version using an optional GitHub token. ```typescript import { getDownloadUrl } from './download-url.js'; const url = await getDownloadUrl({ version: '1.0.x', token: process.env.GITHUB_TOKEN }); ``` -------------------------------- ### getPlatform Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/utils.md Gets the current operating system platform in a Bun-compatible format. This function is useful for cross-platform compatibility checks. ```APIDOC ## getPlatform ### Description Get the current operating system platform in Bun-compatible format. ### Method ```typescript function getPlatform(): string ``` ### Return Type Returns platform string: "windows", "darwin", or "linux". ### Behavior Normalizes Node.js process.platform values to Bun release naming: - "win32" → "windows" - "darwin" → "darwin" - "linux" → "linux" ### Example ```typescript import { getPlatform } from './utils.js'; const platform = getPlatform(); // Returns: "linux", "darwin", or "windows" ``` ``` -------------------------------- ### Platform-Specific Builds: ARM64 Support Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Installs Bun on ARM64 runners, ensuring native support. Requires Bun version 1.3.10 or later for native ARM64 builds. ```yaml jobs: test-arm64: runs-on: ubuntu-latest-arm64 steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: bun-version: '1.3.10' # Or later (has native ARM64) - run: bun install - run: bun test ``` -------------------------------- ### Migrate from Deprecated Registry Inputs to Registries Input Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/errors.md This YAML example demonstrates the migration from deprecated 'registry-url' and 'scope' inputs to the newer 'registries' input format for configuring npm registries. ```yaml # OLD - Deprecated with: registry-url: 'https://npm.pkg.github.com/' scope: '@myorg' # NEW - Use registries instead with: registries: | @myorg:https://npm.pkg.github.com/ ``` -------------------------------- ### Main Action Export Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/EXPORTS.md Defines the primary function for orchestrating Bun downloads, installations, and caching. Includes types for input configuration, output results, and cache state. ```typescript export default async function(options: Input): Promise export type Input = { ... } export type Output = { ... } export type CacheState = { ... } ``` -------------------------------- ### Main Action Export Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/EXPORTS.md The main action orchestrator function. It downloads, installs, and caches Bun. It accepts an Input object for configuration and returns an Output object detailing the result. ```APIDOC ## Main Action Export ### Description This is the primary function for orchestrating the download, installation, and caching of Bun. It takes a configuration object and returns details about the operation. ### Function Signature `default(options: Input): Promise` ### Types - **Input**: Configuration for the action, including version, platform, registries, and caching options. - **Output**: Result of the action, containing version, revision, Bun path, download URL, and cache status. - **CacheState**: Represents the state persisted between main and post-action for cache operations. ``` -------------------------------- ### Normalize Bun OS Platform Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/implementation-details.md Maps Node.js process.platform values to Bun's release naming convention. For example, 'win32' is normalized to 'windows'. ```typescript function getPlatform(): string { const platform = process.platform; if (platform === "win32") return "windows"; return platform; // "darwin", "linux" } ``` -------------------------------- ### Read Bun Version from File with Silent Option Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/errors.md This example shows how to read the Bun version from a specified file, demonstrating the use of the 'silent' option to control warning logs. It also suggests providing an explicit version as an alternative. ```typescript // With silent: false (default) - logs warning readVersionFromFile('.bun-version', false); // With silent: true - no warning logged readVersionFromFile('package.json', true); // Provide explicit version instead bun-version: '1.0.0' ``` -------------------------------- ### Get Operating System Platform Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/utils.md Retrieves the current operating system platform in a format compatible with Bun releases (e.g., 'windows', 'darwin', 'linux'). ```typescript import { getPlatform } from './utils.js'; const platform = getPlatform(); // Returns: "linux", "darwin", or "windows" ``` -------------------------------- ### Check Pinned Bun Version Match Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/implementation-details.md Compares an existing Bun installation's revision against a requested version. Returns false for dynamic versions or when no version is requested to ensure updates. ```typescript function isVersionMatch(existingRevision: string, requestedVersion?: string): boolean ``` -------------------------------- ### Get Bun Download URL Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/download-url.md Resolves the download URL for a specific Bun version and platform. Supports 'latest', 'canary', semver, and range version specifications. Defaults to current OS and architecture if not provided. ```typescript async function getDownloadUrl(options: Input): Promise ``` ```typescript import { getDownloadUrl } from './download-url.js'; // Resolve latest version for current platform const url1 = await getDownloadUrl({ version: 'latest' }); // Returns: "https://github.com/oven-sh/bun/releases/download/1.0.0/bun-linux-x64.zip" ``` ```typescript // Pin specific version const url2 = await getDownloadUrl({ version: '1.0.0', os: 'windows', arch: 'x64', avx2: true }); // Returns: "https://github.com/oven-sh/bun/releases/download/bun-v1.0.0/bun-windows-x64.zip" ``` ```typescript // Use custom URL (skips resolution) const url3 = await getDownloadUrl({ customUrl: 'https://custom-mirror.example.com/bun-linux-x64.zip' }); // Returns: "https://custom-mirror.example.com/bun-linux-x64.zip" ``` ```typescript // Range with GitHub auth const url4 = await getDownloadUrl({ version: '1.0.x', token: process.env.GITHUB_TOKEN }); // Fetches all tags, matches latest 1.0.x release ``` -------------------------------- ### Handle Multiple Global Registries Error Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/errors.md Illustrates how to correct the `registries` input when it contains more than one unscoped (global) registry. The example shows the incorrect and correct configurations. ```yaml # BAD - Two unscoped registries registries: | https://registry.npmjs.org/ https://other-registry.example.com/ # GOOD - One global, others scoped registries: | https://registry.npmjs.org/ @other:https://other-registry.example.com/ ``` -------------------------------- ### Handle Bun Version Check Error Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/errors.md Addresses failures when checking the Bun version after installation, which can happen if the executable is corrupted or lacks permissions. Suggests retrying the action or specifying a working build URL. ```typescript // Newly downloaded executable is corrupted // Executable lacks permissions // Bun binary execution fails // Version output format is unexpected ``` -------------------------------- ### Project Structure Overview Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/README.md This snippet outlines the directory and file organization of the setup-bun project. It helps in understanding the location of source files, build outputs, and configuration. ```bash setup-bun/ ├── src/ │ ├── index.ts # Entry point (parses inputs, calls runAction) │ ├── action.ts # Main orchestration logic │ ├── download-url.ts # Version resolution and URL building │ ├── registry.ts # Registry configuration parsing │ ├── bunfig.ts # bunfig.toml writing │ ├── cache-save.ts # Post-action cache saving │ └── utils.ts # 9 utility functions ├── dist/ │ ├── setup/index.js # Bundled main action │ └── cache-save/index.js # Bundled post-action ├── action.yml # Action definition with inputs/outputs ├── package.json # Dependencies and scripts ├── tsconfig.json # TypeScript configuration └── README.md # Main project README ``` -------------------------------- ### Access All Outputs Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Demonstrates how to access all available outputs from the setup-bun action, including version, revision, path, download URL, and cache hit status. ```yaml steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 id: bun - run: | echo "Version: ${{ steps.bun.outputs.bun-version }}" echo "Revision: ${{ steps.bun.outputs.bun-revision }}" echo "Path: ${{ steps.bun.outputs.bun-path }}" echo "URL: ${{ steps.bun.outputs.bun-download-url }}" echo "Cache hit: ${{ steps.bun.outputs.cache-hit }}" ``` -------------------------------- ### API Reference Overview Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/INDEX.md This section provides an overview of the API surface for the setup-bun GitHub Actions action, including details on exported functions, types, and parameters. ```APIDOC ## API Surface This API provides the following capabilities: ### Exported Functions - All 13 exported functions are documented with full signatures. - Practical usage examples are provided for each function. ### Exported Types - All 5 exported types are documented with field descriptions. ### Parameters - Parameter tables include types, defaults, and requirements. ### Return Types - Return type documentation is provided for all functions. ### Modules - **action.md**: Details the `runAction` function and orchestration. - **registry.md**: Details the `parseRegistries` function. - **download-url.md**: Details the `getDownloadUrl` function. - **bunfig.md**: Details the `writeBunfig` function. - **utils.md**: Details 9 utility functions. ``` -------------------------------- ### File Organization Structure Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/INDEX.md Illustrates the directory structure of the setup-bun GitHub Actions action documentation, showing the location of various reference files. ```text output/ ├── README.md # Start here ├── EXPORTS.md # Symbol index ├── types.md # Type definitions ├── configuration.md # Inputs/outputs/config ├── errors.md # Error reference ├── architecture.md # System design ├── implementation-details.md # Internals ├── usage-examples.md # Practical patterns ├── INDEX.md # This file └── api-reference/ ├── action.md # Main orchestrator ├── registry.md # Registry parsing ├── download-url.md # URL resolution ├── bunfig.md # Config writing └── utils.md # Utilities (9 functions) ``` -------------------------------- ### Use Bun Path in Scripts Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Shows how to use the 'bun-path' output to directly execute the Bun binary in scripts, ensuring the correct version is used. ```yaml steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 id: bun - name: Run Bun directly run: ${{ steps.bun.outputs.bun-path }} --version ``` -------------------------------- ### Build and Run Commands Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/README.md Commands for building, running locally, and formatting the project code using npm scripts. ```bash npm run build # Compile and bundle npm run start # Build and run locally npm run format # Format code with prettier ``` -------------------------------- ### Registry Scope Normalization Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/implementation-details.md Normalizes registry scope names by ensuring they start with '@' and are converted to lowercase. It also conditionally adds the token property if provided. ```typescript const scopeName = registry.scope.startsWith("@") ? registry.scope.toLowerCase() : `@${registry.scope.toLowerCase()}`; config.install.scopes[scopeName] = { url: registry.url, ...(registry.token ? { token: registry.token } : {}), }; ``` -------------------------------- ### Use Bun Version from a File Source: https://github.com/oven-sh/setup-bun/blob/main/README.md Specify a file containing the Bun version to use, such as '.bun-version', '.tool-versions', or 'package.json'. ```yaml - uses: oven-sh/setup-bun@v2 with: bun-version-file: ".bun-version" ``` -------------------------------- ### Configuration Writing Export Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/EXPORTS.md Creates or updates the bunfig.toml file with provided registry configurations. It takes a file path and an array of Registry objects. ```APIDOC ## Configuration Writing Export ### Description Writes or updates a `bunfig.toml` file at the specified path with the given registry configurations. This allows for persistent configuration of Bun's registry settings. ### Function Signature `writeBunfig(path: string, registries: Registry[]): void` ### Parameters - **path** (string) - Required - The file path where `bunfig.toml` should be created or updated. - **registries** (Registry[]) - Required - An array of `Registry` objects to be written to the configuration file. ``` -------------------------------- ### AVX2 Auto-Detection on Linux x64 Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/README.md Explains the process for detecting AVX2 support on Linux x64 systems to select the appropriate Bun build. Includes fallback and logging for unavailable CPU information. ```text 1. Read /proc/cpuinfo 2. Check for "avx2" flag 3. Use AVX2 build if present, baseline if not 4. Log warning if /proc/cpuinfo unavailable ``` -------------------------------- ### Output Type Definition for Action Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/action.md Defines the structure of the output object returned by the `runAction` function, including the installed Bun version, revision, path, and cache status. ```typescript type Output = { version: string; revision: string; bunPath: string; url: string; cacheHit: boolean; }; ``` -------------------------------- ### Specify Bun Version in .bun-version file Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/configuration.md Use a plain text file named `.bun-version` to specify the desired Bun version. ```text 1.0.0 ``` -------------------------------- ### Use Custom Bun Download URL Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/configuration.md Bypass version resolution and download Bun directly from a custom URL using the `bun-download-url` input. This is useful for private mirrors. ```yaml - uses: oven-sh/setup-bun@v2 with: bun-download-url: 'https://private-mirror.example.com/bun-linux-x64.zip' ``` -------------------------------- ### Configuration Data Flow Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/architecture.md Details the process of parsing and writing registry configurations to bunfig.toml, including validation steps. ```text Input: registries string ↓ parseRegistries() → Validate URLs, parse scopes/tokens ↓ writeBunfig(path, Registry[]) ├─ Read existing bunfig.toml if present ├─ Validate no >1 global registry ├─ Update install.registry (global) ├─ Update install.scopes (scoped) ↓ Write to bunfig.toml ↓ Bun reads bunfig.toml during package installation ``` -------------------------------- ### Configuration Writing Export Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/EXPORTS.md Exports a function to create or update 'bunfig.toml' with provided registry configurations. ```typescript export function writeBunfig(path: string, registries: Registry[]): void ``` -------------------------------- ### Handle HTTP Request Errors Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/errors.md Catches HTTP request errors, including status codes and network failures. Provides examples for handling rate limiting (403) and invalid tokens (401). ```typescript const response = await request(url, { headers: { 'Authorization': `Bearer ${token}` } }).catch(error => { if (error.message.includes('status code: 403')) { // Rate limited - retry with token } else if (error.message.includes('status code: 401')) { // Invalid token - check GITHUB_TOKEN secret } }); ``` -------------------------------- ### getDownloadUrl Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/download-url.md Get the download URL for a specific Bun version and platform combination. It resolves the URL based on provided options, including custom URLs, version specifications, OS, architecture, and feature flags. ```APIDOC ## getDownloadUrl ### Description Get the download URL for a specific Bun version and platform combination. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (Input) - Required - Configuration object with version and platform details ### Input Properties - **customUrl** (string) - Optional - Direct download URL; if provided, returned immediately - **version** (string) - Optional - Version specification: "latest", "canary", semver, or range - **os** (string) - Optional - Operating system (defaults to current OS) - **arch** (string) - Optional - CPU architecture (defaults to process.arch) - **avx2** (boolean) - Optional - CPU feature level for x64 (auto-detected if undefined) - **profile** (boolean) - Optional - Include profiling symbols - **token** (string) - Optional - GitHub PAT for API rate limiting ### Request Example ```typescript import { getDownloadUrl } from './download-url.js'; // Resolve latest version for current platform const url1 = await getDownloadUrl({ version: 'latest' }); // Pin specific version const url2 = await getDownloadUrl({ version: '1.0.0', os: 'windows', arch: 'x64', avx2: true }); // Use custom URL (skips resolution) const url3 = await getDownloadUrl({ customUrl: 'https://custom-mirror.example.com/bun-linux-x64.zip' }); // Range with GitHub auth const url4 = await getDownloadUrl({ version: '1.0.x', token: process.env.GITHUB_TOKEN }); ``` ### Response #### Success Response (200) - **URL** (string) - A complete HTTPS URL to the Bun release ZIP file. #### Response Example ```json { "url": "https://github.com/oven-sh/bun/releases/download/1.0.0/bun-linux-x64.zip" } ``` ### Throws - **Error**: "No Bun release found matching version '{version}'" if version cannot be resolved - **Fetch errors**: From GitHub API if network request fails or rate limit exceeded ``` -------------------------------- ### Registry Configuration: GitHub Packages Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Configures access to GitHub Packages using a GitHub token. Ensure the token has the necessary read permissions. ```yaml steps: - uses: oven-sh/setup-bun@v2 with: registries: | https://registry.npmjs.org/ @myorg:https://npm.pkg.github.com/|${{ secrets.GITHUB_TOKEN }} - run: bun install ``` -------------------------------- ### Specify Bun Version in .tool-versions file Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/configuration.md This snippet shows how to specify the Bun version using the `.tool-versions` format, commonly used by version managers like asdf. ```text bun 1.0.0 ``` -------------------------------- ### Create Directory Safely Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/implementation-details.md Creates a directory recursively if it does not exist. It safely ignores 'EEXIST' errors, indicating the directory is already present, and re-throws any other errors encountered. ```typescript try { mkdirSync(binPath, { recursive: true }); } catch (error) { if (error.code !== "EEXIST") { throw error; } } ``` -------------------------------- ### Registry Configuration: With Authentication Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Configures registries with authentication tokens or credentials. Supports environment variables for sensitive information. ```yaml steps: - uses: oven-sh/setup-bun@v2 with: registries: | https://registry.npmjs.org/ @myorg:https://npm.pkg.github.com/|$GITHUB_TOKEN @internal:https://username:$INTERNAL_PASSWORD@registry.internal.com/ env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} INTERNAL_PASSWORD: ${{ secrets.INTERNAL_PASSWORD }} - run: bun install ``` -------------------------------- ### Custom Download URL Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Configures the action to download Bun from a custom URL. This is useful for private mirrors, air-gapped networks, or specific build artifacts. ```yaml steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: bun-download-url: 'https://private-mirror.example.com/bun-linux-x64.zip' - run: bun install ``` -------------------------------- ### Create Bunx Symlink Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/implementation-details.md Creates a symlink for 'bunx' pointing to 'bun'. It ignores 'EEXIST' errors if the symlink already exists and throws for other errors. On Windows, it uses '.exe' extensions. ```typescript const bunPath = join(binPath, exe("bun")); try { symlinkSync(bunPath, join(binPath, exe("bunx"))); } catch (error) { if (error.code !== "EEXIST") { throw error; } } ``` -------------------------------- ### Write Bunfig Configuration Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/bunfig.md Creates or updates a bunfig.toml file with specified registry configurations. It handles validation, merging, and enforcement of registry constraints. ```typescript import { writeBunfig } from './bunfig.js'; const registries = [ { url: 'https://registry.npmjs.org/', scope: '' }, { url: 'https://npm.pkg.github.com/', scope: '@myorg', token: '$GITHUB_TOKEN' } ]; writeBunfig('/workspace/bunfig.toml', registries); // Creates or updates bunfig.toml with registry configuration ``` -------------------------------- ### Configure Default NPM Registry Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/configuration.md Configure the default unscoped NPM registry for Bun using the `registries` input. A token can optionally be appended. ```yaml registries: | https://registry.npmjs.org/ ``` ```yaml registries: | https://registry.npmjs.org/|npm_token123 ``` -------------------------------- ### readVersionFromFile Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/utils.md Reads the Bun version from a specified project configuration file. ```APIDOC ## readVersionFromFile Read Bun version from a project configuration file. ```typescript function readVersionFromFile(file: string, silent?: boolean): string | undefined ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | file | string | Yes | — | File path relative to GITHUB_WORKSPACE (e.g., "package.json", ".bun-version") | | silent | boolean | No | false | Suppress warnings if file not found or parsing fails | ### Return Type Returns the version string if found and parsed successfully, otherwise undefined. ### Supported Files | File | Format | |------|--------| | package.json | `packageManager` field (e.g., "bun@1.0.0") or `engines.bun` | | .tool-versions | Line matching `bun ` | | .bumrc | Full file content as version | | .bun-version | Full file content as version | ### Behavior - Returns undefined if GITHUB_WORKSPACE environment variable is not set - Returns undefined if file parameter is empty - Returns undefined if file does not exist (warns unless silent=true) - Logs info message with found version - Logs warning for parsing errors (unless silent=true) - Trims whitespace from extracted version ### Example ```typescript import { readVersionFromFile } from './utils.js'; const version = readVersionFromFile('package.json', false); // Returns: "1.0.0" if packageManager or engines.bun is set const bunVersion = readVersionFromFile('.bun-version', true); // Returns: content of .bun-version file, no warnings ``` ``` -------------------------------- ### getArchitecture Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/utils.md Resolves the CPU architecture for Bun download URLs, with special handling for Windows ARM64. ```APIDOC ## getArchitecture Resolve CPU architecture for Bun download URL, with Windows ARM64 handling. ```typescript function getArchitecture(os: string, arch: string, version?: string): string ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | os | string | Yes | — | Operating system: "windows", "darwin", "linux" | | arch | string | Yes | — | CPU architecture from process.arch: "x64", "arm64", "aarch64" | | version | string | No | undefined | Bun version for ARM64 support checking | ### Return Type Returns normalized architecture string for Bun releases: "x64", "aarch64", "arm64", or other. ### Behavior - For Windows ARM64: if version < 1.3.10, returns "x64" with warning (falls back to emulation) - For ARM64 systems: normalizes "arm64" to "aarch64" - Otherwise returns arch unchanged - Logs warning if Windows ARM64 requires x64 emulation ### Example ```typescript import { getArchitecture } from './utils.js'; getArchitecture('linux', 'x64', '1.0.0'); // "x64" getArchitecture('darwin', 'arm64', '1.0.0'); // "aarch64" getArchitecture('windows', 'arm64', '1.3.10'); // "arm64" getArchitecture('windows', 'arm64', '1.3.9'); // "x64" (with warning) ``` ``` -------------------------------- ### Configure Profile Builds for Bun Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/implementation-details.md Appends a '-profile' suffix to download URLs when profiling is enabled. Used for generating debugging symbols and flame graphs. ```typescript const eprofile = encodeURIComponent(profile === true ? "-profile" : ""); // Generates "-profile" suffix in URL if enabled ``` -------------------------------- ### Matrix Testing with Different Versions Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/usage-examples.md Sets up Bun for matrix testing, allowing you to run tests against multiple specified Bun versions within a single job. ```yaml jobs: test: strategy: matrix: bun-version: ['1.0.0', '1.0.25', 'canary'] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 with: bun-version: ${{ matrix.bun-version }} - run: bun test ``` -------------------------------- ### writeBunfig Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/bunfig.md Creates or updates the bunfig.toml file with specified registry configurations. It handles validation, merging with existing configurations, and enforces constraints on global registries. ```APIDOC ## writeBunfig ### Description Creates or updates bunfig.toml with registry configurations. This function validates registry URLs, enforces the constraint of at most one global registry, and merges new configurations with any existing content in the bunfig.toml file. ### Method `writeBunfig(path: string, registries: Registry[]): void` ### Parameters #### Path Parameters - **path** (string) - Required - Absolute file path where bunfig.toml will be written - **registries** (Registry[]) - Required - Array of registry configurations to apply ### Behavior 1. **Early exit**: Returns immediately if registries array is empty (no file is modified) 2. **Validation**: Validates all registry URLs are valid URL format 3. **Enforcement**: Ensures at most one global (unscoped) registry; throws if multiple exist 4. **Merge**: Reads existing bunfig.toml if present and merges new registries 5. **Configuration**: Sets or updates install.registry and install.scopes in the TOML structure 6. **Write**: Writes merged configuration back to file with UTF-8 encoding ### Global Registry Constraint Only one registry can have an empty scope (global default registry). If multiple registries with empty scope are provided, an error is thrown. ### Scoped Registry Handling - Scopes without `@` prefix are automatically prefixed: "myorg" → "@myorg" - Scopes are normalized to lowercase - Existing scopes in bunfig.toml are preserved unless overridden - If no registries with scopes remain, the scopes section is removed from config ### Configuration Format Generated bunfig.toml structure: ```toml [install] # Global default registry (if provided) [install.registry] url = "https://registry.npmjs.org/" token = "optional_token" # Scoped registries [install.scopes] @myorg = { url = "https://registry.myorg.com/", token = "token" } ``` ### Throws - **Error**: "Invalid registry URL: {url}" if any registry URL is malformed - **Error**: "You can't have more than one global registry." if multiple registries have empty scope - **File system errors**: If unable to read or write the file ### Example ```typescript import { writeBunfig } from './bunfig.js'; const registries = [ { url: 'https://registry.npmjs.org/', scope: '' }, { url: 'https://npm.pkg.github.com/', scope: '@myorg', token: '$GITHUB_TOKEN' } ]; writeBunfig('/workspace/bunfig.toml', registries); // Creates or updates bunfig.toml with registry configuration ``` ### Logs - **Info**: "Writing bunfig.toml to '{path}'." when starting to write - **Info**: Error message if existing bunfig.toml cannot be parsed (continues with empty config) ``` -------------------------------- ### Cache Ignored Due to Unparsable Version URL Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/errors.md This log message indicates that the cache is being ignored because the downloaded Bun URL did not match the expected format, leading to a re-download. ```text "Could not parse expected version from URL: {url}. Ignoring cache." ``` -------------------------------- ### Re-downloading Bun Due to Version Mismatch in Cache Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/errors.md This warning signifies that the cached Bun version does not match the requested version, prompting a re-download of the correct version. ```text "Cached Bun version {version} does not match expected version {expected}. Re-downloading." ``` -------------------------------- ### Registry Configuration Format Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/README.md Defines the format for specifying NPM registries and optional authentication tokens. Supports multi-line entries and scoped registries. ```text REGISTRY_URL [|TOKEN] @SCOPE:REGISTRY_URL [|TOKEN] ``` -------------------------------- ### Read Bun Version from File Source: https://github.com/oven-sh/setup-bun/blob/main/_autodocs/api-reference/utils.md Reads the Bun version from various project configuration files like `package.json` or `.bun-version`. Use the `silent` option to suppress warnings for missing files or parsing errors. ```typescript import { readVersionFromFile } from './utils.js'; const version = readVersionFromFile('package.json', false); // Returns: "1.0.0" if packageManager or engines.bun is set const bunVersion = readVersionFromFile('.bun-version', true); // Returns: content of .bun-version file, no warnings ```