### Install Project Dependencies (NPM) Source: https://github.com/val-town/val-town-docs/blob/main/README.md Installs all necessary project dependencies listed in the package.json file. This command should be run after cloning the repository or when dependencies are updated. ```Shell npm install ``` -------------------------------- ### Setting up an example Node.js project Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/api/sdk.mdx Provides the necessary bash commands to set up a basic Node.js project using npm. This includes creating a project directory, initializing a `package.json` file, and installing the `@valtown/sdk` package as a project dependency. ```bash # Create a directory for your project mkdir example-project cd example-project # Create a package.json file npm init # Install the SDK npm install @valtown/sdk ``` -------------------------------- ### Start Local Development Server (NPM) Source: https://github.com/val-town/val-town-docs/blob/main/README.md Runs the development server locally, typically accessible at localhost:4321. This command is used for developing and previewing changes to the documentation in real-time. ```Shell npm run dev ``` -------------------------------- ### Get Astro CLI Help (NPM) Source: https://github.com/val-town/val-town-docs/blob/main/README.md Displays the help documentation for the Astro command-line interface. This provides a list of available commands, options, and usage instructions for the Astro CLI. ```Shell npm run astro -- --help ``` -------------------------------- ### Running index.mjs and getting profile information Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/api/sdk.mdx Shows the bash command to execute the `index.mjs` script using Node.js and provides an example of the expected JSON output, confirming that the SDK was successfully initialized and authenticated to retrieve the user's profile information. ```bash node index.mjs { id: '19892fed-baf3-41fb-a5cc-96c80e95edec', bio: '👷 Building Val Town', username: 'tmcw', profileImageUrl: 'https://img.clerk.com/eyJ0eXBl…', tier: 'pro', email: 'tom@macwright.com' } ``` -------------------------------- ### Preview Production Build (NPM) Source: https://github.com/val-town/val-town-docs/blob/main/README.md Serves the production build from the ./dist/ directory locally. This allows testing the built site to ensure it functions correctly before deploying it to a hosting environment. ```Shell npm run preview ``` -------------------------------- ### Running Public Val in Deno Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/interop.md Demonstrates how to execute a public Val Town val directly using the Deno runtime by providing its module URL. Requires Deno installed. ```sh $ deno run https://esm.town/v/tmcw/randomVal 0.5133662021089374 ``` -------------------------------- ### Build Production Site (NPM) Source: https://github.com/val-town/val-town-docs/blob/main/README.md Compiles the project into a production-ready static site, outputting the build files into the ./dist/ directory. This command is used for preparing the documentation site for deployment. ```Shell npm run build ``` -------------------------------- ### Initialize Astro Starlight Project (NPM) Source: https://github.com/val-town/val-town-docs/blob/main/README.md Command to create a new Astro project pre-configured with the Starlight documentation theme. This sets up the basic project structure and dependencies required for the documentation site. ```Shell npm create astro@latest -- --template starlight ``` -------------------------------- ### List Blob Keys Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/blob.mdx Lists blob keys using `blob.list`. It shows how to list all keys and how to filter keys that start with a specific prefix. ```TypeScript import { blob } from "https://esm.town/v/std/blob"; let allKeys = await blob.list(); console.log(allKeys); const appKeys = await blob.list("app_"); console.log(appKeys); // all keys that begin with `app_` ``` -------------------------------- ### Usage of npm:@octokit/core Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/GitHub/get-a-github-user.mdx Shows how to fetch a GitHub user using the `octokit.js` library imported as an npm package. It initializes `Octokit` and uses the `request` method with the appropriate endpoint and headers. ```TypeScript import { Octokit } from "npm:@octokit/core"; export const getGithubUserViaOctokit = async (username: string) => { const octokit = new Octokit(); const user = await octokit.request("GET /users/{username}", { username, headers: { "X-GitHub-Api-Version": "2022-11-28" } }); return user; }; ``` -------------------------------- ### Run Project Tests (NPM) Source: https://github.com/val-town/val-town-docs/blob/main/README.md Executes the test suite defined in the project's package.json. In this project, running tests also triggers the cspell spell-checker to identify and report any typos. ```Shell npm test ``` -------------------------------- ### Expected Output from Puppeteer Example Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/browserless.mdx Displays the expected output when running the Puppeteer example snippet. It shows the text content extracted from the specified paragraph on the Wikipedia page. ```txt "OpenAI is an American artificial intelligence (AI) research laboratory consisting of the non-profit OpenAI Incorporated and its for-profit subsidiary corporation OpenAI Limited Partnership. OpenAI conducts AI research with the declared intention of promoting and developing friendly AI." ``` -------------------------------- ### Run Astro CLI Commands (NPM) Source: https://github.com/val-town/val-town-docs/blob/main/README.md Executes various commands provided by the Astro command-line interface, such as adding integrations (astro add) or checking the project (astro check). The '...' indicates where specific Astro commands are placed. ```Shell npm run astro ... ``` -------------------------------- ### Usage Example for getGithubStars Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/GitHub/github-users-stars-pagination.mdx This snippet demonstrates how to import and use the `getGithubStars` function. It calls the function with the username "stevekrouse" and logs the returned total star count to the console. ```ts import { getGithubStars } from "https://esm.town/v/vtdocs/getGithubStars"; console.log(await getGithubStars("stevekrouse")); ``` -------------------------------- ### Basic Usage Example Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/openai.mdx This snippet demonstrates how to perform a basic chat completion using the `std/openai` library. It initializes the client, sends a simple user message to the `gpt-4` model, and logs the response content. This method uses Val Town's shared API key. ```ts import { OpenAI } from "https://esm.town/v/std/openai"; const openai = new OpenAI(); const completion = await openai.chat.completions.create({ messages: [ { role: "user", content: "Say hello in a creative way" }, ], model: "gpt-4", max_tokens: 30, }); console.log(completion.choices[0].message.content); ``` -------------------------------- ### Versions of external imports Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/reference/version-control.mdx Illustrates how to specify versions for NPM modules imported via the `npm:` specifier. It shows examples of pinning to an exact version and using a version range, recommending pinning for stability. ```ts import { min } from "npm:lodash-es@4.17.21"; // Or you can specify a version range, like // you would in a package.json file: import { min } from "npm:lodash-es@4"; ``` -------------------------------- ### Example Deno Permission Error Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/troubleshooting/permission-errors.md Illustrates a typical permission error encountered in Val Town when a module attempts an disallowed operation, such as reading from the filesystem without the necessary `--allow-read` flag. ```json { "error": "Requires read access to , run again with the --allow-read flag" } ``` -------------------------------- ### Querying Data from a Val Town SQLite Table Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/SQLite/usage.mdx This example demonstrates how to fetch all `key` and `value` pairs from the `kv` table using a simple `SELECT` statement with `sqlite.execute`. ```TypeScript import { sqlite } from "https://esm.town/v/std/sqlite"; console.log(await sqlite.execute(`select key, value from kv`)); ``` -------------------------------- ### Importing Val in Node.js ESM File Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/interop.md Provides an example of importing a Val Town val into a Node.js script using ES Module syntax in a .mjs file. Requires Node.js with the --experimental-network-imports flag enabled. ```js // index.mjs import rand from "https://esm.town/v/tmcw/randomVal"; console.log(rand); ``` -------------------------------- ### Using the SDK in Val Town Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/api/sdk.mdx Demonstrates how to use the Val Town SDK directly within a Val Town environment. Authentication is handled automatically via the `VAL_TOWN_API_KEY` environment variable provided by Val Town. The example shows retrieving the current user's profile, listing their vals, and listing vals they have liked. ```ts import ValTown from "npm:@valtown/sdk"; const vt = new ValTown(); // print your username const me = await vt.me.profile.retrieve(); console.log(me.email); // list some of your vals const { data: vals } = await vt.users.vals.list(me.id, {}); console.log(vals); // list vals you've liked const { data: likes } = await vt.me.likes.list({}); console.log(likes); ``` -------------------------------- ### Usage of @vtdocs/getGithubUser Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/GitHub/get-a-github-user.mdx Demonstrates how to import and call the `getGithubUser` function defined in the previous snippet. It logs the result for the username "stevekrouse". ```TypeScript import { getGithubUser } from "https://esm.town/v/vtdocs/getGithubUser"; console.log(await getGithubUser("stevekrouse")); ``` -------------------------------- ### Basic Val Town SQLite Usage: Create, Insert, Query Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/SQLite/usage.mdx This example illustrates fundamental SQLite operations in Val Town, including creating a table if it doesn't exist, inserting data using parameterized queries, querying data with parameters, and mapping the raw result rows into an array of objects. ```TypeScript import { sqlite } from "https://esm.town/v/std/sqlite"; await sqlite.execute(`create table if not exists kv( key text unique, value text )`); const key = crypto.randomUUID(); await sqlite.execute({ sql: `insert into kv(key, value) values(?, ?)`, args: [key, "value1"] }); const result = await sqlite.execute({ sql: `select * from kv where key = ?`, args: [key] }); console.log(result); // { // columns: [ "key", "value" ], // columnTypes: [ "TEXT", "TEXT" ], // rows: [ [ "d65991f8-6f03-4275-bcf1-1fdb1164e153", "value1" ] ], // rowsAffected: 0, // lastInsertRowid: null // } const rows: { key: string; value: string }[] = result.rows.map(row => Object.fromEntries(row.map((value, index) => [result.columns[index], value])) as any ); console.log(rows); // [ { key: "d65991f8-6f03-4275-bcf1-1fdb1164e153", value: "value1" } ] ``` -------------------------------- ### Image Input Example Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/openai.mdx This snippet shows how to include an image in a chat completion request by converting a file to a data URL using `stevekrouse/fileToDataURL`. It sets up a system role and sends the image data URL within the user message content to the `gpt-4o` model. ```ts import { fileToDataURL } from "https://esm.town/v/stevekrouse/fileToDataURL"; const dataURL = await fileToDataURL(file); const response = await chat([ { role: "system", content: `You are an nutritionist. Estimate the calories. We only need a VERY ROUGH estimate. Respond ONLY in a JSON array with values conforming to: {ingredient: string, calories: number} `, }, { role: "user", content: [{ type: "image_url", image_url: { url: dataURL, }, }], }, ], { model: "gpt-4o", max_tokens: 200, }); ``` -------------------------------- ### Running Private Val in Deno with Token Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/interop.md Shows how to run a private Val Town val in Deno by setting the DENO_AUTH_TOKENS environment variable with an API token for the esm.town domain. Requires a Val Town API token and Deno installed. ```sh $ DENO_AUTH_TOKENS=xxx@esm.town deno run https://esm.town/v/tmcw/privateVal Hello world! ``` -------------------------------- ### index.mjs Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/api/sdk.mdx Contains the core JavaScript/TypeScript code for the Node.js example. It demonstrates importing the Val Town SDK and making a basic API call to retrieve the current user's profile. The file uses ESM import syntax, requiring a `.mjs` extension or setting `"type": "module"` in `package.json`. ```ts import ValTown from "@valtown/sdk"; const valTown = new ValTown(); async function main() { const myProfile = await valTown.me.profile.retrieve(); console.log(myProfile); } main(); ``` -------------------------------- ### @vtdocs/getGithubUser Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/GitHub/get-a-github-user.mdx Defines an asynchronous function `getGithubUser` that takes a username and fetches the corresponding GitHub user object using `fetchJSON`. It constructs the API URL dynamically. ```TypeScript import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41"; export const getGithubUser = async (username: string) => { const user = await fetchJSON( `https://api.github.com/users/${username}`, ); return user; }; ``` -------------------------------- ### Example of Merge Conflict Markers Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/vals/branches.mdx This snippet illustrates the standard format used to indicate merge conflicts in text files within version control systems. It shows the conflicting sections from the 'main' branch and the 'branch' separated by markers. ```text <<<<<<< main This is the main branch ======= This is the branch >>>>>>> branch ``` -------------------------------- ### Using Hono Cache Middleware for Cache Control (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/vals/http/cdns.mdx Shows how to integrate Hono's built-in `cache` middleware to manage cache control headers for routes. Configures caching for all GET requests (`*`) with a public cache for 5 minutes (300 seconds). Requires the `hono` library. ```TypeScript import { cache } from "hono/cache"; import { Hono } from "hono"; const app = new Hono(); app.get( "*", cache({ cacheName: "my-app", cacheControl: "public, max-age=300", // cache for 5 minutes wait: true, }) ); app.get("/", (c) => { return c.html("Hello, world!"); }); ``` -------------------------------- ### Using gsheet_call for Google Sheets API in TypeScript Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/google-sheets.mdx This snippet demonstrates how to use the `gsheet_call` function to interact with the Google Sheets API. It shows examples of appending data using a POST request and reading data using a GET request, requiring a Google service account key from environment variables and a specific sheet ID. ```TypeScript import { gsheet_call } from "https://esm.town/v/mattx/gsheet_call"; // Appending to a sheet await gsheet_call( Deno.env.get("google_sa"), "1LDgOhO6Fxg2wt5rGFH29t6XYbmKe6fXI7fLSFaqZkDA", "POST", "values/A1:C1:append?valueInputOption=RAW", { values: [[Date(), Math.random(), 1]] }, ); // Reading from the top of the sheet const data = await gsheet_call( Deno.env.get("google_sa"), "1LDgOhO6Fxg2wt5rGFH29t6XYbmKe6fXI7fLSFaqZkDA", "GET", "values/A1:C1?majorDimension=ROWS", {}, ); console.log(data["values"][0]); ``` -------------------------------- ### Get JSON Blob Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/blob.mdx Retrieves a JSON blob by its key using `blob.getJSON`. It imports the `blob` module and logs the result, which will be `undefined` if the key is not found. ```TypeScript import { blob } from "https://esm.town/v/std/blob"; let blobDemo = await blob.getJSON("myKey"); console.log(blobDemo); // returns `undefined` if not found ``` -------------------------------- ### Downloading a file from AWS S3 using s3_lite_client in Val Town Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/s3.mdx This snippet shows how to download a file from an AWS S3 bucket using the `s3_lite_client` library in Val Town. It initializes the S3 client similarly to the upload example and then uses `getObject` to retrieve the file content as a standard HTTP Response object, which is then read as text. ```TypeScript import { S3Client } from "https://deno.land/x/s3_lite_client@0.6.1/mod.ts"; const s3client = new S3Client({ endPoint: `s3.${Deno.env.get("awsS3Region")}.amazonaws.com`, region: Deno.env.get("awsS3Region"), bucket: Deno.env.get("awsS3Bucket"), accessKey: Deno.env.get("awsS3Key"), secretKey: Deno.env.get("awsS3Secret"), }); const res = await s3client.getObject("filename.txt"); console.log(await res.text()); ``` -------------------------------- ### Accessing Environment Variables with Deno.env (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/reference/environment-variables.mdx Demonstrates how to retrieve an environment variable named 'someSdkSecret' using the Deno.env.get() method, commonly used in Deno environments, and assign it to a variable for use, for example, in initializing an SDK. ```ts const secret = Deno.env.get("someSdkSecret"); export let sdk = new SomeSDK(secret); ``` -------------------------------- ### Connecting to Neon Postgres with deno-postgres Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/Databases/neon-postgres.mdx This snippet demonstrates how to connect to a Neon Postgres database from a Val Town val using the deno-postgres library. It initializes a client with the connection URL retrieved from an environment variable named 'neon_url', connects to the database, executes a simple query to get the current time, and logs the result. Requires the 'deno-postgres' dependency and the 'neon_url' environment variable to be set. ```ts import { Client } from "https://deno.land/x/postgres/mod.ts"; const client = new Client(Deno.env.get("neon_url")); await client.connect(); const result = await client.queryObject`select CURRENT_TIME;`; console.log(result); ``` -------------------------------- ### Accessing Airtable Data in Val Town Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/airtable.mdx This snippet demonstrates how to initialize the Airtable client in Val Town using a Deno library. It shows how to retrieve the API key from environment variables and configure the base ID and table name. The example then performs a select operation to fetch data from the specified table. ```TypeScript import { Airtable } from "https://deno.land/x/airtable@v1.1.1/mod.ts"; const airtable = new Airtable({ apiKey: Deno.env.get("airtable_pat"), baseId: "appXSrKDlwbAijRmD", tableName: "All content", }); // Sample data from: https://blog.airtable.com/database-vs-spreadsheet/ const results = await airtable.select(); console.log(results); ``` -------------------------------- ### Embedding New Val Template with Code Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/embed.mdx Shows how to embed a new Val Town val template pre-populated with specific code. The code is passed as a URL parameter to the /embed/new endpoint, allowing readers to easily remix a starting point. ```TypeScript const myNewEmbeddedVal = `The time this ran was ${new Date().toLocaleTimeString()}`; ``` -------------------------------- ### Using feTS Client with Type Safety (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/vals/http/routing.mdx This snippet demonstrates creating a type-safe client using feTS to interact with a feTS server deployed on Val Town. It imports the router type from the server val, creates a client instance pointing to the server's endpoint, makes a GET request to the '/greetings' path, and logs the typed response. ```tsx val import { type router } from "https://esm.town/v/user/fetsServer"; import { createClient } from "npm:fets"; const client = createClient({ endpoint: "https://user-fetsServer.web.val.run", }); // The `response` and `greetings` have proper types automatically inferred const response = await client["/greetings"].get(); const greetings = await response.json(); console.log(greetings); ``` -------------------------------- ### Specify JSX Import Source Pragma (Preact) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/vals/http/jsx.mdx This comment is a per-file pragma used by the TypeScript compiler to specify the module where JSX factory functions (like `h` or `React.createElement`) should be imported from. This example shows how to configure it for Preact imported from esm.sh. ```tsx /** @jsxImportSource https://esm.sh/preact */ ``` -------------------------------- ### Using Recommended std/blob.setJSON in Val Town (New Method) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/troubleshooting/std-set-permission-error.md Shows the recommended way to persist JSON data in Val Town using `std/blob.setJSON`. This method is the modern alternative to `std/set`, does not require the `val:write` scope, and is the preferred approach for storing data. ```js // Using std/blob import { blob } from "https://esm.town/v/std/blob"; blob.setJSON("createdAt", Date.now()); ``` -------------------------------- ### Conditionally Disabling Cache-Control for Development Domains (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/vals/http/cdns.mdx Modifies the basic cache control example to check the request hostname. If the hostname ends with `.val.run`, the `Cache-Control` header is set to an empty string, effectively disabling caching for development URLs while enabling it for custom domains. ```TypeScript export default (req: Request) => { const url = new URL(req.url); return new Response("Hello, world!", { headers: { "Cache-Control": url.hostname.endsWith(".val.run") ? "" : "public, max-age=3600", }, }); }; ``` -------------------------------- ### Using Deprecated std/set in Val Town (Old Method) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/troubleshooting/std-set-permission-error.md Demonstrates the deprecated method of persisting data in Val Town using `std/set`. This requires the `val:write` scope, which is no longer granted by default. Users encountering errors with `std/set` should migrate to `std/blob.setJSON`. ```js // Using std/set import { set } from "https://esm.town/v/std/set"; set("createdAt", Date.now()); ``` -------------------------------- ### Public Val Using Private Environment Variables (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/reference/permissions.mdx Shows a public Val connecting to an external service (Upstash Redis) using credentials stored in private environment variables (`upstashURL`, `upstashToken`). The example demonstrates that the variables are used internally for computation, but their values are not exposed to users viewing the public Val, only the result of the operation. ```ts import { Redis } from "npm:@upstash/redis"; const redis = new Redis({ url: Deno.env.get("upstashURL"), token: Deno.env.get("upstashToken"), }); await redis.set("json-ex-1", { a: { b: "nested json" } }); const get = await redis.get("json-ex-1"); console.log(get); ``` ```ts nested json ``` -------------------------------- ### Accessing Google Sheets API via Pipedream (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/google-sheets.mdx This TypeScript code demonstrates how to fetch a fresh Google Sheets OAuth access token using the Pipedream Accounts API and a Pipedream API key stored as a Val Town environment variable. It then uses this token to make authenticated requests to the Google Sheets API, showing examples for appending data and reading data from a specified sheet. ```TypeScript import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41"; const accountID = ""; const sheetID = ""; const baseURL = `https://sheets.googleapis.com/v4/spreadsheets/${sheetID}/values`; async function fetchAccessToken() { const response = await fetch( `https://api.pipedream.com/v1/accounts/${accountID}?include_credentials=1`, { headers: { Authorization: `Bearer ${Deno.env.get("pipedream_api_key")}`, }, }, ); if (!response.ok) { throw new Error(`Error fetching access token: ${response.statusText}`); } const { data } = await response.json(); return data.credentials.oauth_access_token; } async function makeSheetsRequest(url, method, body = null) { const accessToken = await fetchAccessToken(); const options: RequestInit = { method, headers: { Authorization: `Bearer ${accessToken}`, }, }; if (body) { options.body = JSON.stringify(body); } return fetchJSON(url, options); } // Write data to a sheet await makeSheetsRequest( `${baseURL}/A1:C1:append?valueInputOption=RAW`, "POST", { values: [[Date(), Math.random(), 1]] }, ); // Read data from a sheet const data = await makeSheetsRequest( `${baseURL}/A1:C1?majorDimension=ROWS`, "GET", ); console.log(data.values[0]); ``` -------------------------------- ### Adding an HTML Form to a Webpage (HTML) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/save-html-form-data.mdx This snippet provides a complete HTML page example demonstrating how to add a form that submits data to a Val Town HTTP endpoint. Users should replace the `action` attribute value with their specific Val Town endpoint URL. The form includes a required email input field. ```html Email Form

``` -------------------------------- ### Ignore Words in Spell Check (YAML Frontmatter) Source: https://github.com/val-town/val-town-docs/blob/main/README.md Example of adding a cspell:ignore comment within a document's frontmatter section. This configuration tells the cspell spell-checker to ignore specific words listed on that line only within that particular file. ```YAML --- title: Your first cron val description: Make your first cron val - a weather notifier lastUpdated: 2024-05-09 # cspell:ignore crongpt --- ``` -------------------------------- ### Astro/npm Development Commands Source: https://github.com/val-town/val-town-docs/blob/main/CLAUDE.md Essential npm scripts for building, running the development server, previewing the build, and type checking the Astro documentation project. ```Shell npm run build ``` ```Shell npm run dev ``` ```Shell npm run preview ``` ```Shell npm run astro check ``` -------------------------------- ### Interacting with Built Node.js Package Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/interop.md Demonstrates how to use the Node.js package built by dnt by requiring it in the Node REPL. Shows the output when the package is required, indicating successful build and import. Requires Node.js and the npm directory created by dnt. ```sh $ npm node Welcome to Node.js v18.18.0. Type ".help" for more information. > require('./') 0.402717678920262 {} ``` -------------------------------- ### Using Personal API Key Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/openai.mdx This snippet demonstrates how to initialize the OpenAI client using the official `npm:openai` package. This approach requires you to set your own `OPENAI_API_KEY` environment variable in your Val Town settings, bypassing the limits of the shared key. ```ts import { OpenAI } from "npm:openai"; const openai = new OpenAI(); ``` -------------------------------- ### Running dnt Build Script Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/interop.md Command to execute the Deno build script (build.ts) using deno run -A, which grants all permissions needed by dnt to build the Node.js package. Requires Deno and the build.ts file. ```sh $ deno run -A build.ts [dnt] Transforming... [dnt] Running npm install... added 3 packages, and audited 4 packages in 543ms found 0 vulnerabilities [dnt] Building project... [dnt] Type checking ESM... [dnt] Emitting ESM package... [dnt] Emitting script package... [dnt] Running post build action... [dnt] Running tests... > test > node test_runner.js [dnt] Complete! ``` -------------------------------- ### Deleting Data from Val Town SQLite with Named Parameters Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/SQLite/usage.mdx This example demonstrates how to remove a specific row from the `kv` table using `sqlite.execute` with a parameterized `DELETE` query that filters by `key` using a named parameter (`:key`). ```TypeScript import { sqlite } from "https://esm.town/v/std/sqlite"; await sqlite.execute({ sql: `delete from kv where key = :key`, args: { key: "specialkey" }, }); ``` -------------------------------- ### Accessing Allowed System Information in Val Town (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/troubleshooting/permission-errors.md Demonstrates how to access specific system information using the `node:os` module and `Deno` runtime functions that are permitted within the Val Town sandbox, including CPU details, home directory, OS release, and hostname. ```ts import os from "node:os"; os.cpus(); os.homedir(); Deno.osRelease(); Deno.hostname(); ``` -------------------------------- ### Running Node.js Script with Network Imports Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/interop.md Command to execute a Node.js script (index.mjs) that imports a Val Town val via HTTP/S, requiring the --experimental-network-imports flag. Requires Node.js and the script file. ```sh $ node --experimental-network-imports index.mjs 0.4050279110448427 ``` -------------------------------- ### Building Node.js Package with dnt Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/interop.md A Deno script (build.ts) that uses the dnt library to build a Node.js compatible package from the index.ts shim file. It clears the output directory, configures the build process, and specifies package details. Requires Deno and the dnt library. ```ts // build.ts import { build, emptyDir } from "https://deno.land/x/dnt/mod.ts"; await emptyDir("./npm"); await build({ entryPoints: ["index.ts"], outDir: "./npm", typecheck: false, shims: { deno: true, }, package: { name: "your-val", version: Deno.args[0], description: "Your package.", }, postBuild() {}, }); ``` -------------------------------- ### Using another's val as a library Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/reference/permissions.mdx Demonstrates importing a function (`gpt3`) from another user's val (`patrickjm/gpt3`) and using it. It shows how to pass data and environment variables (`Deno.env.get("openai")`) to the imported function. The import uses version pinning (`?v=4`). ```TypeScript import { gpt3 } from "https://esm.town/v/patrickjm/gpt3?v=4"; export let librarySecret = gpt3({ prompt: "what is the meaning of life?", openAiKey: Deno.env.get("openai") }); ``` -------------------------------- ### Setting your Val Town API Token Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/api/sdk.mdx Instructs the user on how to authenticate the Node.js application by setting the `VAL_TOWN_API_KEY` environment variable in their terminal. This variable should contain an API token obtained from the Val Town settings page. ```bash export VAL_TOWN_API_KEY=your api token… ``` -------------------------------- ### Making a Proxied Fetch Request with std/fetch Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/fetch.md This snippet demonstrates how to import and use the `std/fetch` function from the Val Town standard library to make an HTTP request. It fetches the current IP address from an external service and logs it to the console, illustrating the use of the proxied fetch. ```typescript import { fetch } from "https://esm.town/v/std/fetch"; let result = await fetch("https://api64.ipify.org?format=json"); let json = await result.json(); console.log(json.ip); ``` -------------------------------- ### Accessing Query Parameters with HTTP Val Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/troubleshooting/express-to-http-migration.md This HTTP val snippet shows how to access query string parameters using the web-standard `Request` object. It involves parsing the URL from `req.url` and using the `URLSearchParams` API to get a specific parameter by name. ```TypeScript export function handler(req) { return new Response(new URL(req.url).searchParams.get("name")); } ``` -------------------------------- ### Creating TypeScript Shim for dnt Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/interop.md Defines a TypeScript file (index.ts) that re-exports a Val Town val from its esm.town URL. This file serves as an entry point for the dnt tool to process the val for Node.js compatibility. Requires Deno and the val URL. ```ts // index.ts export * from "https://esm.town/v/tmcw/randomVal?v=3"; ``` -------------------------------- ### Creating Initial Users Table (Migration 1) - TypeScript Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/SQLite/migrations.mdx This TypeScript snippet demonstrates the first migration step: creating the initial 'users' table in the Val Town SQLite database. It defines columns for 'id' (primary key, auto-incrementing) and 'email' (text, not null, unique). It requires the 'v/std/sqlite' dependency. ```ts import { sqlite } from "https://esm.town/v/std/sqlite"; await sqlite.execute(` create table users ( id integer primary key autoincrement, email text not null unique ) `); ``` -------------------------------- ### Initializing Drizzle ORM and Querying SQLite Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/SQLite/orms.mdx This snippet demonstrates how to set up Drizzle ORM with Val Town's built-in SQLite instance. It initializes Drizzle, defines a simple 'kv' table schema, and performs a basic select query to fetch all rows from that table. This requires importing modules from 'drizzle-orm', 'drizzle-orm/libsql', 'drizzle-orm/sqlite-core' via npm and the 'std/sqlite' val. ```ts import { sqlite } from "https://esm.town/v/std/sqlite"; import { sql } from "npm:drizzle-orm"; import { drizzle } from "npm:drizzle-orm/libsql"; import { integer, sqliteTable, text } from "npm:drizzle-orm/sqlite-core"; const db = drizzle(sqlite as any); const kv = sqliteTable("kv", { key: text("key").primaryKey(), value: text("value").notNull(), }); const sqliteDrizzleExample = await db.select().from(kv).all(); console.log(sqliteDrizzleExample); ``` -------------------------------- ### Creating a Table in Val Town SQLite Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/SQLite/usage.mdx This snippet shows the SQL command executed via `sqlite.execute` to create a table named `kv` with `key` and `value` columns, ensuring it only creates the table if it doesn't already exist. ```TypeScript import { sqlite } from "https://esm.town/v/std/sqlite"; await sqlite.execute(`create table if not exists kv( key text unique, value text )`); ``` -------------------------------- ### Create Table using Postgres Client (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/Databases/supabase.mdx This snippet demonstrates creating a table in Supabase using a generic Postgres client via the 'supaBaseQuery' utility. It executes a SQL 'CREATE TABLE' statement using a connection string obtained from environment variables. The statement defines the schema for 'my_first_table'. ```TypeScript import { supaBaseQuery } from "https://esm.town/v/vtdocs/supaBaseQuery"; await supaBaseQuery( Deno.env.get("supabasePostgres"), `create table my_first_table ( id bigint generated by default as identity primary key, inserted_at timestamp with time zone default timezone('utc'::text, now()) not null, updated_at timestamp with time zone default timezone('utc'::text, now()) not null, data jsonb, name text );` ); ``` -------------------------------- ### Creating a PlanetScale Table (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/Databases/planetscale.mdx This snippet demonstrates how to create a new table named `stock` in the PlanetScale database using the `queryPlanetScale` helper. It defines the table schema with `id`, `name`, and `price` columns, using environment variables for database credentials. ```ts import { queryPlanetScale } from "https://esm.town/v/vtdocs/queryPlanetScale"; await queryPlanetScale( { host: Deno.env.get("planetScaleHost"), username: Deno.env.get("planetScaleUsername"), password: Deno.env.get("planetScalePassword"), }, `CREATE TABLE stock ( id int NOT NULL AUTO_INCREMENT PRIMARY KEY, name varchar(255) NOT NULL, price varchar(255) NOT NULL );` ); ``` -------------------------------- ### Saving data in Upstash Redis with Val Town Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/Databases/upstash.mdx Initialize the Upstash Redis client using environment variables for the URL and token. This snippet demonstrates setting a simple key-value pair ("foo" to "bar") and then retrieving the value to verify the connection and operation. Requires the `@upstash/redis` npm package and `upstashURL` and `upstashToken` environment variables. ```TypeScript import { Redis } from "npm:@upstash/redis"; const redis = new Redis({ url: Deno.env.get("upstashURL"), token: Deno.env.get("upstashToken") }); console.log(await redis.set("foo", "bar")); console.log(await redis.get("foo")); ``` -------------------------------- ### Importing Val in Browser Script Module Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/interop.md Illustrates how to import a Val Town val into a web browser using an HTML script tag with type="module". The val is imported via its esm.town URL and then used in the script. Requires a modern browser supporting ES Modules. ```html ``` -------------------------------- ### Saving JSON in Upstash Redis with Val Town Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/Databases/upstash.mdx Initialize the Upstash Redis client and demonstrate saving a complex JSON object directly as a value. The SDK automatically handles the serialization and deserialization of the JSON data. The example sets a nested object and then retrieves a specific nested property. Requires the `@upstash/redis` npm package and `upstashURL` and `upstashToken` environment variables. ```TypeScript import { Redis } from "npm:@upstash/redis"; const redis = new Redis({ url: Deno.env.get("upstashURL"), token: Deno.env.get("upstashToken") }); await redis.set("json-ex-1", { a: { b: "nested json" } }); console.log(((await redis.get("json-ex-1")) as any).a.b); ``` -------------------------------- ### Scraping with Puppeteer and Browserless in TypeScript Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/browserless.mdx Shows how to use the Puppeteer library to connect to a headless browser instance hosted by Browserless from Val Town. It navigates to a specified URL, executes arbitrary JavaScript on the page using `page.evaluate` to extract content, and then closes the browser connection. Requires a Browserless API key. ```ts import { PuppeteerDeno } from "https://deno.land/x/puppeteer@16.2.0/src/deno/Puppeteer.ts"; const puppeteer = new PuppeteerDeno({ productName: "chrome", }); const browser = await puppeteer.connect({ browserWSEndpoint: `wss://chrome.browserless.io?token=${Deno.env.get("browserless")}`, }); const page = await browser.newPage(); await page.goto("https://en.wikipedia.org/wiki/OpenAI"); const intro = await page.evaluate( `document.querySelector('p:nth-of-type(2)').innerText` ); await browser.close(); console.log(intro); ``` -------------------------------- ### Linking to Stripe Payment Link in HTML Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/stripe.mdx Shows how to create a simple HTML anchor tag that redirects users to a Stripe Payment Link URL for initiating a payment without requiring a backend. ```HTML Buy ``` -------------------------------- ### Inserting Data into PlanetScale (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/Databases/planetscale.mdx This snippet shows how to insert a new row into the `stock` table. It uses the `queryPlanetScale` helper with a parameterized `INSERT` statement to add a record for "banana" with a price of 15, retrieving database credentials from environment variables. ```ts import { queryPlanetScale } from "https://esm.town/v/vtdocs/queryPlanetScale"; await queryPlanetScale( { host: Deno.env.get("planetScaleHost"), username: Deno.env.get("planetScaleUsername"), password: Deno.env.get("planetScalePassword"), }, `INSERT INTO stock (name, price) VALUES (?, ?);`, ["banana", 15] ); ``` -------------------------------- ### Handling CORS Preflight Requests in Val Town Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/troubleshooting/cors.mdx Shows how to explicitly handle HTTP OPTIONS requests to gain full control over CORS preflight responses, setting status 204 and including necessary Access-Control-* headers like Allow-Origin, Allow-Methods, Allow-Headers, and Max-Age. ```javascript export async function myEndpoint(req) { if (req.method === "OPTIONS") { return new Response(null, { status: 204, headers: { "Access-Control-Allow-Origin": "https://specific-domain.com", "Access-Control-Allow-Methods": "GET,POST", "Access-Control-Allow-Headers": "*", "Access-Control-Max-Age": "86400" } }); } // Handle the actual request return Response.json({ message: "Hello" }); } ``` -------------------------------- ### Registering Discord /ping Slash Command (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/Discord/how-to-make-a-discord-bot-hosted-24-7-for-free-in-.mdx This TypeScript snippet imports a utility function to register a Discord slash command. It uses environment variables `discordAppId` and `discordBotToken` to define a new command named "ping" with a simple description. Running this code adds the `/ping` command to the bot's available commands on Discord, allowing users to trigger it. ```TypeScript import { registerDiscordSlashCommand } from "https://esm.town/v/neverstew/registerDiscordSlashCommand"; const result = await registerDiscordSlashCommand( Deno.env.get("discordAppId"), Deno.env.get("discordBotToken"), { name: "ping", description: "Say hi to your bot", }, ); export const registerDiscordCommand = result.json(); ``` -------------------------------- ### Send Basic Email using std/email (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/std/email.md Imports the `email` function from `std/email` and sends a simple email with a subject and text body. This demonstrates the minimal required parameters for sending an email to the account owner. Requires importing `https://esm.town/v/std/email`. ```ts import { email } from "https://esm.town/v/std/email"; await email({ subject: "New Ink & Switch Post!", text: "https://www.inkandswitch.com/embark/" }); ``` -------------------------------- ### Setting Response Details with HTTP Val Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/troubleshooting/express-to-http-migration.md This HTTP val snippet shows how to set the HTTP status code and headers by passing an options object as the second argument to the `Response` constructor, providing an alternative to the chaining pattern used in Express. ```TypeScript export function handler(req) { return new Response("Hello world", { status: 200, headers: { "Content-Type": "text/plain", }, }); } ``` -------------------------------- ### Run Spell Check Command Source: https://github.com/val-town/val-town-docs/blob/main/CLAUDE.md The npm command used to execute the spell checker (cspell) against the project files. ```Shell npm test ``` -------------------------------- ### Querying Supabase Data with supaBaseQuery (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/Databases/supabase.mdx This TypeScript snippet demonstrates how to query data from a Supabase PostgreSQL database using the `supaBaseQuery` helper val. It retrieves the database connection string from environment variables, executes a parameterized SQL query, and logs the result. Requires the `supaBaseQuery` val and a Supabase connection string configured in environment variables. ```TypeScript import { supaBaseQuery } from "https://esm.town/v/vtdocs/supaBaseQuery"; const data = await supaBaseQuery( Deno.env.get("supabasePostgres"), `SELECT NAME, DATA FROM MY_FIRST_TABLE WHERE NAME = $1;`, ["Alice"] ); console.log(data); ``` -------------------------------- ### Scraping HTML with Cheerio in TypeScript Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/guides/web-scraping.mdx This snippet demonstrates how to fetch HTML content from a URL using `fetchText` and then parse it using the `cheerio` library. It uses a CSS selector (`p:nth-of-type(2)`) to find a specific paragraph element and extracts its text content. The result is logged to the console. Dependencies include `fetchText` (from `esm.town`) and `cheerio` (from `npm`). ```TypeScript import { fetchText } from "https://esm.town/v/stevekrouse/fetchText?v=6"; import { load } from "npm:cheerio"; const html = await fetchText( "https://en.wikipedia.org/wiki/OpenAI", ); const $ = load(html); // Cheerio accepts a CSS selector, here we pick the second

const intro = $("p:nth-of-type(2)").first().text(); console.log(intro); ``` ```txt OpenAI is an American artificial intelligence (AI) research organization consisting of the non-profit OpenAI, Inc.[5] registered in Delaware and its for-profit subsidiary OpenAI Global, LLC.[6] One of the leading organizations of the AI Spring,[7][8][9] OpenAI researches artificial intelligence with the declared intention of developing "safe and beneficial" artificial general intelligence, which it defines as "highly autonomous systems that outperform humans at most economically valuable work".[10] OpenAI has developed several large language models, advanced image generation models, and previously, also open-source models.[11][12] ``` -------------------------------- ### Querying Data from PlanetScale (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/integrations/Databases/planetscale.mdx This snippet illustrates how to query data from the `stock` table. It uses the `queryPlanetScale` helper with a `SELECT` statement to retrieve the `id`, `name`, and `price` for the item named "banana", logging the first row of the results to the console. ```ts import { queryPlanetScale } from "https://esm.town/v/vtdocs/queryPlanetScale"; const results = await queryPlanetScale( { host: Deno.env.get("planetScaleHost"), username: Deno.env.get("planetScaleUsername"), password: Deno.env.get("planetScalePassword"), }, `SELECT id, name, price FROM stock WHERE name=?`, ["banana"] ); console.log(results.rows[0]); ``` -------------------------------- ### Conditionally Applying Hono Cache Middleware for Development Domains (TypeScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/vals/http/cdns.mdx Wraps the Hono cache middleware application within a custom middleware. It checks if the request hostname ends with `.val.run`. If true, it skips the cache middleware and proceeds to the next handler; otherwise, it applies the cache middleware. Requires the `hono` library. ```TypeScript app.get("*", async (c, next) => { const url = new URL(c.req.url); if (url.hostname.endsWith(".val.run")) { return next(); } return cache({ cacheName: "my-app", cacheControl: "public, max-age=300", wait: true, })(c, next); }); ``` -------------------------------- ### Calling Secured Endpoint With Authentication (TypeScript/JavaScript) Source: https://github.com/val-town/val-town-docs/blob/main/src/content/docs/reference/permissions.mdx Demonstrates successfully accessing the secured HTTP endpoint (`user/secretEndpoint`) by providing the correct `Authorization` header containing the secret value from an environment variable, showing the resulting 200 OK response object logged to the console. ```ts import { fetch } from "https://esm.town/v/std/fetch"; const response = await fetch("https://user-secretEndpoint.web.val.run", { headers: { Authorization: "birdsarentreal" }, }); console.log(response); ``` ```js Response { body: ReadableStream { locked: false }, bodyUsed: false, headers: Headers { /* omitted */ }, ok: true, redirected: false, status: 200, statusText: "OK", url: "http://localhost:3001/v1/fetch?url=https%3A%2F%2Fuser-secretEndpoint.web.val.run" } ```