### Bundler Setup with esbuild Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Illustrates setting up the Chromium package with esbuild for efficient bundling. This is part of the bundler compatibility configuration. ```javascript // Example configuration for esbuild (esbuild.config.js) const esbuild = require('esbuild'); const chromium = require('@sparticuz/chromium'); esbuild.build({ entryPoints: ['src/index.js'], bundle: true, outfile: 'dist/bundle.js', external: chromium.getChromiumExternal(), // Crucial for externalizing Chromium // ... other esbuild options }).catch(() => process.exit(1)); ``` -------------------------------- ### Bundler Setup with Serverless-esbuild Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Configures Chromium for serverless environments using serverless-esbuild. This optimizes the deployment package size and build times. ```javascript // Example serverless.yml configuration snippet plugins: - serverless-esbuild custom: esbuild: bundle: true external: ['@sparticuz/chromium'] # Externalize Chromium # ... other esbuild options functions: myFunction: handler: src/handler.js # ... other function configurations ``` -------------------------------- ### Bundler Setup with Vite Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Shows how to configure Chromium with Vite, a modern frontend build tool. This ensures compatibility with Vite's bundling process. ```javascript // Example configuration for Vite (vite.config.js) import { defineConfig } from 'vite'; import chromium from '@sparticuz/chromium'; export default defineConfig({ build: { rollupOptions: { external: chromium.getChromiumExternal(), // Externalize Chromium }, }, }); ``` -------------------------------- ### Puppeteer Basic Setup Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Launch a browser instance using Puppeteer with @sparticuz/chromium for optimized execution. ```javascript import chromium from "@sparticuz/chromium"; import puppeteer from "puppeteer-core"; const browser = await puppeteer.launch({ args: await puppeteer.defaultArgs({ args: chromium.args, headless: "shell" }), executablePath: await chromium.executablePath(), headless: "shell" }); const page = await browser.newPage(); // ... use page ... await browser.close(); ``` -------------------------------- ### Install Chromium Locally with Playwright CLI Source: https://github.com/sparticuz/chromium/blob/master/README.md Use the Playwright CLI to install a local Chromium binary. This is a prerequisite for local development setups. ```bash npx playwright install chromium ``` -------------------------------- ### Playwright Basic Setup Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Launch a browser instance using Playwright with @sparticuz/chromium for optimized execution. ```javascript import chromium from "@sparticuz/chromium"; import { chromium as playwright } from "playwright-core"; const browser = await playwright.launch({ args: chromium.args, executablePath: await chromium.executablePath(), headless: true }); const context = await browser.newContext(); const page = await context.newPage(); // ... use page ... await browser.close(); ``` -------------------------------- ### Install @sparticuz/chromium-min Source: https://github.com/sparticuz/chromium/blob/master/README.md Install the minified version of @sparticuz/chromium if your deployment environment has size constraints. This package requires hosting the chromium-v#-pack.tar file separately. ```shell npm install --save @sparticuz/chromium-min@$CHROMIUM_VERSION ``` -------------------------------- ### Caching Strategy Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Details the caching strategy for Chromium binaries and related assets. This is crucial for optimizing cold start behavior in serverless environments. ```javascript const chromium = require('@sparticuz/chromium'); // The caching strategy is often managed by the package itself, leveraging Lambda layers or file system caching. // Ensure your deployment environment supports caching mechanisms effectively. console.log('Caching strategy is managed internally. Ensure Lambda layers or persistent storage are configured.'); ``` -------------------------------- ### Setup Lambda Environment Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Configure the Lambda environment by setting environment variables like FONTCONFIG_PATH and HOME, and updating LD_LIBRARY_PATH. ```javascript import { setupLambdaEnvironment } from "@sparticuz/chromium"; setupLambdaEnvironment("/tmp/al2023/lib"); // Sets: // - FONTCONFIG_PATH → /tmp/fonts (if not set) // - HOME → /tmp (if not set) // - LD_LIBRARY_PATH → prepend with /tmp/al2023/lib ``` -------------------------------- ### AWS Lambda Configuration Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Provides an example of configuring AWS Lambda for Chromium deployment, including memory, timeout, and layers. This is essential for serverless execution. ```yaml # Example serverless.yml configuration snippet service: my-chromium-app provider: name: aws runtime: nodejs18.x memorySize: 1024 # MB timeout: 60 # seconds layers: - arn:aws:lambda:us-east-1:123456789012:layer:chromium:1 # Example layer ARN functions: renderPage: handler: handler.js # ... other function configurations ``` -------------------------------- ### Download Pipeline Configuration Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Explains the configuration of the download pipeline for remote Chromium binaries. This includes handling URLs and ensuring integrity. ```javascript const chromium = require('@sparticuz/chromium'); // Configuration might involve specifying download URLs, retries, or proxy settings. // Example: Setting a custom download URL if needed. // process.env.CHROMIUM_DOWNLOAD_URL = 'https://example.com/chromium.tar.gz'; console.log('Download pipeline configuration involves setting environment variables or using specific options.'); ``` -------------------------------- ### Environment Setup for Lambda Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/ARCHITECTURE.md Details the steps for setting up the Lambda environment, including configuring FONTCONFIG_PATH, HOME, and LD_LIBRARY_PATH for native library loading. ```typescript setupLambdaEnvironment(baseLibPath): 1. FONTCONFIG_PATH ??= `/tmp/fonts` └─ Allows fontconfig library to locate fonts 2. HOME ??= `/tmp` └─ Provides writable home directory for Chromium 3. LD_LIBRARY_PATH setup: if (undefined) LD_LIBRARY_PATH = baseLibPath else if (!startsWith(baseLibPath)) LD_LIBRARY_PATH = `${baseLibPath}:${existing}` └─ Prepends lib path for native library loading ``` -------------------------------- ### Environment Detection Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Shows how the system detects the runtime environment. This is used to ensure compatibility and apply environment-specific configurations. ```javascript const chromium = require('@sparticuz/chromium'); // The library automatically detects the environment (e.g., Lambda, local). // You can check specific environments like Amazon Linux 2023: if (chromium.isRunningInAmazonLinux2023()) { console.log('Environment detected: Amazon Linux 2023'); } console.log('Environment detection is handled automatically by the package.'); ``` -------------------------------- ### Bundling with esbuild Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/errors.md Example command to bundle a JavaScript file with esbuild, marking @sparticuz/chromium as an external dependency to avoid issues in Lambda. ```bash esbuild --bundle --external:@sparticuz/chromium input.js ``` -------------------------------- ### Explicit Environment Setup Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Manually set up the Lambda environment, typically for Amazon Linux 2023, by specifying the base library path. ```javascript import { setupLambdaEnvironment } from "@sparticuz/chromium"; // Usually automatic, but can be explicit setupLambdaEnvironment("/tmp/al2023/lib"); ``` -------------------------------- ### Helper Functions Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Utility functions for common tasks such as environment setup, file decompression, and downloading. ```APIDOC ## setupLambdaEnvironment() ### Description Configures the Lambda environment for optimal Chromium execution. ### Method INVOKE ### Endpoint N/A (Function) ### Parameters None ### Response #### Success Response (200) - **status** (string) - Indicates successful configuration. ### Response Example ```json "Lambda environment configured successfully" ``` ## inflate() ### Description Decompresses Brotli or Gzip compressed data. ### Method INVOKE ### Endpoint N/A (Function) ### Parameters - **data** (Buffer) - Required - The compressed data buffer. - **encoding** (string) - Optional - The encoding type ('br' for Brotli, 'gz' for Gzip). ### Response #### Success Response (200) - **decompressedData** (Buffer) - The decompressed data. ### Response Example ```json "" ``` ## downloadFile() ### Description Downloads a file from a given URL. ### Method INVOKE ### Endpoint N/A (Function) ### Parameters - **url** (string) - Required - The URL of the file to download. - **destinationPath** (string) - Required - The local path to save the downloaded file. ### Response #### Success Response (200) - **message** (string) - Confirmation of successful download. ### Response Example ```json "File downloaded successfully to /path/to/destination" ``` ## downloadAndExtract() ### Description Downloads a file from a URL and extracts it if it is a tar archive. ### Method INVOKE ### Endpoint N/A (Function) ### Parameters - **url** (string) - Required - The URL of the file to download. - **destinationPath** (string) - Required - The directory to extract the contents into. ### Response #### Success Response (200) - **message** (string) - Confirmation of successful download and extraction. ### Response Example ```json "File downloaded and extracted successfully to /path/to/destination" ``` ``` -------------------------------- ### Explicitly Setup Lambda Environment Libraries Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/errors.md Demonstrates how to explicitly set up the Lambda environment for @sparticuz/chromium, particularly for older runtimes or specific library paths. ```javascript import { setupLambdaEnvironment } from "@sparticuz/chromium"; import { join } from "node:path"; import { tmpdir } from "node:os"; // Automatic on AL2023+, but can be explicit setupLambdaEnvironment(join(tmpdir(), "al2023", "lib")); ``` -------------------------------- ### Get Chromium Executable Path Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Retrieves the path to the Chromium executable. This is a core part of the initialization flow and binary extraction process. ```javascript const chromium = require('@sparticuz/chromium'); async function getChromium() { try { const executablePath = await chromium.executablePath; console.log('Chromium executable path:', executablePath); // Use this path to launch Chromium // const browser = await puppeteer.launch({ executablePath }); } catch (error) { console.error('Failed to get Chromium executable path:', error); } } getChromium(); ``` -------------------------------- ### Cache Strategy for Chromium Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/ARCHITECTURE.md Illustrates the cache strategy for Chromium, detailing the steps for both cold and warm invocations. Cold starts involve decompression and extraction, while warm starts leverage existing cached files for faster execution. ```text First invocation (cold start): 1. Check if /tmp/chromium exists → no 2. Decompress from bin/ 3. All files extracted to /tmp 4. Return /tmp/chromium Warm invocation (cached): 1. Check if /tmp/chromium exists → yes 2. Return immediately 3. Other invocations share /tmp state Lambda timing: - Cold start: extraction ~1s + browser launch ~2-5s = 3-6s total - Warm start: cached + browser launch ~2-5s = 2-5s total ``` -------------------------------- ### Install @sparticuz/chromium Source: https://github.com/sparticuz/chromium/blob/master/README.md Install the main @sparticuz/chromium package. Ensure your puppeteer-core version matches the supported Chromium version. ```shell # Puppeteer or Playwright is a production dependency npm install --save puppeteer-core@$PUPPETEER_VERSION # @sparticuz/chromium can be a DEV dependency IF YOU ARE USING A LAYER. If you are not using a layer, use it as a production dependency! npm install --save-dev @sparticuz/chromium@$CHROMIUM_VERSION ``` -------------------------------- ### Full Puppeteer Integration Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/api-reference/chromium.md A complete example demonstrating the usage of the Chromium class with Puppeteer, including launching the browser, navigating to a page, and closing the browser. ```javascript import chromium from "@sparticuz/chromium"; import puppeteer from "puppeteer-core"; async function main() { // Optional: Disable WebGL if needed // chromium.setGraphicsMode = false; const browser = await puppeteer.launch({ args: await puppeteer.defaultArgs({ args: chromium.args, headless: "shell" }), executablePath: await chromium.executablePath(), headless: "shell" }); try { const page = await browser.newPage(); await page.goto("https://example.com"); const title = await page.title(); console.log("Page title:", title); } finally { await browser.close(); } } main().catch(console.error); ``` -------------------------------- ### Full Playwright Integration Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/api-reference/chromium.md A complete example demonstrating the usage of the Chromium class with Playwright, including launching the browser, creating a new context and page, navigating, and closing the browser. ```javascript import chromium from "@sparticuz/chromium"; import { chromium as playwright } from "playwright-core"; async function main() { const browser = await playwright.launch({ args: chromium.args, executablePath: await chromium.executablePath(), headless: true }); try { const context = await browser.newContext(); const page = await context.newPage(); await page.goto("https://example.com"); const title = await page.title(); console.log("Page title:", title); } finally { await browser.close(); } } main().catch(console.error); ``` -------------------------------- ### Set Environment Variable Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Demonstrates setting environment variables like FONTCONFIG_PATH. This is often required for specific library configurations or runtime behaviors. ```javascript const chromium = require('@sparticuz/chromium'); // Set FONTCONFIG_PATH process.env.FONTCONFIG_PATH = '/path/to/fonts'; console.log('FONTCONFIG_PATH set.'); // Other variables like HOME, LD_LIBRARY_PATH can be set similarly. ``` -------------------------------- ### Setup Lambda Environment Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/api-reference/helper-functions.md Manually sets up the Lambda environment for Chromium. This is typically called automatically, but can be overridden if custom paths are needed. ```javascript // Automatic on AL2023+ import chromium from "@sparticuz/chromium"; // setupLambdaEnvironment is called automatically // Manual override if needed import { setupLambdaEnvironment } from "@sparticuz/chromium"; setupLambdaEnvironment("/custom/lib/path"); ``` -------------------------------- ### Get Binary Path Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Retrieves the binary directory path using getBinPath(). This is essential for locating Chromium executables or related files within the package. ```typescript import { getBinPath } from "@sparticuz/chromium"; const binPath = getBinPath(); console.log(`Chromium binary path: ${binPath}`); ``` -------------------------------- ### Using Full Package Variant Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Demonstrates using the full package variant of Chromium. This variant includes all necessary binaries and dependencies for broader compatibility. ```javascript const chromium = require('@sparticuz/chromium'); // Ensure you have installed the full package: npm install @sparticuz/chromium // Usage remains the same, but the full package is utilized. ``` -------------------------------- ### Handling Directory Not Found Error Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Illustrates how to handle 'Error: directory not found' which typically indicates bundler misconfiguration or missing files. ```javascript const chromium = require('@sparticuz/chromium'); try { // Code that might trigger this error, e.g., accessing a misconfigured path chromium.getBinPath(); } catch (error) { if (error.message.includes('directory not found')) { console.error('Bundler misconfiguration: Ensure Chromium is correctly installed and paths are set.'); // Suggest checking bundler config and installation } else { console.error('An unexpected error occurred:', error); } } ``` -------------------------------- ### Configure Chromium Flags Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Applies optimized Chromium flags for performance and security. This snippet shows how to set multiple flags. ```javascript const chromium = require('@sparticuz/chromium'); const flags = [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu', '--disable-dev-shm-usage', // ... add other optimized flags ]; chromium.setChromiumFlags(flags); console.log('Chromium flags configured.'); ``` -------------------------------- ### Performance Optimization Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Highlights performance optimizations related to memory and disk usage. This includes efficient binary extraction and decompression. ```javascript const chromium = require('@sparticuz/chromium'); // Optimizations are typically built into the library. // Ensure you are using the min package variant for reduced size if applicable. // Consider Lambda memory settings for optimal performance. console.log('Performance optimizations focus on efficient binary handling and resource management.'); ``` -------------------------------- ### Setup Lambda Environment with Default HOME Path Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/configuration.md Configure the Lambda environment using setupLambdaEnvironment, which defaults the HOME directory to '/tmp'. This is crucial for serverless functions as Chromium requires a writable directory for cache and preferences. ```javascript import { setupLambdaEnvironment } from "@sparticuz/chromium"; setupLambdaEnvironment("/tmp/al2023/lib"); // Sets HOME to /tmp (if not already set) console.log(process.env.HOME); // /tmp ``` -------------------------------- ### Build AWS SAM Project Source: https://github.com/sparticuz/chromium/blob/master/examples/aws-sam/README.md Builds the AWS SAM project. Ensure Docker is installed and running. ```sh sam build ``` -------------------------------- ### Named Exports Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/MODULE-EXPORTS.md Provides access to utility functions for environment setup and file inflation. ```APIDOC ## Named Exports ### Description Provides access to utility functions for environment setup and file inflation. ### Functions - **`setupLambdaEnvironment(baseLibPath: string): void`**: Sets up the Lambda environment. - **`inflate(filePath: string): Promise`**: Asynchronously inflates a file. ``` -------------------------------- ### Local Testing Setup and Execution Source: https://github.com/sparticuz/chromium/blob/master/_/ec2/README.md Set environment variables and run the build script on an EC2 instance for local testing. Ensure all required variables are exported before executing the script. ```bash export CHROMIUM_REVISION=1596535 export S3_BUCKET=your-bucket export GITHUB_PAT=ghp_xxx export GITHUB_REPO=owner/repo export PR_NUMBER=123 export AWS_DEFAULT_REGION=us-east-1 bash build-chromium.sh ``` -------------------------------- ### Decompression Pipeline Configuration Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Details the configuration of the decompression pipeline, focusing on stream handling and efficiency. This is relevant for how Chromium binaries are unpacked. ```javascript const chromium = require('@sparticuz/chromium'); // Configuration might involve setting stream options or choosing decompression methods. // Example: Ensuring proper stream handling during extraction. // const streamOptions = { highWaterMark: 1024 * 1024 }; // Example: 1MB chunks // chromium.configureDecompression(streamOptions); console.log('Decompression pipeline configuration is typically handled internally or via environment variables.'); ``` -------------------------------- ### Correct Symlink Creation Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/errors.md Ensure the source file exists before attempting to create a symlink. This example demonstrates creating a source file and then a symlink to it. ```javascript import { createSymlink } from "@sparticuz/chromium"; import { writeFileSync } from "node:fs"; // Create source file first writeFileSync("/tmp/source.txt", "content"); // Now create symlink await createSymlink("/tmp/source.txt", "/tmp/link.txt"); ``` -------------------------------- ### Runtime Detection Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Checks if the current environment is Amazon Linux 2023 using isRunningInAmazonLinux2023(). This is crucial for environment-specific configurations or behaviors. ```typescript import { isRunningInAmazonLinux2023 } from "@sparticuz/chromium"; if (isRunningInAmazonLinux2023()) { console.log("Running on Amazon Linux 2023"); } else { console.log("Not running on Amazon Linux 2023"); } ``` -------------------------------- ### Handling HTTP Download Errors Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Demonstrates how to catch and handle HTTP errors that may occur during resource downloads. This is important for network-related operations. ```javascript const chromium = require('@sparticuz/chromium'); try { // Simulate a download that might fail with an HTTP error await chromium.downloadChromium(); // Assuming this method can throw HTTP errors } catch (error) { if (error.response && error.response.status) { // Check for common HTTP error properties console.error(`HTTP error occurred: ${error.response.status} ${error.response.statusText}`); // Implement retry logic or inform the user about network issues } else { console.error('An unexpected error occurred during download:', error); } } ``` -------------------------------- ### Type Notation Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/INDEX.md Illustrates the type notation used in function signatures and tables within the documentation. This helps in understanding parameter types and return values. ```javascript // Parameter types in signatures function method(param: Type): ReturnType // Shorthand in tables string[] // Array of strings Promise // Promise resolving to type T ``` -------------------------------- ### Import Submodule for Advanced Usage Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Access specific functionalities from submodules, such as getting the binary path. ```javascript import { getBinPath } from "@sparticuz/chromium/source/paths.js"; ``` -------------------------------- ### Security Considerations Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Details security measures, such as disabled features and the rationale behind them. This is crucial for secure deployments, especially in serverless environments. ```javascript const chromium = require('@sparticuz/chromium'); // The package disables potentially insecure features by default. // Example: --no-sandbox and --disable-setuid-sandbox flags are often used. const defaultFlags = chromium.getChromiumFlags(); console.log('Security-related flags:', defaultFlags.filter(flag => flag.includes('sandbox'))); console.log('Security considerations involve disabling risky features and understanding the attack surface.'); ``` -------------------------------- ### Inflate Binary Implementation Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/ARCHITECTURE.md Details the step-by-step process for inflating binary files, including path determination, cache checks, format detection, stream setup, decompression, and event handling. It emphasizes memory efficiency through chunk size configuration. ```typescript inflate(filePath): Promise │ ├─ Step 1: Determine output path │ ├─ if (swiftshader) → output = /tmp │ └─ else → output = /tmp/{filename-without-ext} │ ├─ Step 2: Check cache │ ├─ if (swiftshader) && /tmp/libGLESv2.so exists → resolve(output) │ ├─ else if (output directory exists) → resolve(output) │ └─ else → continue │ ├─ Step 3: Detect format │ ├─ Regex: /\.(?:t(?:ar(?: .(?:br|gz))?|br|gz))?$/i │ │ │ ├─ Is Brotli? (.br extension) │ ├─ Is Gzip? (.gz extension) │ └─ Is Tar? (.tar.br, .tar.gz, .tar) │ ├─ Step 4: Setup streams │ ├─ source = createReadStream(filePath, {highWaterMark: 2^22}) │ │ └─ 4 MB chunks for memory efficiency │ │ │ ├─ if (isTar) │ │ └─ target = extract(output) [tar-fs] │ │ └─ Emits 'finish' event │ │ │ └─ else │ └─ target = createWriteStream(output, {mode: 0o700}) │ └─ Emits 'close' event │ ├─ Step 5: Setup decompression │ ├─ if (isBrotli) │ │ └─ decompressor = createBrotliDecompress({chunkSize: 2^21}) │ │ │ ├─ else if (isGzip) │ │ └─ decompressor = createUnzip({chunkSize: 2^21}) │ │ │ └─ else │ └─ no decompressor, pipe directly │ ├─ Step 6: Pipe streams │ ├─ source → decompressor → target │ │ OR │ └─ source → target [if no decompression] │ └─ Step 7: Event handling ├─ target: 'finish' or 'close' → resolve(output) └─ errors → reject with error ``` -------------------------------- ### Cross-Reference Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/INDEX.md Demonstrates the markdown format used for cross-referencing related sections within the documentation. This allows easy navigation between related topics. ```markdown See [Document Name](path/to/document.md#section) for details See [api-reference/chromium.md](api-reference/chromium.md#executablepath) ``` -------------------------------- ### Setup Lambda Environment Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/api-reference/helper-functions.md Configures environment variables for Chromium execution on AWS Lambda. This is usually called automatically but can be invoked manually. ```javascript import { setupLambdaEnvironment } from "@sparticuz/chromium"; import { join } from "node:path"; import { tmpdir } from "node:os"; // Manually setup Lambda environment (usually called automatically) setupLambdaEnvironment(join(tmpdir(), "al2023", "lib")); ``` -------------------------------- ### Binary Compression: Brotli vs. Gzip Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/ARCHITECTURE.md Compares Brotli and Gzip compression for Chromium binaries, highlighting Brotli's superior compression ratios and faster decompression times. This optimization is crucial for reducing deployment package size and improving cold start performance. ```text Raw chromium binary: 130 MB Brotli compressed: 38 MB (level 11) Compression ratio: 71.6% Decompression time: ~0.6 seconds vs. Gzip: Gzip compressed: 46 MB (level 9) Gzip decompression: 0.97 seconds Brotli wins on both size and speed ``` -------------------------------- ### Bundler Configuration for @sparticuz/chromium Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/errors.md Provides examples of how to configure webpack and esbuild to externalize @sparticuz/chromium, which is a common solution for 'Input Directory Does Not Exist' errors. ```javascript // webpack.config.js module.exports = { externals: ["@sparticuz/chromium"], }; ``` ```bash # esbuild esbuild --bundle --external:@sparticuz/chromium index.js ``` -------------------------------- ### Create GitHub Labels Source: https://github.com/sparticuz/chromium/blob/master/CONTRIBUTING.md These commands create the necessary labels for triggering and managing builds and tests within the GitHub repository. Ensure you have the GitHub CLI installed and authenticated. ```bash gh label create "binaries:build" --description "Trigger: start EC2 Chromium build" --color "0E8A16" gh label create "binaries:test" --description "Trigger: run tests against built binaries" --color "0E8A16" # Build state labels (managed by workflows) gh label create "binaries:needed" --description "Chromium binaries need to be built for this PR" --color "FBCA04" gh label create "binaries:building" --description "Chromium build in progress" --color "ededed" gh label create "binaries:available" --description "Chromium binaries ready in S3" --color "1D76DB" gh label create "binaries:testing" --description "Tests running against built binaries" --color "ededed" gh label create "binaries:verified" --description "Binaries built and tests passed" --color "0E8A16" gh label create "binaries:failed" --description "Chromium build or tests failed" --color "D93F0B" # Build option labels gh label create "build:on-demand" --description "Use on-demand EC2 pricing instead of spot" --color "D93F0B" gh label create "build:ssh" --description "Enable SSH + screen session on build instance" --color "0E8A16" ``` -------------------------------- ### Get Recommended Chromium Args Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/api-reference/chromium.md Retrieve an array of recommended Chromium flags optimized for serverless environments. These flags help in reducing memory footprint and disabling conflicting security features. ```javascript import chromium from "@sparticuz/chromium"; import puppeteer from "puppeteer-core"; const browser = await puppeteer.launch({ args: await puppeteer.defaultArgs({ args: chromium.args, headless: "shell" }), executablePath: await chromium.executablePath(), headless: "shell" }); ``` -------------------------------- ### Create Chromium Lambda Layer Source: https://github.com/sparticuz/chromium/blob/master/README.md Generates a zip file containing Chromium binaries for AWS Lambda. Ensure you have Git installed and clone the repository. ```shell archType="x64" && \ git clone --depth=1 https://github.com/sparticuz/chromium.git && \ cd chromium && \ make chromium.${archType}$\.zip ``` -------------------------------- ### Enable WebGL Graphics Mode Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Configures Chromium to enable WebGL graphics mode. This is useful for applications requiring hardware-accelerated graphics. ```javascript const chromium = require('@sparticuz/chromium'); // Enable WebGL chromium.setGraphicsMode(true); console.log('WebGL graphics mode enabled.'); ``` -------------------------------- ### Create Symbolic Link Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Creates a symbolic link using createSymlink(). This function is typically used for setting up executable paths or linking configuration files. ```typescript import { createSymlink } from "@sparticuz/chromium"; const targetPath = "/path/to/target"; const linkPath = "/path/to/symlink"; createSymlink(targetPath, linkPath) .then(() => console.log(`Symlink created from ${targetPath} to ${linkPath}`)) .catch(err => console.error("Failed to create symlink:", err)); ``` -------------------------------- ### Setup Lambda Environment with LD_LIBRARY_PATH Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/configuration.md Configure the Lambda environment by setting the LD_LIBRARY_PATH. This ensures that Chromium can locate necessary native libraries, especially when running on Amazon Linux 2023 where libraries are extracted to a specific path. ```javascript import { setupLambdaEnvironment } from "@sparticuz/chromium"; import { join } from "node:path"; import { tmpdir } from "node:os"; const libPath = join(tmpdir(), "al2023", "lib"); setupLambdaEnvironment(libPath); // If LD_LIBRARY_PATH was "/usr/lib" // It becomes "/tmp/al2023/lib:/usr/lib" console.log(process.env.LD_LIBRARY_PATH); ``` -------------------------------- ### Handling Decompression Errors Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Shows how to catch and handle decompression errors, such as 'ENOSPC' (No space left on device). This is relevant for file stream operations. ```javascript const chromium = require('@sparticuz/chromium'); try { // Assume a process that involves decompression, like extracting a file await someDecompressionProcess(); } catch (error) { if (error.code === 'ENOSPC') { console.error('Decompression failed: No space left on device. Please free up disk space.'); // Suggest freeing disk space or using a different storage location } else { console.error('An unexpected decompression error occurred:', error); } } ``` -------------------------------- ### Chromium Flags Architecture Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Illustrates the logic behind selecting and applying Chromium flags. This section focuses on the architecture of flag management for optimization and security. ```javascript const chromium = require('@sparticuz/chromium'); // The library applies a set of default optimized flags. // You can view or override these flags. const defaultFlags = chromium.getChromiumFlags(); console.log('Default Chromium flags:', defaultFlags); // Example of adding a custom flag: // chromium.addChromiumFlags(['--enable-features=MyFeature']); ``` -------------------------------- ### Concurrency Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Discusses handling concurrent operations with Chromium. This is important in environments like AWS Lambda where multiple requests might be processed in parallel. ```javascript const chromium = require('@sparticuz/chromium'); // To handle concurrency, ensure your application logic correctly manages multiple browser instances // or processes. The Chromium package itself is designed to be thread-safe. // Example: Launching multiple browser instances concurrently (conceptual) // Promise.all([ // puppeteer.launch({ executablePath: await chromium.executablePath }), // puppeteer.launch({ executablePath: await chromium.executablePath }) // ]).then(browsers => { // console.log('Launched multiple browser instances.'); // }); ``` -------------------------------- ### setupLambdaEnvironment(baseLibPath) Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Explicitly sets up the Lambda environment, configuring paths for fonts, home directory, and library loading. ```APIDOC ## setupLambdaEnvironment(baseLibPath) **Parameters:** `baseLibPath: string` **Returns:** `void` ```javascript import { setupLambdaEnvironment } from "@sparticuz/chromium"; setupLambdaEnvironment("/tmp/al2023/lib"); // Sets: // - FONTCONFIG_PATH → /tmp/fonts (if not set) // - HOME → /tmp (if not set) // - LD_LIBRARY_PATH → prepend with /tmp/al2023/lib ``` ``` -------------------------------- ### Local Development with Playwright Source: https://github.com/sparticuz/chromium/blob/master/README.md Configure Playwright to use a locally installed Chromium for development. Ensure Chromium is installed via Playwright's CLI. ```typescript import chromium from "@sparticuz/chromium"; import { chromium as playwright } from "playwright-core"; const isLocal = process.env.IS_LOCAL; const browser = await playwright.launch({ args: isLocal ? [] : chromium.args, executablePath: isLocal ? "/path/to/local/chromium" // e.g., from `npx playwright install chromium` : await chromium.executablePath(), headless: true, }); ``` -------------------------------- ### setupLambdaEnvironment Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/api-reference/helper-functions.md Manually sets up the Lambda environment. This is typically called automatically during Chromium class initialization but can be overridden if needed. ```APIDOC ## setupLambdaEnvironment ### Description Manually sets up the Lambda environment. This is typically called automatically during Chromium class initialization but can be overridden if needed. ### Signature ```javascript import { setupLambdaEnvironment } from "@sparticuz/chromium"; setupLambdaEnvironment("/custom/lib/path"); ``` ### Parameters #### Path Parameters - **libPath** (string) - Optional - Custom path to the library directory. ``` -------------------------------- ### Using @sparticuz/chromium-min with Remote Binaries Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/configuration.md Demonstrates how to use the minimal @sparticuz/chromium-min package by specifying the location of the pre-compressed binary files via a remote URL. This is useful for size-constrained deployments or ARM64 support. ```javascript import chromium from "@sparticuz/chromium-min"; // Use Brotli files from S3 const binary = await chromium.executablePath( "https://my-bucket.s3.amazonaws.com/chromium-pack.tar" ); ``` -------------------------------- ### Get Remote Executable Path Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Retrieve the path to a Chromium binary from a remote HTTPS URL. ```javascript // Remote URL (HTTPS) await chromium.executablePath("https://example.com/chromium-pack.tar") ``` -------------------------------- ### Get Default Executable Path Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Retrieve the default path to the Chromium binary included with the package. ```javascript // Default (built-in bin/) await chromium.executablePath() ``` -------------------------------- ### Create and Upload Lambda Layer Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Steps to clone the Chromium repository, build a Lambda-compatible zip file, and publish it as a Lambda layer. Ensure you specify compatible runtimes and architectures. ```bash # Create layer with chromium binaries git clone https://github.com/Sparticuz/chromium.git cd chromium make chromium.x64.zip # Upload to AWS aws lambda publish-layer-version \ --layer-name chromium-149 \ --zip-file fileb://chromium.x64.zip \ --compatible-runtimes nodejs22.x nodejs24.x \ --compatible-architectures x86_64 ``` -------------------------------- ### SSH into Build Instance Source: https://github.com/sparticuz/chromium/blob/master/CONTRIBUTING.md Connects to the build instance via SSH using the generated private key. Replace with the actual IP address of the build instance. ```bash ssh -i ~/.ssh/chromium-build root@ ``` -------------------------------- ### Get Localhost Executable Path Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Retrieve the path to a Chromium binary served from a local testing server. ```javascript // Localhost for testing await chromium.executablePath("http://localhost:3000/pack.tar") ``` -------------------------------- ### Get Custom Executable Path Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Retrieve the path to a Chromium binary located in a specified local directory. ```javascript // Local path await chromium.executablePath("/opt/chromium") ``` -------------------------------- ### Direct Import: Helper Functions Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/MODULE-EXPORTS.md Shows how to import all helper functions directly from the main module or specifically from the submodule. ```javascript import { createSymlink, downloadFile, setupLambdaEnvironment, isValidUrl, isRunningInAmazonLinux2023, downloadAndExtract } from "@sparticuz/chromium"; // Or from submodule import { createSymlink, downloadFile, setupLambdaEnvironment, isValidUrl, isRunningInAmazonLinux2023, downloadAndExtract } from "@sparticuz/chromium/source/helper.js"; ``` -------------------------------- ### Correct Usage of Chromium.executablePath Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/errors.md Demonstrates the correct ways to use Chromium.executablePath, including default usage, specifying a local path, and providing a remote URL. ```javascript import chromium from "@sparticuz/chromium"; // ✓ Default — uses internal bin directory const binary = await chromium.executablePath(); // ✓ Valid local path with min package const binary = await chromium.executablePath("/opt/chromium"); // ✓ Remote URL const binary = await chromium.executablePath( "https://example.com/chromium-pack.tar" ); ``` -------------------------------- ### setupLambdaEnvironment Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/api-reference/helper-functions.md Configures environment variables required for Chromium execution on AWS Lambda and compatible platforms. It initializes FONTCONFIG_PATH, HOME, and LD_LIBRARY_PATH. ```APIDOC ## setupLambdaEnvironment ### Description Configures environment variables necessary for Chromium to function in Lambda and serverless containers. This function is typically called automatically during module initialization on compatible runtimes. ### Signature ```typescript setupLambdaEnvironment(baseLibPath: string): void ``` ### Parameters #### Path Parameters - **baseLibPath** (string) - Yes - Path to the lib directory containing native libraries ### Returns `void` ### Description Initializes environment variables: FONTCONFIG_PATH, HOME, and LD_LIBRARY_PATH to ensure Chromium runs correctly in serverless environments. ### Example ```javascript import { setupLambdaEnvironment } from "@sparticuz/chromium"; import { join } from "node:path"; import { tmpdir } from "node:os"; // Manually setup Lambda environment (usually called automatically) setupLambdaEnvironment(join(tmpdir(), "al2023", "lib")); ``` ``` -------------------------------- ### Puppeteer with Local or Remote Chromium Source: https://github.com/sparticuz/chromium/blob/master/README.md Launches Puppeteer, dynamically selecting between a local Chromium installation or the Sparticuz/Chromium package based on an environment variable. ```javascript const viewport = { deviceScaleFactor: 1, hasTouch: false, height: 1080, isLandscape: true, isMobile: false, width: 1920, }; const headlessType = process.env.IS_LOCAL ? false : "shell"; const browser = await puppeteer.launch({ args: process.env.IS_LOCAL ? await puppeteer.defaultArgs() : await puppeteer.defaultArgs({ args: chromium.args, headless: headlessType }), defaultViewport: viewport, executablePath: process.env.IS_LOCAL ? "/tmp/localChromium/chromium/linux-1122391/chrome-linux/chrome" : await chromium.executablePath(), headless: headlessType, }); ``` -------------------------------- ### Puppeteer with -min Package and Remote Brotli Files Source: https://github.com/sparticuz/chromium/blob/master/README.md Launches Puppeteer using the -min package, downloading Brotli files from a specified URL. Subsequent runs utilize cached files for faster startup. ```javascript const viewport = { deviceScaleFactor: 1, hasTouch: false, height: 1080, isLandscape: true, isMobile: false, width: 1920, }; const browser = await puppeteer.launch({ args: await puppeteer.defaultArgs({ args: chromium.args, headless: "shell" }), defaultViewport: viewport, executablePath: await chromium.executablePath( "https://www.example.com/chromiumPack.tar", ), headless: "shell", }); ``` -------------------------------- ### URL Validation Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Demonstrates how to validate a URL using the isValidUrl() method. This is useful for ensuring that input URLs are correctly formatted before processing. ```typescript import { isValidUrl } from "@sparticuz/chromium"; const url = "https://example.com"; const isValid = isValidUrl(url); console.log(`Is ${url} valid? ${isValid}`); ``` -------------------------------- ### Puppeteer with -min Package and Local Brotli Files Source: https://github.com/sparticuz/chromium/blob/master/README.md Launches Puppeteer using the -min package, requiring manual specification of the Brotli file path. Assumes Brotli files are located in /opt/chromium. ```javascript const viewport = { deviceScaleFactor: 1, hasTouch: false, height: 1080, isLandscape: true, isMobile: false, width: 1920, }; const browser = await puppeteer.launch({ args: await puppeteer.defaultArgs({ args: chromium.args, headless: "shell" }), defaultViewport: viewport, executablePath: await chromium.executablePath("/opt/chromium"), headless: "shell", }); ``` -------------------------------- ### Direct Import: inflate Function Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/MODULE-EXPORTS.md Demonstrates importing the inflate function either from the main module or directly from the lambdafs submodule. ```javascript import { inflate } from "@sparticuz/chromium"; // Or from submodule import { inflate } from "@sparticuz/chromium/source/lambdafs.js"; ``` -------------------------------- ### Module Load Time Initialization Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/ARCHITECTURE.md Code executed upon importing @sparticuz/chromium to configure the Lambda/Vercel/Netlify environment by setting up the Lambda environment if running on Amazon Linux 2023. ```typescript // source/index.ts (lines 14-21) const nodeMajorVersion = Number.parseInt( process.versions.node.split(".")[0] ?? "" ); if (isRunningInAmazonLinux2023(nodeMajorVersion)) { setupLambdaEnvironment(join(tmpdir(), "al2023", "lib")); } ``` -------------------------------- ### Bundler Behavior Comparison Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/ARCHITECTURE.md Illustrates the difference in how a bundler handles the @sparticuz/chromium package with and without the 'external' flag, highlighting path resolution and accessibility issues. ```text Bundler WITHOUT external: @sparticuz/chromium ├─ Relocates source/ to ├─ Breaks relative path in getBinPath() └─ bin/ directory not found → error Bundler WITH external: @sparticuz/chromium ├─ Left untouched in node_modules ├─ Relative paths work correctly └─ bin/ accessible from original location ``` -------------------------------- ### Get Chromium Executable Path (Default) Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/api-reference/chromium.md Retrieves the path to the Chromium binary using the default internal 'bin/' directory. Recommended for most use cases. ```javascript import chromium from "@sparticuz/chromium"; import puppeteer from "puppeteer-core"; const browser = await puppeteer.launch({ args: chromium.args, executablePath: await chromium.executablePath(), headless: "shell" }); ``` -------------------------------- ### Type Safety with TypeScript Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Demonstrates the use of TypeScript definitions for type safety. This improves code quality and maintainability by catching type errors during development. ```typescript import { isValidUrl, ChromiumOptions } from "@sparticuz/chromium"; const url: string = "https://example.com"; const isValid: boolean = isValidUrl(url); const options: ChromiumOptions = { args: ['--no-sandbox'], executablePath: "/path/to/chromium", }; console.log(`URL validation result: ${isValid}`); console.log('Chromium options:', options); ``` -------------------------------- ### Import Default and Common Helpers Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Import the default Chromium instance and frequently used helper functions. ```javascript import chromium, { setupLambdaEnvironment, inflate } from "@sparticuz/chromium"; ``` -------------------------------- ### Use Custom Binary Location Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Point to a local directory containing the Chromium binary, such as when using @sparticuz/chromium-min. ```javascript import chromium from "@sparticuz/chromium"; // Use @sparticuz/chromium-min with local files const binary = await chromium.executablePath("/opt/chromium"); ``` -------------------------------- ### Invoke AWS Lambda Function Locally Source: https://github.com/sparticuz/chromium/blob/master/examples/aws-sam/README.md Invokes an AWS Lambda function locally using AWS SAM. This example connects to a website and returns its title. ```sh sam local invoke ExampleFunction ``` -------------------------------- ### Bundler Compatibility Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Explains why externalizing the Chromium package is required for bundlers like webpack and esbuild. This prevents issues with large package sizes and native modules. ```javascript const chromium = require('@sparticuz/chromium'); // When using bundlers, ensure Chromium is externalized: // webpack.config.js: // module.exports = { // externals: chromium.getChromiumExternal(), // }; console.log('Externalizing Chromium is necessary for bundler compatibility.'); ``` -------------------------------- ### AWS Lambda Specific Error Handling Example Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/_DOCUMENTATION-SUMMARY.txt Illustrates handling Lambda-specific errors, such as issues with AL2023 libraries or timeouts. This requires understanding the Lambda execution environment. ```javascript const chromium = require('@sparticuz/chromium'); // Example handler function in AWS Lambda exports.handler = async (event) => { try { // Code that might interact with Chromium and potentially cause Lambda-specific errors await chromium.executablePath(); } catch (error) { if (error.message.includes('timeout')) { console.error('Lambda execution timed out. Increase the timeout setting.'); } else if (error.message.includes('AL2023')) { console.error('AL2023 library issue detected. Ensure compatibility.'); } else { console.error('An unexpected Lambda error occurred:', error); } // Return an error response return { statusCode: 500, body: JSON.stringify('Internal Server Error') }; } // Return success response return { statusCode: 200, body: JSON.stringify('Success') }; }; ``` -------------------------------- ### Create a Symbolic Link Source: https://github.com/sparticuz/chromium/blob/master/_autodocs/QUICK-REFERENCE.md Asynchronously creates a symbolic link from a source path to a target path. This is useful for setting up executable paths. ```javascript import { createSymlink } from "@sparticuz/chromium"; await createSymlink("/tmp/chromium", "/app/browser"); ```