### NVM Installation Script Example Source: https://github.com/nvm-sh/nvm Provides an example of a command used to install Node.js versions via NVM. This command downloads and installs pre-compiled binaries. ```shell nvm install ``` -------------------------------- ### Install Node.js Version from .nvmrc Source: https://github.com/nvm-sh/nvm This example illustrates the 'nvm install' command's behavior when a .nvmrc file is present. If the specified Node.js version is not installed, nvm will download and install it automatically before switching to it. ```shell $ nvm install Found '/path/to/project/.nvmrc' with version <5.9> Downloading and installing node v5.9.1... Downloading https://nodejs.org/dist/v5.9.1/node-v5.9.1-linux-x64.tar.xz... #################################################################################### 100.0% Computing checksum with sha256sum Checksums matched! Now using node v5.9.1 (npm v3.7.3) ``` -------------------------------- ### Example Create Migration with Durable Object Binding Source: https://context7_llms This example demonstrates how to configure a new Durable Object binding named `DURABLE_OBJECT_A` and its corresponding class `DurableObjectAClass` using a Create migration. It shows the setup in both `wrangler.jsonc` and `wrangler.toml`. ```jsonc { "durable_objects": { "bindings": [ { "name": "DURABLE_OBJECT_A", "class_name": "DurableObjectAClass" } ] }, "migrations": [ { "tag": "v1", "new_sqlite_classes": [ "DurableObjectAClass" ] } ] } ``` ```toml # Creating a new Durable Object class [[durable_objects.bindings]] name = "DURABLE_OBJECT_A" class_name = "DurableObjectAClass" # Add the lines below for a Create migration. [[migrations]] tag = "v1" new_sqlite_classes = ["DurableObjectAClass"] ``` -------------------------------- ### Manual Installation of Node Version Manager (nvm) Source: https://github.com/nvm-sh/nvm Provides steps for manually installing nvm by cloning the repository and sourcing the nvm.sh script. This method offers more control over the installation location. ```Shell git clone https://github.com/nvm-sh/nvm.git ~/.nvm . ~/.nvm/nvm.sh ``` -------------------------------- ### SQL API Examples Source: https://context7_llms Examples demonstrating how to use the SQL API for Durable Objects storage, including creating tables, executing queries, and processing results. ```APIDOC ## SQL API Examples This section provides examples for using the SQL API with Durable Objects, assuming the following SQL schema: ```ts import { DurableObject } from "cloudflare:workers"; export class MyDurableObject extends DurableObject { sql: SqlStorage constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.sql = ctx.storage.sql; this.sql.exec(`CREATE TABLE IF NOT EXISTS artist( artistid INTEGER PRIMARY KEY, artistname TEXT );INSERT INTO artist (artistid, artistname) VALUES (123, 'Alice'), (456, 'Bob'), (789, 'Charlie');` ); } } ``` ### Iterating Over Query Results Iterate over query results as row objects: ```ts let cursor = this.sql.exec("SELECT * FROM artist;"); for (let row of cursor) { // Iterate over row object and do something } ``` ### Converting Query Results to Arrays Convert query results to an array of row objects: ```ts // Return array of row objects: [{"artistid":123,"artistname":"Alice"},{"artistid":456,"artistname":"Bob"},{"artistid":789,"artistname":"Charlie"}] let resultsArray1 = this.sql.exec("SELECT * FROM artist;").toArray(); // OR let resultsArray2 = Array.from(this.sql.exec("SELECT * FROM artist;")); // OR let resultsArray3 = [...this.sql.exec("SELECT * FROM artist;")]; // JavaScript spread syntax ``` Convert query results to an array of row values arrays: ```ts // Returns [[123,"Alice"],[456,"Bob"],[789,"Charlie"]] let cursor = this.sql.exec("SELECT * FROM artist;"); let resultsArray = cursor.raw().toArray(); // Returns ["artistid","artistname"] let columnNameArray = this.sql.exec("SELECT * FROM artist;").columnNames.toArray(); ``` ### Getting the First Row Get the first row object of query results: ```ts // Returns {"artistid":123,"artistname":"Alice"} let firstRow = this.sql.exec("SELECT * FROM artist ORDER BY artistname DESC;").toArray()[0]; ``` ### Checking for Exactly One Row Check if query results have exactly one row: ```ts // returns error this.sql.exec("SELECT * FROM artist ORDER BY artistname ASC;").one(); // returns { artistid: 123, artistname: 'Alice' } let oneRow = this.sql.exec("SELECT * FROM artist WHERE artistname = ?;", "Alice").one() ``` ### Cursor Behavior Returned cursor behavior: ```ts let cursor = this.sql.exec("SELECT * FROM artist ORDER BY artistname ASC;"); let result = cursor.next(); if (!result.done) { console.log(result.value); // prints { artistid: 123, artistname: 'Alice' } } else { // query returned zero results } let remainingRows = cursor.toArray(); console.log(remainingRows); // prints [{ artistid: 456, artistname: 'Bob' },{ artistid: 789, artistname: 'Charlie' }] ``` Returned cursor and `raw()` iterator iterate over the same query results: ```ts let cursor = this.sql.exec("SELECT * FROM artist ORDER BY artistname ASC;"); let result = cursor.raw().next(); if (!result.done) { console.log(result.value); // prints [ 123, 'Alice' ] } else { // query returned zero results } console.log(cursor.toArray()); // prints [{ artistid: 456, artistname: 'Bob' },{ artistid: 789, artistname: 'Charlie' }] ``` ### `rowsRead()` Method `sql.exec().rowsRead()`: ```ts let cursor = this.sql.exec("SELECT * FROM artist;"); cursor.next() console.log(cursor.rowsRead); // prints 1 cursor.toArray(); // consumes remaining cursor console.log(cursor.rowsRead); // prints 3 ``` ### `databaseSize` Property `databaseSize`: number #### Returns The current SQLite database size in bytes. ```ts let size = ctx.storage.sql.databaseSize; ``` ``` -------------------------------- ### Manually Install and Load nvm (Bash) Source: https://github.com/nvm-sh/nvm This snippet demonstrates the manual installation of nvm by cloning the repository and checking out the latest tag. It then sources the nvm.sh script to load nvm into the current shell session. Ensure you have git installed. ```shell export NVM_DIR="$HOME/.nvm" && ( git clone https://github.com/nvm-sh/nvm.git "$NVM_DIR" cd "$NVM_DIR" git checkout `git describe --abbrev=0 --tags --match "v[0-9]*" $(git rev-list --tags --max-count=1)` ) && . "$NVM_DIR/nvm.sh" ``` -------------------------------- ### Install nvm using Wget and Bash Source: https://github.com/nvm-sh/nvm This command downloads the nvm installation script using Wget and pipes it directly to bash for execution. It serves the same purpose as the cURL command for installing or updating nvm. ```shell wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash ``` -------------------------------- ### Install and Update Node Version Manager (nvm) Source: https://github.com/nvm-sh/nvm This script installs or updates nvm. It downloads the latest version from GitHub and installs it into the specified directory. Ensure you have curl or wget installed. ```Shell #!/bin/bash curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash ``` -------------------------------- ### Manual Install NVM Source: https://github.com/nvm-sh/nvm Performs a manual installation of NVM by cloning the repository, checking out the latest tag, and sourcing the NVM script. It also configures automatic sourcing on login. ```bash export NVM_DIR="$HOME/.nvm" && ( git clone https://github.com/nvm-sh/nvm.git "$NVM_DIR" cd "$NVM_DIR" git checkout `git describe --abbrev=0 --tags --match "v[0-9]*" $(git rev-list --tags --max-count=1)` ) && \. "$NVM_DIR/nvm.sh" # Add to shell configuration files (~/.bashrc, ~/.profile, or ~/.zshrc): export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion ``` -------------------------------- ### List Installed and Remote Node.js Versions with NVM Source: https://github.com/nvm-sh/nvm Shows commands for listing all locally installed Node.js versions and all versions available for remote installation. This helps users keep track of their Node.js environment and discover available versions. ```bash nvm ls nvm ls-remote ``` -------------------------------- ### Install nvm using cURL and Bash Source: https://github.com/nvm-sh/nvm This command downloads the nvm installation script using cURL and pipes it directly to bash for execution. It is used for installing or updating the Node Version Manager. ```shell curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash ``` -------------------------------- ### Example Transfer Migration Configuration in wrangler.toml Source: https://context7_llms This example provides a practical implementation of a transfer migration using wrangler.toml. It outlines how to migrate 'DurableObjectExample' from 'OldWorkerScript' to 'TransferredClass', configuring the destination binding 'MY_DURABLE_OBJECT'. This example serves as a clear reference for setting up such migrations. ```toml # destination worker [[durable_objects.bindings]] name = "MY_DURABLE_OBJECT" class_name = "TransferredClass" # Transferring class [[migrations]] tag = "v4" transferred_classes = [{from = "DurableObjectExample", from_script = "OldWorkerScript", to = "TransferredClass" }] ``` -------------------------------- ### Install Node.js Version using nvm Source: https://github.com/nvm-sh/nvm Installs a specific version of Node.js. nvm will download and compile the specified version if it's not already installed. ```Shell nvm install 16 ``` -------------------------------- ### Wrangler Deployment Output Example (Text) Source: https://context7_llms Example output from the `npm run deploy` command using Wrangler CLI. It shows the build process, asset upload status, and details about the deployed worker, including its bindings and access link. ```text ⛅️ wrangler 3.78.8 ------------------- 🌀 Building list of assets... 🌀 Starting asset upload... 🌀 Found 1 new or modified file to upload. Proceeding with upload... + /index.html Uploaded 1 of 1 assets ✨ Success! Uploaded 1 file (1.93 sec) Total Upload: 3.45 KiB / gzip: 1.39 KiB Your worker has access to the following bindings: - Durable Objects: - FLIGHT: Flight Uploaded seat-book (12.12 sec) Deployed seat-book triggers (5.54 sec) [DEPLOYED_APP_LINK] Current Version ID: [BINDING_ID] ``` -------------------------------- ### Launch Local Development Environment with Wrangler Source: https://github.com/cloudflare/workers-wonnx This command starts the local development server for Cloudflare Workers using the Wrangler CLI. It allows for testing your worker locally before deploying. Ensure you have Wrangler installed and configured. ```bash npx wrangler@latest dev ``` -------------------------------- ### Install Node.js from Git Repository using nvm Source: https://github.com/nvm-sh/nvm Allows installation of Node.js directly from a git repository. This is useful for testing development branches or specific commits. ```Shell nvm install git://github.com/nodejs/node-v0.x.git#v0.12.0 ``` -------------------------------- ### Docker Run Example: Interactive Node.js Session Source: https://github.com/nvm-sh/nvm Shows how to run the Docker container interactively. After starting the container, you can verify the NVM and Node.js versions and execute commands within the Node.js environment. ```bash docker run --rm -it nvmimage root@0a6b5a237c14:/# nvm -v 0.40.3 root@0a6b5a237c14:/# node -v v19.9.0 root@0a6b5a237c14:/# npm -v 9.6.3 ``` -------------------------------- ### NVM Install Node Command Source: https://github.com/nvm-sh/nvm Installs Node.js using the NVM command-line tool. It supports installing the latest version using the 'node' alias or a specific version number. ```bash # Install the latest version of Node.js nvm install node # Install a specific version of Node.js nvm install 14.7.0 ``` -------------------------------- ### Git Install NVM Source: https://github.com/nvm-sh/nvm Installs NVM using Git by cloning the repository, checking out a specific version, and sourcing the NVM script. It also includes instructions for automatically sourcing NVM on login by adding lines to shell configuration files. ```bash cd ~/ git clone https://github.com/nvm-sh/nvm.git .nvm cd ~/.nvm git checkout v0.40.3 . ./nvm.sh # Add to shell configuration files (~/.bashrc, ~/.profile, or ~/.zshrc): export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion ``` -------------------------------- ### Shell: Install Volta and Node.js Source: https://volta.sh/ This is a common shell command sequence for installing Volta, a JavaScript tool manager, and then using Volta to install Node.js. It begins with a curl command to download and execute the Volta installation script, followed by commands to install Node.js and start using it. ```shell # install Volta curl https://get.volta.sh | bash # install Node volta install node # start using Node node ``` -------------------------------- ### List Installed Node Versions with NVM Source: https://github.com/nvm-sh/nvm Displays all Node.js versions currently installed on your system via NVM. This command helps in managing your installed runtimes. ```shell nvm ls ``` -------------------------------- ### Install nvm using Ansible Source: https://github.com/nvm-sh/nvm This Ansible task automates the installation of Node Version Manager (NVM) by downloading and executing the install script. It ensures that the nvm.sh script exists before running, preventing redundant installations. This is useful for setting up consistent development environments. ```yaml - name: Install nvm ansible.builtin.shell: > curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash args: creates: "{{ ansible_env.HOME }}/.nvm/nvm.sh" ``` -------------------------------- ### NVM Automatic Version Switching with .nvmrc Source: https://github.com/nvm-sh/nvm Demonstrates how 'nvm use' and 'nvm install' automatically detect and switch to the Node.js version specified in a .nvmrc file. If the version is not installed, 'nvm install' will download and install it. ```shell $ nvm use Found '/path/to/project/.nvmrc' with version <5.9> Now using node v5.9.1 (npm v3.7.3) $ nvm install Found '/path/to/project/.nvmrc' with version <5.9> Downloading and installing node v5.9.1... Downloading https://nodejs.org/dist/v5.9.1/node-v5.9.1-linux-x64.tar.xz... #################################################################################### 100.0% Computing checksum with sha256sum Checksums matched! Now using node v5.9.1 (npm v3.7.3) ``` -------------------------------- ### Install Node.js iojs with NVM Source: https://github.com/nvm-sh/nvm Installs a new version of io.js using NVM. This is useful for managing different Node.js runtimes on your system. ```shell nvm install iojs ``` -------------------------------- ### Install Dependencies and Run Tests for NVM Source: https://github.com/nvm-sh/nvm Commands to install project dependencies and execute different test suites (fast, slow, all) for the nvm (Node Version Manager) project. It's recommended to avoid running nvm while tests are in progress. ```bash npm install ``` ```bash npm run test/fast ``` ```bash npm run test/slow ``` ```bash npm test ``` -------------------------------- ### Install or Update nvm using curl or wget Source: https://github.com/nvm-sh/nvm This script installs or updates the Node Version Manager (nvm). It downloads the installation script and executes it. The script clones the nvm repository and attempts to configure the shell profile. Dependencies include curl or wget. ```bash curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash ``` ```bash wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash ``` -------------------------------- ### Install and Manage io.js Versions with NVM Source: https://github.com/nvm-sh/nvm Provides commands for installing io.js and migrating npm packages from a previous version to io.js. This functionality is similar to managing Node.js versions, allowing users to switch between io.js and Node.js environments. ```bash nvm install iojs nvm install --reinstall-packages-from=iojs iojs ``` -------------------------------- ### Install NVM with Customizations Source: https://github.com/nvm-sh/nvm This command installs NVM using curl, allowing for customization of the installation source, directory, profile, and Node.js version. By setting PROFILE=/dev/null, it prevents the installer from modifying the shell configuration, which is useful when using other NVM management tools like zsh plugins. Ensure the NVM_DIR does not have a trailing slash. ```shell PROFILE=/dev/null bash -c 'curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash' ``` -------------------------------- ### Run WONNX Example with Cargo Source: https://github.com/webonnx/wonnx This command executes a specific example ('squeeze') from the WONNX project using Cargo, the Rust package manager. It compiles and runs the example in release mode for optimized performance. This is part of the development setup for WONNX. ```shell cargo run --example squeeze --release ``` -------------------------------- ### Boot Container on Durable Object Start (JavaScript) Source: https://context7_llms This JavaScript code snippet demonstrates how to start a container when a Durable Object is initialized. It uses `this.ctx.blockConcurrencyWhile` to ensure the container starts without concurrent access issues. The `container.start()` method is called within this block. ```javascript export class MyDurableObject extends DurableObject { constructor(ctx, env) { super(ctx, env); // boot the container when starting the DO this.ctx.blockConcurrencyWhile(async () => { this.ctx.container.start(); }); } } ``` -------------------------------- ### List Available Remote Node.js Versions with NVM Source: https://github.com/nvm-sh/nvm Fetches and displays a list of all available Node.js versions that can be installed remotely. This command is useful for discovering version numbers before installation or aliasing. ```shell nvm ls-remote ``` -------------------------------- ### Dockerfile: Install NVM and Node.js Source: https://github.com/nvm-sh/nvm This Dockerfile installs curl, NVM, and a specified Node.js version. It sets up the NVM environment and configures the entrypoint to source the NVM environment before executing commands. The default Node.js version is 20.x.y. ```dockerfile FROM ubuntu:latest ARG NODE_VERSION=20 # install curl RUN apt update && apt install curl -y # install nvm RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash # set env ENV NVM_DIR=/root/.nvm # install node RUN bash -c "source $NVM_DIR/nvm.sh && nvm install $NODE_VERSION" # set ENTRYPOINT for reloading nvm-environment ENTRYPOINT ["bash", "-c", "source $NVM_DIR/nvm.sh && exec \"$@\"", "--"] # set cmd to bash CMD ["/bin/bash"] ``` -------------------------------- ### Durable Object Fetch Handler Example in JavaScript Source: https://context7_llms Implements the fetch handler for a Durable Object to return a "Hello, World!" response. This example extends the base DurableObject class and demonstrates a basic fetch request-response cycle. ```javascript export class MyDurableObject extends DurableObject { constructor(ctx, env) { super(ctx, env); } async fetch(request) { return new Response("Hello, World!"); } } ``` -------------------------------- ### Manage Default Global Packages with NVM Source: https://github.com/nvm-sh/nvm Explains how to define a list of default npm packages to be installed automatically whenever a new Node.js version is installed using NVM. Packages are listed one per line in the `$NVM_DIR/default-packages` file. ```bash # $NVM_DIR/default-packages rimraf object-inspect@1.0.2 stevemao/left-pad ``` -------------------------------- ### Install Rosetta on Apple Silicon Macs Source: https://github.com/nvm-sh/nvm This command installs Rosetta, a translation layer that allows Intel-based applications to run on Apple Silicon Macs. It's a prerequisite for running older Node.js versions or Intel-compiled tools. ```bash softwareupdate --install-rosetta ``` -------------------------------- ### Install and Use LTS Node.js Versions with NVM Source: https://github.com/nvm-sh/nvm Demonstrates how to install and use Long-Term Support (LTS) versions of Node.js using NVM. It covers installing the latest LTS, specific LTS lines like 'argon', and managing these versions. These commands interact with remote Node.js repositories and local NVM aliases. ```bash nvm install --lts nvm install --lts=argon nvm install 'lts/*' nvm install lts/argon nvm uninstall --lts nvm uninstall --lts=argon nvm uninstall 'lts/*' nvm uninstall lts/argon nvm use --lts nvm use --lts=argon nvm use 'lts/*' nvm use lts/argon nvm exec --lts nvm exec --lts=argon nvm exec 'lts/*' nvm exec lts/argon nvm run --lts nvm run --lts=argon nvm run 'lts/*' nvm run lts/argon nvm ls-remote --lts nvm ls-remote --lts=argon nvm ls-remote 'lts/*' nvm ls-remote lts/argon nvm version-remote --lts nvm version-remote --lts=argon nvm version-remote 'lts/*' nvm version-remote lts/argon ``` -------------------------------- ### Install Latest Node.js Version with NVM Source: https://github.com/nvm-sh/nvm Installs the latest available version of Node.js using NVM. This is the simplest way to get the most recent stable release for your project. Ensure NVM is sourced in your shell. ```shell nvm install node # "node" is an alias for the latest version ``` -------------------------------- ### Static Frontend with Container Backend Example Source: https://developers.cloudflare.com/llms.txt This example demonstrates how to set up a simple frontend application that communicates with a containerized backend. It showcases a common deployment pattern for web applications using Cloudflare Containers. ```plaintext This section describes a pattern and does not contain a direct code snippet. ``` -------------------------------- ### Install Node.js with Latest npm using NVM Source: https://github.com/nvm-sh/nvm This command installs the latest LTS version of Node.js and ensures the latest compatible npm version is installed. It's useful when starting with a new Node.js version or when a specific npm version is required. The `--latest-npm` flag ensures npm is updated. ```shell nvm install --reinstall-packages-from=default --latest-npm 'lts/*' ``` -------------------------------- ### Install Latest npm on Current Node.js Version using NVM Source: https://github.com/nvm-sh/nvm This command updates npm to its latest available version for the currently active Node.js installation. It's a quick way to get the newest npm features or bug fixes without changing the Node.js version. This command does not require specifying a Node.js version. ```shell nvm install-latest-npm ``` -------------------------------- ### Get First Row Object from SQL Query Results Source: https://context7_llms Demonstrates how to retrieve only the first row object from the results of a SQL query. This is achieved by converting the results to an array and accessing the first element using index `[0]`. An example with ordering is provided. ```typescript // Returns {"artistid":123,"artistname":"Alice"} let firstRow = this.sql.exec("SELECT * FROM artist ORDER BY artistname DESC;").toArray()[0]; ``` -------------------------------- ### Build a Remote MCP Server Guide Source: https://developers.cloudflare.com/llms.txt Guide on building a remote MCP server. ```APIDOC ## Build a Remote MCP Server ### Description Guide on building a remote Model Context Protocol (MCP) server. ### Functionality Enables agents to communicate via the MCP protocol. ### Link /agents/guides/remote-mcp-server/ ### Details Details the server-side implementation for MCP communication. ``` -------------------------------- ### Initialize WebGPU API using JavaScript Source: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/gpu This JavaScript snippet demonstrates how to check for WebGPU support, request a GPU adapter, and then request a device. It's a fundamental example for getting started with the WebGPU API. Ensure your environment supports WebGPU and is a secure context (HTTPS). ```javascript async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const device = await adapter.requestDevice(); // ... } ``` -------------------------------- ### Build a Chat Agent Guide Source: https://developers.cloudflare.com/llms.txt A guide on building a chat agent using the Agents SDK. ```APIDOC ## Build a Chat Agent ### Description Starter template and guide for building AI-powered chat agents using the Cloudflare Agents SDK. ### Getting Started This project provides a foundation for creating interactive chat experiences with AI, including UI and tool integration. ### Link /agents/getting-started/build-a-chat-agent/ ### Details Focuses on practical implementation with the Agents SDK. ``` -------------------------------- ### Install nvm in Ubuntu Docker Image for CI/CD Source: https://github.com/nvm-sh/nvm This Dockerfile installs curl and then uses it to download and install nvm from a GitHub repository. It sets the Node.js version to be installed via nvm, suitable for CI/CD environments. ```dockerfile FROM ubuntu:latest ARG NODE_VERSION=20 # install curl RUN apt update && apt install curl -y # install nvm RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | PROFILE="${BASH_ENV}" bash ``` -------------------------------- ### Start Container with Options (JavaScript) Source: https://developers.cloudflare.com/durable-objects/api/container Initiates the startup of a container. This asynchronous method does not wait for the container to be fully ready. It accepts an options object to configure environment variables, the entrypoint command, and internet access. ```javascript this.ctx.container.start({ env: { FOO: "bar", }, enableInternet: false, entrypoint: ["node", "server.js"], }); ``` -------------------------------- ### Install nvm in WSL with potential network errors (Shell) Source: https://github.com/nvm-sh/nvm This command attempts to download and install nvm using curl. It includes an example of a network error ('Could not resolve host') that may occur if DNS resolution is not working correctly in WSL. ```shell curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- 0:00:09 --:--:-- 0curl: (6) Could not resolve host: raw.githubusercontent.com ``` -------------------------------- ### Configure Staging Environment Durable Object Binding (TOML) Source: https://context7_llms This TOML snippet shows the equivalent configuration for a 'staging' environment Durable Object binding using wrangler.toml. It defines 'EXAMPLE_CLASS' bound to 'DurableObjectExample' for the staging environment. ```toml [env.staging] durable_objects.bindings = [ {name = "EXAMPLE_CLASS", class_name = "DurableObjectExample"} ] ``` -------------------------------- ### Build a Remote MCP Client Guide Source: https://developers.cloudflare.com/llms.txt Guide on building an AI agent as a remote MCP client. ```APIDOC ## Build a Remote MCP Client ### Description Guide on building an AI Agent that functions as a remote MCP client. ### Role Acts as a client for the Model Context Protocol (MCP). ### Link /agents/guides/build-mcp-client/ ### Details Focuses on the client-side implementation within the MCP framework. ``` -------------------------------- ### TypeScript: Interact with Durable Objects and KV Namespace Source: https://context7_llms A TypeScript example demonstrating a Cloudflare Worker's `fetch` handler that interacts with a Durable Object. It shows how to get a Durable Object stub based on a room ID, pass requests to it, and how the Durable Object itself can read from and write to a KV namespace. ```typescript import { DurableObject } from 'cloudflare:workers'; interface Env { YOUR_KV_NAMESPACE: KVNamespace; YOUR_DO_CLASS: DurableObjectNamespace; } export default { async fetch(req: Request, env: Env): Promise { // Assume each Durable Object is mapped to a roomId in a query parameter // In a production application, this will likely be a roomId defined by your application // that you validate (and/or authenticate) first. let url = new URL(req.url); let roomIdParam = url.searchParams.get("roomId"); if (roomIdParam) { // Create (or get) a Durable Object based on that roomId. let durableObjectId = env.YOUR_DO_CLASS.idFromName(roomIdParam); // Get a "stub" that allows you to call that Durable Object let durableObjectStub = env.YOUR_DO_CLASS.get(durableObjectId); // Pass the request to that Durable Object and await the response // This invokes the constructor once on your Durable Object class (defined further down) // on the first initialization, and the fetch method on each request. // // You could pass the original Request to the Durable Object's fetch method // or a simpler URL with just the roomId. let response = await durableObjectStub.fetch(`http://do/${roomId}`); // This would return the value you read from KV *within* the Durable Object. return response; } } } export class YourDurableObject extends DurableObject { constructor(public state: DurableObjectState, env: Env) { this.state = state; // Ensure you pass your bindings and environmental variables into // each Durable Object when it is initialized this.env = env; } async fetch(request: Request) { // Error handling elided for brevity. // Write to KV await this.env.YOUR_KV_NAMESPACE.put("some-key"); // Fetch from KV let val = await this.env.YOUR_KV_NAMESPACE.get("some-other-key"); return Response.json(val); } } ``` -------------------------------- ### NVM Command Autocompletion Examples Source: https://github.com/nvm-sh/nvm These examples demonstrate how tab completion works for the 'nvm' command and its subcommands. When you type 'nvm' followed by a Tab key, your shell will suggest available commands and arguments. ```shell $ nvm Tab alias deactivate install list-remote reinstall-packages uninstall version cache exec install-latest-npm ls run unload version-remote current help list ls-remote unalias use which ``` ```shell $ nvm alias Tab default iojs lts/* lts/argon lts/boron lts/carbon lts/dubnium lts/erbium node stable unstable ``` ```shell $ nvm alias my_alias Tab v10.22.0 v12.18.3 v14.8.0 ``` ```shell $ nvm use Tab # (This would typically list installed Node.js versions for selection) ``` -------------------------------- ### Docker Build Example: Override Node.js Version Source: https://github.com/nvm-sh/nvm Demonstrates how to build the Docker image while specifying a different Node.js version using the --build-arg flag. This allows for flexibility in choosing the Node.js runtime. ```bash docker build -t nvmimage --build-arg NODE_VERSION=19 . ``` -------------------------------- ### WebGPU API Availability in Durable Objects Source: https://context7_llms Details on the WebGPU API subset supported within Cloudflare Durable Objects and how to enable it for local development. ```APIDOC ## WebGPU API in Durable Objects ### Description The WebGPU API allows direct GPU access from JavaScript within Durable Objects, but is **only available in local development**. It cannot be deployed to Cloudflare. ### Enabling WebGPU for Local Development To use the WebGPU API in your local development environment, you must enable the `experimental` and `webgpu` compatibility flags in your Wrangler configuration file (`wrangler.toml`). ### Wrangler Configuration Example ```toml compatibility_flags = ["experimental", "webgpu"] ``` ### Supported WebGPU APIs The following subset of the WebGPU API is available within Durable Objects: | API | Supported? | | ---------------------------------------------------------------- | ---------- | | [`navigator.gpu`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/gpu) | ✅ | | [`GPU.requestAdapter`](https://developer.mozilla.org/en-US/docs/Web/API/GPU/requestAdapter) | ✅ | | [`GPUAdapterInfo`](https://developer.mozilla.org/en-US/docs/Web/API/GPUAdapterInfo) | ✅ | | [`GPUAdapter`](https://developer.mozilla.org/en-US/docs/Web/API/GPUAdapter) | ✅ | | [`GPUBindGroupLayout`](https://developer.mozilla.org/en-US/docs/Web/API/GPUBindGroupLayout) | ✅ | | [`GPUBindGroup`](https://developer.mozilla.org/en-US/docs/Web/API/GPUBindGroup) | ✅ | | [`GPUBuffer`](https://developer.mozilla.org/en-US/docs/Web/API/GPUBuffer) | ✅ | | [`GPUCommandBuffer`](https://developer.mozilla.org/en-US/docs/Web/API/GPUCommandBuffer) | ✅ | | [`GPUCommandEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/GPUCommandEncoder) | ✅ | | [`GPUComputePassEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/GPUComputePassEncoder) | ✅ | | [`GPUComputePipeline`](https://developer.mozilla.org/en-US/docs/Web/API/GPUComputePipeline) | ✅ | | [`GPUComputePipelineError`](https://developer.mozilla.org/en-US/docs/Web/API/GPUPipelineError) | ✅ | | [`GPUDevice`](https://developer.mozilla.org/en-US/docs/Web/API/GPUDevice) | ✅ | | [`GPUOutOfMemoryError`](https://developer.mozilla.org/en-US/docs/Web/API/GPUOutOfMemoryError) | ✅ | | [`GPUValidationError`](https://developer.mozilla.org/en-US/docs/Web/API/GPUValidationError) | ✅ | | [`GPUInternalError`](https://developer.mozilla.org/en-US/docs/Web/API/GPUInternalError) | ✅ | | [`GPUDeviceLostInfo`](https://developer.mozilla.org/en-US/docs/Web/API/GPUDeviceLostInfo) | ✅ | | [`GPUPipelineLayout`](https://developer.mozilla.org/en-US/docs/Web/API/GPUPipelineLayout) | ✅ | | [`GPUQuerySet`](https://developer.mozilla.org/en-US/docs/Web/API/GPUQuerySet) | ✅ | | [`GPUQueue`](https://developer.mozilla.org/en-US/docs/Web/API/GPUQueue) | ✅ | | [`GPUSampler`](https://developer.mozilla.org/en-US/docs/Web/API/GPUSampler) | ✅ | | [`GPUCompilationMessage`](https://developer.mozilla.org/en-US/docs/Web/API/GPUCompilationMessage) | ✅ | | [`GPUShaderModule`](https://developer.mozilla.org/en-US/docs/Web/API/GPUShaderModule) | ✅ | | [`GPUSupportedFeatures`](https://developer.mozilla.org/en-US/docs/Web/API/GPUSupportedFeatures) | ✅ | | [`GPUSupportedLimits`](https://developer.mozilla.org/en-US/docs/Web/API/GPUSupportedLimits) | ✅ | | [`GPUMapMode`](https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API#reading_the_results_back_to_javascript) | ✅ | | [`GPUShaderStage`](https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API#create_a_bind_group_layout) | ✅ | | [`GPUUncapturedErrorEvent`](https://developer.mozilla.org/en-US/docs/Web/API/GPUUncapturedErrorEvent) | ✅ | ### Unsupported WebGPU APIs The following WebGPU APIs are **not yet supported** in Durable Objects: | API | Supported? | | ------------------------------------------------------------------ | ---------- | | [`GPU.getPreferredCanvasFormat`](https://developer.mozilla.org/en-US/docs/Web/API/GPU/getPreferredCanvasFormat) | | | [`GPURenderBundle`](https://developer.mozilla.org/en-US/docs/Web/API/GPURenderBundle) | | | [`GPURenderBundleEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/GPURenderBundleEncoder) | | | [`GPURenderPassEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/GPURenderPassEncoder) | | ### Note For information on running machine learning models on Cloudflare's global network, refer to [Workers AI](https://developers.cloudflare.com/workers-ai/). ``` -------------------------------- ### Initialize Cloudflare Project with npm Source: https://developers.cloudflare.com/durable-objects/get-started Creates a new Cloudflare project using npm, selecting a 'Hello World example' with a 'Worker + Durable Objects' template in TypeScript. It sets up version control but defers deployment. ```bash npm create cloudflare@latest -- durable-object-starter cd durable-object-starter ``` -------------------------------- ### Verify Node.js Architecture Source: https://github.com/nvm-sh/nvm After setting up the environment, this command verifies that Node.js is running under the expected architecture (x64 for Rosetta). This confirms that your setup is correctly configured for Intel-based Node.js versions. ```javascript node -p process.arch ``` -------------------------------- ### NVM Install Specific Node.js Versions and Migrate Packages Source: https://github.com/nvm-sh/nvm This demonstrates how to install specific Node.js versions and migrate packages from other specific versions. You can provide version numbers or release channels as sources for package migration. This offers granular control over package management during Node.js upgrades. ```shell nvm install --reinstall-packages-from=5 6 nvm install --reinstall-packages-from=iojs v4.2 ``` -------------------------------- ### Install NVM on Alpine Linux 3.13+ Source: https://github.com/nvm-sh/nvm This snippet installs NVM on Alpine Linux version 3.13 and later. It first adds necessary build and runtime dependencies using `apk add` and then downloads and executes the NVM installation script from a specified URL using `curl` and `bash`. Ensure you have `curl` and `bash` installed before running. ```shell apk add -U curl bash ca-certificates openssl ncurses coreutils python3 make gcc g++ libgcc linux-headers grep util-linux binutils findutils curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash ``` -------------------------------- ### Implement Effective Agent Patterns Guide Source: https://developers.cloudflare.com/llms.txt Guide on implementing common agent patterns using the Agents SDK. ```APIDOC ## Implement Effective Agent Patterns ### Description Guide on implementing common agent patterns using the Agents SDK framework. ### Scope Covers various established patterns for agent behavior and interaction. ### Link /agents/guides/human-in-the-loop/ ### Details Provides practical examples and strategies for robust agent design. ``` -------------------------------- ### Boot Container on Durable Object Start (TypeScript) Source: https://context7_llms This TypeScript code snippet shows how to initiate a container when a Durable Object is first created. It leverages `this.ctx.blockConcurrencyWhile` to manage concurrent operations and calls `this.ctx.container.start()` to boot the container. ```typescript export class MyDurableObject extends DurableObject { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); // boot the container when starting the DO this.ctx.blockConcurrencyWhile(async () => { this.ctx.container.start(); }); } } ``` -------------------------------- ### NVM Which Command Source: https://github.com/nvm-sh/nvm Retrieves the installation path of the Node.js executable for a specified version. This command is helpful for locating the binary if direct execution is needed. ```bash nvm which 12.22 ``` -------------------------------- ### Prompt an AI model Guide Source: https://developers.cloudflare.com/llms.txt Guide on using the Workers 'mega prompt' for building agents. ```APIDOC ## Prompt an AI Model ### Description Guide on using the Workers "mega prompt" to build Agents with preferred AI tools. ### Usage The prompt understands Agents SDK APIs, best practices, and guidelines to facilitate building valid Agents and Workers. ### Link /agents/getting-started/prompting/ ### Details Focuses on best practices and efficient development using the 'mega prompt' feature. ``` -------------------------------- ### Wrangler Deployment Output Example Source: https://developers.cloudflare.com/durable-objects/tutorials/build-a-seat-booking-app Example output from the Wrangler CLI after deploying a Cloudflare Worker. It shows the build process, asset upload, and confirms successful deployment, including available bindings. ```bash ⛅️ wrangler 3.78.8 ------------------- 🌀 Building list of assets...🌀 Starting asset upload...🌀 Found 1 new or modified file to upload. Proceeding with upload... + /index.html Uploaded 1 of 1 assets ✨ Success! Uploaded 1 file (1.93 sec) Total Upload: 3.45 KiB / gzip: 1.39 KiB Your worker has access to the following bindings: - Durable Objects: - FLIGHT: Flight Uploaded seat-book (12.12 sec) Deployed seat-book triggers (5.54 sec) [DEPLOYED_APP_LINK] Current Version ID: [BINDING_ID] ``` -------------------------------- ### Manage Node.js Versions with NVM (Shell) Source: https://github.com/nvm-sh/nvm This snippet demonstrates how to use nvm to switch between installed Node.js versions and install a new version. NVM allows for easy management of different Node.js runtimes per shell session. It requires nvm to be installed and configured in the environment. ```shell $ nvm use 16 Now using node v16.9.1 (npm v7.21.1) $ node -v v16.9.1 $ nvm use 14 Now using node v14.18.0 (npm v6.14.15) $ node -v v14.18.0 $ nvm install 12 Now using node v12.22.6 (npm v6.14.5) $ node -v v12.22.6 ``` -------------------------------- ### Create and Submit GPU Commands with WebGPU Source: https://developer.mozilla.org/en-US/docs/Web/API/GPUCommandEncoder This example demonstrates the creation of a GPUCommandEncoder, setting up a render pass, drawing a triangle, and submitting the encoded commands to the GPU queue. It shows the typical workflow for rendering in WebGPU. ```javascript const commandEncoder = device.createCommandEncoder(); const renderPassDescriptor = { colorAttachments: [ { clearValue: clearColor, loadOp: "clear", storeOp: "store", view: context.getCurrentTexture().createView(), }, ], }; const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); passEncoder.setPipeline(renderPipeline); passEncoder.setVertexBuffer(0, vertexBuffer); passEncoder.draw(3); passEncoder.end(); device.queue.submit([commandEncoder.finish()]); ``` -------------------------------- ### Verify nvm Installation (Shell) Source: https://github.com/nvm-sh/nvm This command verifies if nvm is installed and accessible in the current shell environment. It checks for the 'nvm' shell function. If 'command -v nvm' outputs 'nvm', the installation is successful. Note that 'which nvm' will not work as nvm is a sourced shell function, not an executable. ```shell command -v nvm ```