### Local Development: Preview Static Site with Simulated KV Store Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.short.md These commands set up a local development environment for previewing static sites. They involve installing dependencies, publishing files to a simulated local KV Store, and starting a local server for preview. ```sh cd compute-js npm install npm run dev:publish # 'publish' your files to the simulated local KV Store npm run dev:start # preview locally ``` -------------------------------- ### Quick Start: Publish Static Site to Fastly KV Store Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.short.md This command initiates the process of publishing static files to a specified Fastly KV Store. It requires the root directory containing the static files and the name of the KV store to use. ```sh npx @fastly/compute-js-static-publish@latest --root-dir=./public --kv-store-name=site-content ``` -------------------------------- ### Configure Publish Content File Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Example `publish-content.config.js` file for configuring publishing behavior and server runtime settings. Includes root directory, exclusions, compression, content types, and server-specific options like SPA fallback and 404 pages. ```javascript // publish-content.config.js /** @type {import('@fastly/compute-js-static-publish').PublishContentConfig} */ const config = { // Directory containing static files (relative to this config) rootDir: '../public', // Directories to exclude from publishing excludeDirs: ['node_modules', '.git', 'src'], // Exclude dotfiles (default: true) excludeDotFiles: true, // Include .well-known even if dotfiles excluded (default: true) includeWellKnown: true, // Custom inclusion test for fine-grained control kvStoreAssetInclusionTest: (assetKey, contentType) => { // Exclude large video files if (assetKey.endsWith('.mp4') || assetKey.endsWith('.webm')) { return false; } return true; }, // Compression formats to pre-generate (default: ['br', 'gzip']) contentCompression: ['br', 'gzip'], // Custom content type definitions contentTypes: [ { test: /\.custom$/, contentType: 'application/x-custom', text: false }, { test: /\.wasm$/, contentType: 'application/wasm', text: false }, ], // Server runtime settings (saved to KV Store per collection) server: { // Public directory prefix for URL resolution publicDirPrefix: '', // SPA fallback file for client-side routing spaFile: '/index.html', // Custom 404 page notFoundPageFile: '/404.html', // Index file resolution autoIndex: ['index.html', 'index.htm'], // Extension resolution (e.g., /about -> /about.html) autoExt: ['.html', '.htm'], // Directories with long cache TTL (immutable assets) staticItems: ['/static/', '/assets/', '/_next/'], // Allowed compression formats to serve allowedEncodings: ['br', 'gzip'], }, }; export default config; ``` -------------------------------- ### Integrate PublisherServer in Custom Compute Apps Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Example of integrating PublisherServer into a custom Fastly Compute JS application. This allows serving static assets managed by PublisherServer and then falling back to custom request handling logic for APIs or other dynamic content. ```js import { PublisherServer } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)); }); async function handleRequest(request) { const response = await publisherServer.serveRequest(request); if (response) { return response; } // Add your custom logic here if (request.url.endsWith('/api/hello')) { return new Response(JSON.stringify({ greeting: "hi" }), { headers: { 'content-type': 'application/json' } }); } return new Response("Not Found", { status: 404 }); } ``` -------------------------------- ### Subdomain-Based Collection Routing (Compute JS) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Example of routing requests to specific collections based on subdomain patterns. It uses `collectionSelector.fromHostDomain` to extract the collection name from the request host. ```js import { PublisherServer, collectionSelector } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", event => { const request = event.request; const collectionName = collectionSelector.fromHostDomain(request, /^preview-([^.]*)\./); if (collectionName != null) { publisherServer.setActiveCollectionName(collectionName); } event.respondWith(publisherServer.serveRequest(request)); }); ``` -------------------------------- ### Configure Static Publish RC File Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Example `static-publish.rc.js` file defining core application settings baked into the Wasm binary. Includes KV store name, default collection, publish ID, and working directory. Changes require rebuilding and redeploying. ```javascript // static-publish.rc.js /** @type {import('@fastly/compute-js-static-publish').StaticPublishRc} */ const rc = { // Name of KV Store to use for content storage kvStoreName: 'site-content', // Default collection to serve when none specified defaultCollectionName: 'live', // Unique prefix for all KV Store keys (for multi-app sharing) publishId: 'default', // Directory for working files during publish staticPublisherWorkingDir: './static-publisher', }; export default rc; ``` -------------------------------- ### Access Published Asset Metadata Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Example of how to retrieve metadata for a published asset using PublisherServer. This allows developers to inspect details like content type, last modified time, size, hash, and available variants of a file served from KV Store. ```js const asset = await publisherServer.getMatchingAsset('/index.html'); if (asset != null) { // Asset exists with that path asset.contentType; // e.g., 'text/html' asset.lastModifiedTime; // Unix timestamp asset.size; // Size in bytes of the base version asset.hash; // SHA256 hash of base version asset.variants; // Available variants (e.g., ['gzip']) } ``` -------------------------------- ### Configure Content Publishing and Server Settings (JS) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Sets up detailed configuration for publishing content and runtime server behavior. It includes root directory, include/exclude filters, content compression options, custom content types, and server-specific settings like SPA file and 404 page. ```javascript const config = { // these paths are relative to compute-js dir rootDir: '../public', // Include/exclude filters (optional): excludeDirs: ['node_modules'], excludeDotfiles: true, includeWellKnown: true, // Advanced filtering (optional): kvStoreAssetInclusionTest: (key, contentType) => { return true; // include everything by default }, // Override which compressed variants to create for each asset during publish (optional): contentCompression: ['br', 'gzip'], // Content type definitions/overrides (optional): contentTypes: [ { test: /\.custom$/, contentType: 'application/x-custom', text: false }, ], // Server settings server: { publicDir: './public', spaFile: '/spa.html', notFoundPageFile: '/404.html', autoIndex: ['index.html'], autoExt: ['.html'], staticItems: ['/static/', '/assets/'], allowedEncodings: ['br', 'gzip'], } }; export default config; ``` -------------------------------- ### Deploy Compute App and Publish Static Content Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Commands to build, deploy a Compute app to Fastly, and publish static files to KV Store. The deploy command builds the app into a Wasm binary and creates a new or updates an existing Fastly Compute service. The publish command uploads static files to KV Store, using the default collection or a specified one. ```sh npm run fastly:deploy npm run fastly:publish npm run fastly:publish -- --collection-name=preview-42 ``` -------------------------------- ### Scaffold New Compute App (CLI) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Scaffolds a new Fastly Compute JS application for serving static files. This command initializes the project structure and configuration files, including setting up the KV Store name and other build-related options. ```bash npx @fastly/compute-js-static-publish@latest \ --root-dir=./public \ --kv-store-name=site-content \ [--output=./compute-js] \ [--static-publisher-working-dir=/static-publisher] \ [--publish-id=] \ [--public-dir=./public] \ [--static-dir=./public/static] \ [--spa=./public/spa.html] \ [--not-found-page=./public/404.html] \ [--auto-index=index.html,index.htm] \ [--auto-ext=.html,.htm] \ [--name=my-site] \ [--description='My Compute static site'] \ [--author='you@example.com'] \ [--service-id=your-fastly-service-id] ``` -------------------------------- ### Scaffold Fastly Compute Application with Static Publishing (CLI) Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Scaffolds a new Fastly Compute application pre-configured for static publishing. It sets up the necessary directory structure, configuration files, and basic project files. Key options include specifying the root directory for static assets, the KV store name, and output directory for the Compute project. ```bash npx @fastly/compute-js-static-publish@latest \ --root-dir=./public \ --kv-store-name=site-content npx @fastly/compute-js-static-publish@latest \ --root-dir=./public \ --kv-store-name=site-content \ --output=./compute-js \ --name=my-site \ --description="My Compute static site" \ --author="you@example.com" \ --public-dir=./public \ --static-dir=./public/static \ --spa=./public/index.html \ --not-found-page=./public/404.html \ --auto-index=index.html,index.htm \ --auto-ext=.html,.htm \ --service-id=your-fastly-service-id # Output structure created: # compute-js/ # ├── fastly.toml # ├── package.json # ├── static-publish.rc.js # ├── publish-content.config.js # └── src/index.js ``` -------------------------------- ### Local Development Publish (npm script) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Publish assets to a simulated local KV Store for development. This command writes to `kvstore.json` and is a prerequisite for running the local development server. ```sh npm run dev:publish ``` -------------------------------- ### Promote Collection (CLI) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Promote a collection to another, typically from staging or preview to live. This command copies content and settings. An optional expiration can be set for the target collection. ```sh npx @fastly/compute-js-static-publish collections promote \ --collection-name=staging \ --to=live ``` ```sh npx @fastly/compute-js-static-publish collections promote \ --collection-name=preview-42 \ --to=staging \ --expires-in=7d ``` -------------------------------- ### Configure Static Publisher Settings (JS) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Defines essential settings for the static publisher, including the KV store name, default collection, publish ID, and working directory. These settings are baked into the Compute app's Wasm binary and require a rebuild upon change. ```javascript const rc = { kvStoreName: 'site-content', defaultCollectionName: 'live', publishId: 'default', staticPublisherWorkingDir: './static-publisher', }; export default rc; ``` -------------------------------- ### Publish Content to KV Store (CLI) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Publishes static files from a local directory to a named collection in the Fastly KV Store or a local development directory. It automatically skips files that haven't changed and allows configuration of expiration times and API tokens. ```bash npx @fastly/compute-js-static-publish publish-content \ [--root-dir=./public] \ [--collection-name=preview-42] \ [--config=./publish-content.config.js] \ [--expires-in=7d | --expires-at=2025-05-01T12:00Z | --expires-never] \ [--local] \ [--fastly-api-token=...] ``` -------------------------------- ### Promote Collections Between Environments (CLI) Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Copies content and server configuration from one collection to another, facilitating promotion workflows (e.g., staging to live). Allows setting new expiration times for the target collection or setting it to never expire. Supports local development environment operations. ```bash # Promote staging collection to live npx @fastly/compute-js-static-publish collections promote \ --collection-name=staging \ --to=live # Promote preview to staging with new expiration npx @fastly/compute-js-static-publish collections promote \ --collection-name=preview-42 \ --to=staging \ --expires-in=7d # Promote and set to never expire npx @fastly/compute-js-static-publish collections promote \ --collection-name=staging \ --to=live \ --expires-never # Promote in local development environment npx @fastly/compute-js-static-publish collections promote \ --collection-name=preview-123 \ --to=staging \ --local ``` -------------------------------- ### JavaScript: Multi-Environment Preview System with Fastly Compute JS Source: https://context7.com/fastly/compute-js-static-publish/llms.txt This JavaScript code implements a multi-environment preview system for Fastly Compute JS Static Publish. It uses collection selectors to prioritize content based on cookies, subdomains, and headers. It also serves static content and provides an API endpoint for health checks. Dependencies include '@fastly/js-compute' and '@fastly/compute-js-static-publish'. ```javascript /// import { env } from 'fastly:env'; import { PublisherServer, collectionSelector } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const request = event.request; console.log('FASTLY_SERVICE_VERSION', env('FASTLY_SERVICE_VERSION')); // Priority 1: Handle cookie-based preview activation/reset const { collectionName: cookieCollection, redirectResponse } = collectionSelector.fromCookie(request); if (redirectResponse) { return redirectResponse; } // Priority 2: Subdomain-based collection (preview-*.example.com) const subdomainCollection = collectionSelector.fromHostDomain( request, /^preview-([^.]+)\./ ); // Priority 3: Header-based collection (X-Preview-Collection) const headerCollection = collectionSelector.fromRequest( request, (req) => req.headers.get('X-Preview-Collection') ); // Apply first non-null collection const activeCollection = subdomainCollection ?? cookieCollection ?? headerCollection; if (activeCollection != null) { publisherServer.setActiveCollectionName(activeCollection); console.log(`Serving collection: ${activeCollection}`); } // Serve static content const response = await publisherServer.serveRequest(request); if (response != null) { return response; } // API endpoints const url = new URL(request.url); if (url.pathname === '/api/health') { return new Response(JSON.stringify({ status: 'ok', collection: activeCollection ?? rc.defaultCollectionName }), { headers: { 'content-type': 'application/json' } }); } return new Response('Not found', { status: 404 }); } ``` -------------------------------- ### Publish Content to a Specific Collection (Shell) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Demonstrates how to publish content to a named collection using the `publish-content` command. This command allows specifying collection name, expiration time, and a custom configuration file. ```shell npx @fastly/compute-js-static-publish publish-content \ --collection-name=staging \ --expires-in=7d \ --config=./publish-content.config.js ``` -------------------------------- ### Preview Cleanup Operations Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Command to simulate cleanup operations without making any actual changes to the KV Stores. This allows users to preview which files would be deleted, ensuring that critical data is not accidentally removed. ```sh npx @fastly/compute-js-static-publish clean --dry-run ``` -------------------------------- ### Select Collection from Fastly Config Store in JavaScript Source: https://context7.com/fastly/compute-js-static-publish/llms.txt This snippet shows how to select a collection using Fastly's Config Store, enabling centralized configuration management. The `fromConfigStore` function retrieves the collection name from a specified store and key, allowing for dynamic updates without redeploying the service. ```javascript import { PublisherServer, collectionSelector } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const request = event.request; // Read collection name from Fastly Config Store // Useful for feature flags or centralized deployment control const collectionName = collectionSelector.fromConfigStore( 'my-config-store', // Config Store name 'active-collection' // Key name ); if (collectionName != null) { publisherServer.setActiveCollectionName(collectionName); } return publisherServer.serveRequest(request) ?? new Response('Not found', { status: 404 }); } // Config Store can be updated via Fastly API without redeploying: // fastly config-store-entry update --store-id=xxx --key=active-collection --value=staging ``` -------------------------------- ### Publish to Alternative Collection (npm script) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Publish assets to a specific, non-default collection name in the local simulated KV Store during development. ```sh npm run dev:publish -- --collection-name=preview-123 ``` -------------------------------- ### PublisherServer: Basic Usage in Fastly Compute JS Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Demonstrates the basic usage of PublisherServer to serve static content within a Fastly Compute application. It initializes the server from a configuration and handles incoming fetch events, serving static files or custom API responses. ```javascript /// import { PublisherServer } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; // Create server instance from config const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const request = event.request; // Serve static content (returns null if not found) const response = await publisherServer.serveRequest(request); if (response != null) { return response; } // Handle API routes or other custom logic const url = new URL(request.url); if (url.pathname.startsWith('/api/')) { return handleApiRequest(request); } // Final fallback return new Response('Not found', { status: 404 }); } async function handleApiRequest(request) { return new Response(JSON.stringify({ message: 'Hello API' }), { headers: { 'content-type': 'application/json' } }); } ``` -------------------------------- ### List Published Collections in KV Store (CLI) Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Lists all collections currently published in the KV Store, displaying their metadata such as publish time and expiration status. Supports listing from both the Fastly KV Store and a local simulated KV Store. ```bash # List collections in Fastly KV Store npx @fastly/compute-js-static-publish collections list # List collections in local simulated KV Store npx @fastly/compute-js-static-publish collections list --local # Example output: # 📃 Listing collections... # Working on the Fastly KV Store... # Found collections: # live * # Published : Mon May 05 2025 10:30:00 GMT+0000 # Expiration : not set # staging # Published : Mon May 05 2025 09:00:00 GMT+0000 # Expiration : Mon May 12 2025 09:00:00 GMT+0000 # preview-42 # Published : Sun May 04 2025 15:00:00 GMT+0000 # Expiration : Sun May 04 2025 22:00:00 GMT+0000 # 🚮 EXPIRED - Use 'clean --delete-expired-collections' to remove ``` -------------------------------- ### Promote Collection to New Name with Expiration in Fastly KV Store Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md The `collections promote` command copies an existing collection, including its content and configuration, to a new collection name. It requires `--collection-name` for the source and `--to` for the target. Expiration can be set using `--expires-in`, `--expires-at`, or `--expires-never`. If no expiration is specified, the original collection's expiration is preserved. Global options `--local` and `--fastly-api-token` are supported. ```sh npx @fastly/compute-js-static-publish collections promote \ --collection-name=preview-42 \ --to=live \ [--expires-in=7d | --expires-at=2025-06-01T00:00Z | --expires-never] ``` -------------------------------- ### Production Deployment: Deploy and Publish Static Site to Fastly Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.short.md These commands are used for deploying a static site to Fastly production. The first command deploys the Compute@Edge application, and the second uploads the static files to the configured KV Store. Subsequent uploads only require the publish command. ```sh cd compute-js npm run fastly:deploy # deploy the app npm run fastly:publish # upload your static files ``` ```sh cd compute-js npm run fastly:publish # upload your static files ``` -------------------------------- ### Select Collection from Fastly Config Store (Compute JS) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Retrieve a collection name from a Fastly Config Store using a specified store name and key. ```js collectionSelector.fromConfigStore('my-config-store', 'collection-key'); ``` -------------------------------- ### Load File from KV Store (JavaScript) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Loads a file variant from the KV Store. It returns an object containing the KV Store entry, size, hash, content encoding, and chunk information. The KV Store entry's body can be streamed or read as text, JSON, or an ArrayBuffer. ```javascript const kvAssetVariant = await publisherServer.loadKvAssetVariant(asset, null); // pass 'gzip' or 'br' for compressed kvAssetVariant.kvStoreEntry; // KV Store entry (type KVStoreEntry defined in 'fastly:kv-store') kvAssetVariant.size; // Size of the variant kvAssetVariant.hash; // SHA256 of the variant kvAssetVariant.contentEncoding; // 'gzip', 'br', or null kvAssetVariant.numChunks; // Number of chunks (for large files) ``` -------------------------------- ### Publish Static Content to Fastly KV Store (CLI) Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Publishes local static files to a named collection within the Fastly KV Store or a local development environment. Supports setting expiration times (relative or absolute) and overwriting existing content. Can also use a custom configuration file. ```bash # Publish to default collection npx @fastly/compute-js-static-publish publish-content # Publish to a specific collection with expiration npx @fastly/compute-js-static-publish publish-content \ --collection-name=preview-42 \ --expires-in=7d # Publish to local development KV Store npx @fastly/compute-js-static-publish publish-content --local # Publish with absolute expiration timestamp npx @fastly/compute-js-static-publish publish-content \ --collection-name=staging \ --expires-at=2025-05-01T00:00:00Z # Publish with custom config file and forced overwrite npx @fastly/compute-js-static-publish publish-content \ --config=./custom-config.js \ --root-dir=./dist \ --kv-overwrite # Using npm scripts (from scaffolded project) npm run dev:publish # Local development npm run fastly:publish # Production npm run fastly:publish -- --collection-name=staging ``` -------------------------------- ### Select Collection by Host Domain (JavaScript) Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Selects a deployment collection based on subdomain patterns in the request's host. This is useful for managing branch or preview deployments. It takes the request object and a regular expression to match the subdomain. The matched group from the regex is used as the collection name. ```javascript import { PublisherServer, collectionSelector } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const request = event.request; // Match subdomain pattern: preview-pr-123.example.com -> collection 'pr-123' const collectionName = collectionSelector.fromHostDomain( request, /^preview-([^.]*)\./ ); if (collectionName != null) { publisherServer.setActiveCollectionName(collectionName); } // Alternative patterns: // staging.example.com -> 'staging' // const staging = collectionSelector.fromHostDomain(request, /^(staging)\./); // feature-xyz.example.com -> 'xyz' // const feature = collectionSelector.fromHostDomain(request, /^feature-([^.]+)\./); return publisherServer.serveRequest(request) ?? new Response('Not found', { status: 404 }); } ``` -------------------------------- ### List Published Collections in Fastly KV Store Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md The `collections list` command retrieves and displays all collections currently published in the Fastly KV Store. This command does not have specific options beyond the global ones. The `--local` option allows operating on local files for simulation, and `--fastly-api-token` is used for authentication. ```sh npx @fastly/compute-js-static-publish collections list ``` -------------------------------- ### PublisherServer: Access Asset Metadata and Load Variants in Fastly Compute JS Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Illustrates how to programmatically access asset metadata and load specific asset variants using PublisherServer. This allows for custom handling of assets, such as streaming their content or inspecting their properties before serving. ```javascript import { PublisherServer } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const request = event.request; const url = new URL(request.url); // Get asset metadata without serving const asset = await publisherServer.getMatchingAsset('/images/logo.png'); if (asset != null) { console.log('Asset info:', { contentType: asset.contentType, // 'image/png' lastModifiedTime: asset.lastModifiedTime, // Unix timestamp size: asset.size, // Size in bytes hash: asset.key, // 'sha256:abc123...' variants: asset.variants, // ['gzip', 'br'] }); } // Load asset variant from KV Store const kvAssetVariant = await publisherServer.loadKvAssetVariant(asset, 'gzip'); if (kvAssetVariant != null) { console.log('Variant info:', { size: kvAssetVariant.size, hash: kvAssetVariant.hash, contentEncoding: kvAssetVariant.contentEncoding, // 'gzip' numChunks: kvAssetVariant.numChunks, // For large files }); // Stream the body directly const body = kvAssetVariant.kvStoreEntry.body; // Or read as text/json/arrayBuffer: // const text = await kvAssetVariant.kvStoreEntry.text(); // const json = await kvAssetVariant.kvStoreEntry.json(); } return publisherServer.serveRequest(request) ?? new Response('Not found', { status: 404 }); } ``` -------------------------------- ### Clean Up KV Store with CLI Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Commands to remove expired collections and unreferenced content from the KV Store. Includes a dry run option to preview deletions and options for cleaning the local KV Store. Can be integrated with npm scripts. ```bash # Preview what would be deleted (dry run) npx @fastly/compute-js-static-publish clean --dry-run # Clean up expired collections and orphaned content npx @fastly/compute-js-static-publish clean --delete-expired-collections # Clean local KV Store npx @fastly/compute-js-static-publish clean --local --delete-expired-collections # Using npm scripts npm run dev:clean # Local development npm run fastly:clean # Production ``` -------------------------------- ### Select Collection by Request URL (JavaScript) Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Selects a deployment collection based on the request's URL path or query parameters. This method allows for dynamic collection selection using custom logic applied to the URL. It accepts the request object and a callback function that returns the collection name or null. ```javascript import { PublisherServer, collectionSelector } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const request = event.request; // Extract collection from URL path: /preview/pr-42/page -> 'pr-42' const collectionFromPath = collectionSelector.fromRequestUrl( request, (url) => { const pathParts = url.pathname.split('/'); if (pathParts[1] === 'preview' && pathParts[2]) { return pathParts[2]; // Returns 'pr-42' } return null; } ); // Or extract from query parameter: ?preview=staging const collectionFromQuery = collectionSelector.fromRequestUrl( request, (url) => url.searchParams.get('preview') ); const collectionName = collectionFromPath ?? collectionFromQuery; if (collectionName != null) { publisherServer.setActiveCollectionName(collectionName); } return publisherServer.serveRequest(request) ?? new Response('Not found', { status: 404 }); } ``` -------------------------------- ### PublisherServer: Switch Active Collection by Request in Fastly Compute JS Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Shows how to dynamically switch the active collection served by PublisherServer based on request properties like query parameters or custom headers. It also demonstrates how to customize or disable the collection name response header. ```javascript import { PublisherServer } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const request = event.request; const url = new URL(request.url); // Switch collection based on query parameter const collectionParam = url.searchParams.get('collection'); if (collectionParam) { publisherServer.setActiveCollectionName(collectionParam); } // Or switch based on custom header const collectionHeader = request.headers.get('X-Preview-Collection'); if (collectionHeader) { publisherServer.setActiveCollectionName(collectionHeader); } // Optionally customize or disable the collection name response header publisherServer.setCollectionNameHeader('X-Served-Collection'); // Or disable: publisherServer.setCollectionNameHeader(null); const response = await publisherServer.serveRequest(request); return response ?? new Response('Not found', { status: 404 }); } ``` -------------------------------- ### Handle Request with Cookie-Based Collection Selection (JavaScript) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md This snippet shows how to use the `fromCookie` function to parse request cookies for collection selection. It checks for a `redirectResponse` and applies the `collectionName` if found. This is intended for use within a Fastly Compute@Edge JavaScript application. ```javascript async function handleRequest(event) { const request = event.request; // --- Cookie handling starts here const { collectionName, redirectResponse } = collectionSelector.fromCookie(request); if (redirectResponse) { // obey redirect first return redirectResponse; } if (collectionName != null) { publisherServer.setActiveCollectionName(collectionName); } // --- Cookie handling ends here // Regular routing follows... const response = await publisherServer.serveRequest(request); if (response != null) { return response; } return new Response('Not found', { status: 404 }); } ``` -------------------------------- ### Clean Up Local and Fastly KV Stores Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Commands to remove old and unused assets from local and Fastly KV Stores. These scripts help prevent storage bloat by deleting expired collection index files, unreferenced content blobs, and orphaned server configuration files. ```sh npm run dev:clean npm run fastly:clean npx @fastly/compute-js-static-publish clean --delete-expired-collections ``` -------------------------------- ### Manage Collections via Cookie in JavaScript Source: https://context7.com/fastly/compute-js-static-publish/llms.txt This snippet demonstrates how to manage collection selection using browser cookies. It handles activation and reset endpoints, allowing users to dynamically switch collections. The `fromCookie` function reads the cookie, and the `publisherServer` applies the selected collection. ```javascript import { PublisherServer, collectionSelector } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const request = event.request; // fromCookie handles: // - GET /activate?collection=staging&redirectTo=/ -> Sets cookie, redirects // - GET /reset?redirectTo=/ -> Clears cookie, redirects // - Other requests: reads cookie value const { collectionName, redirectResponse } = collectionSelector.fromCookie(request, { cookieName: 'publisher-collection', // Cookie name (default) activatePath: '/activate', // Endpoint to set cookie (default) resetPath: '/reset', // Endpoint to clear cookie (default) cookieHttpOnly: true, // Prevent JS access (default) cookieMaxAge: 60 * 60 * 24 * 7, // 7 days (default: session) cookiePath: '/', // Cookie path (default) }); // Handle activate/reset redirects if (redirectResponse != null) { return redirectResponse; } // Apply collection if cookie was set if (collectionName != null) { publisherServer.setActiveCollectionName(collectionName); } return publisherServer.serveRequest(request) ?? new Response('Not found', { status: 404 }); } // Usage: // Activate: GET https://example.com/activate?collection=staging&redirectTo=/ // Reset: GET https://example.com/reset?redirectTo=/ ``` -------------------------------- ### Select Collection from Host Domain (Compute JS) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Helper function to extract a collection name from the request's host domain using a regular expression. ```js collectionSelector.fromHostDomain(request, /^preview-([^.]*)\./); ``` -------------------------------- ### Select Collection by Custom Request Logic (JavaScript) Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Selects a deployment collection using custom logic that inspects various properties of the request, such as headers or cookies. This provides maximum flexibility in determining the active collection. It takes the request object and a callback function that returns the collection name. ```javascript import { PublisherServer, collectionSelector } from '@fastly/compute-js-static-publish'; import rc from '../static-publish.rc.js'; const publisherServer = PublisherServer.fromStaticPublishRc(rc); addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const request = event.request; // Custom logic using headers, cookies, or any request property const collectionName = collectionSelector.fromRequest( request, (req) => { // Check custom header first const headerValue = req.headers.get('X-Preview-Collection'); if (headerValue) return headerValue; // Fall back to cookie const cookies = req.headers.get('Cookie') ?? ''; const match = cookies.match(/preview-collection=([^;]+)/); if (match) return match[1]; // Default to live return 'live'; } ); publisherServer.setActiveCollectionName(collectionName); return publisherServer.serveRequest(request) ?? new Response('Not found', { status: 404 }); } ``` -------------------------------- ### Set Collection Expiration (CLI) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Configure automatic expiration for collections using relative or absolute times, or disable expiration. Only one expiration option can be specified per collection. ```sh --expires-in=3d --expires-at=2025-05-01T12:00Z --expires-never ``` -------------------------------- ### Select Collection with Custom Matcher (Compute JS) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Use a custom function to determine the collection name based on request properties, such as headers. Provides a fallback to a default collection if no match is found. ```js collectionSelector.fromRequest(request, req => req.headers.get('x-collection') ?? 'live'); ``` -------------------------------- ### Select Collection from Request URL Path (Compute JS) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Extract a collection name from a specific segment of the request URL's pathname. ```js collectionSelector.fromRequestUrl(request, url => url.pathname.split('/')[2]); ``` -------------------------------- ### Activate Collection for Request (Compute JS) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Dynamically set the active collection for the current request within a Compute JS application. This is useful for previewing or routing to specific collections based on request properties. ```js publisherServer.setActiveCollectionName("preview-42"); ``` -------------------------------- ### Delete Collection from KV Store with CLI Source: https://context7.com/fastly/compute-js-static-publish/llms.txt CLI command to delete a specific collection index from the KV Store. Content files associated with the collection are not deleted and may remain if referenced elsewhere. Supports local KV Store deletion. ```bash # Delete a specific collection npx @fastly/compute-js-static-publish collections delete \ --collection-name=preview-42 # Delete from local KV Store npx @fastly/compute-js-static-publish collections delete \ --collection-name=old-preview \ --local # Note: Cannot delete the default collection # After deleting, run 'clean' to remove orphaned content files ``` -------------------------------- ### Update Collection Expiration with CLI Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Commands to update the expiration date for collections in the KV Store. Supports extending by a duration (e.g., '3d') or setting an absolute timestamp. Can also be used to make a collection permanent by removing expiration. ```bash npx @fastly/compute-js-static-publish collections update-expiration \ --collection-name=preview-42 \ --expires-in=3d npx @fastly/compute-js-static-publish collections update-expiration \ --collection-name=staging \ --expires-at=2025-06-01T00:00:00Z npx @fastly/compute-js-static-publish collections update-expiration \ --collection-name=staging \ --expires-never ``` -------------------------------- ### Clean Expired/Unreferenced Items in Fastly KV Store Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md The `clean` command removes expired or unreferenced items from the Fastly KV Store. This includes expired collection indexes and orphaned content assets. It supports a `--delete-expired-collections` flag to explicitly remove expired index files and a `--dry-run` option to preview deletions without making changes. The `--local` and `--fastly-api-token` global options are also applicable. ```sh npx @fastly/compute-js-static-publish clean \ [--delete-expired-collections] \ [--dry-run] ``` -------------------------------- ### Select Collection from Cookie (Compute JS) Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Extract a collection name from a cookie in the request. This method returns both the collection name and a potential redirect response if the cookie is invalid or missing. ```js const { collectionName, redirectResponse } = collectionSelector.fromCookie(request); ``` -------------------------------- ### Update Collection Expiration Time (CLI) Source: https://context7.com/fastly/compute-js-static-publish/llms.txt Modifies the expiration time of an existing collection without needing to republish its content. This is useful for extending the availability of published assets. ```bash # Example command to update expiration (specific command not provided in source, inferred from description) # npx @fastly/compute-js-static-publish collections update-expiration \ # --collection-name=staging \ # --expires-in=14d ``` -------------------------------- ### Select Active Collection Using Cookie - JavaScript Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md A utility function to select the active collection based on a browser cookie. It reads a specified cookie, handles activation and reset endpoints, and includes safety flags like HttpOnly and SameSite. It returns the collection name and an optional redirect response. ```js import { collectionSelector } from '@fastly/compute-js-static-publish'; const { collectionName, redirectResponse } = collectionSelector.fromCookie(request, { // Everything here is optional – these are just examples cookieName: 'publisher-collection', // default activatePath: '/activate', // default resetPath: '/reset', // default cookieHttpOnly: true, // default cookieMaxAge: 60 * 60 * 24 * 7, // 7-days. default is `null`, never expires. cookiePath: '/', // default }); if (redirectResponse) { // honor the redirect return redirectResponse; } // `collectionName` now holds the active collection (or `null` if none) ``` -------------------------------- ### Update Collection Expiration in Fastly KV Store Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md The `collections update-expiration` command allows setting or modifying the expiration time for an existing collection. It requires the `--collection-name` and exactly one of the expiration options: `--expires-in`, `--expires-at`, or `--expires-never`. The `--local` and `--fastly-api-token` global options are also available for this command. ```sh npx @fastly/compute-js-static-publish collections update-expiration \ --collection-name=preview-42 \ --expires-in=3d | --expires-at=2025-06-01T00:00Z | --expires-never ``` -------------------------------- ### Delete Collection Index - Fastly CLI Source: https://github.com/fastly/compute-js-static-publish/blob/main/README.md Deletes a collection index from the Fastly KV Store. Content files are retained as they might be referenced by other indexes. Use `npx @fastly/compute-js-static-publish clean` afterward to remove unreferenced content files. Requires a collection name. ```sh npx @fastly/compute-js-static-publish collections delete \ --collection-name=preview-42 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.