### jsPDF Example Setup Source: https://www.val.town/v/maxm/jsPDFExample This snippet shows the initial setup for a Val Town application, including environment variable configuration and import statements for routing modules. It's essential for bootstrapping the application. ```javascript ((storageKey2, restoreKey) => { if (!window.history.state || !window.history.state.key) { let key = Math.random().toString(32).slice(2); window.history.replaceState({ key }, ""); } try { let positions = JSON.parse(sessionStorage.getItem(storageKey2) || "{}"); let storedY = positions[restoreKey || window.history.state.key]; if (typeof storedY === "number") { window.scrollTo(0, storedY); } } catch (error) { console.error(error); sessionStorage.removeItem(storageKey2); } })("react-router-scroll-positions", null) window.ENV = {"REACT_APP_SENTRY_DSN":"https://586020d86f05489db63a554690acf1e9@o1398359.ingest.sentry.io/6724499","VAL_RUNTIME_NAME":"prod","RENDER_GIT_COMMIT":"9b8091bec2c7db35552d7861cae336baeccbf869","RENDER_GIT_BRANCH":"main","POSTHOG_API_TOKEN":"phc_nmoyuAkStEZuUp69rYlg1DZgrIt19Gx0Y4Hwf8tGgJP","POSTHOG_API_HOST":"https://wart.val.town","WEB_API_TEMPLATE":"https://{val}.web.val.run","APP_URL":"https://www.val.town","MODULE_URL":"https://esm.town","VANITY_WEB_API_TEMPLATE":"https://{label}.val.run/","DENOLS_URL":"https://lsp.val.town","NODE_ENV":"production","CLOUDFLARE_TURNSTILE_SITE_KEY":"0x4AAAAAACtaIZJH7s9rBMZ6","GOOGLE_CLIENT_ID":"875989696899-jtsqkhlbdv5jrlsk8631p7ipjg3c6o62.apps.googleusercontent.com","API_URL":"https://api.val.town"} window.__reactRouterContext = {"basename":"/","future":{"unstable_optimizeDeps":true,"v8_passThroughRequests":false,"unstable_trailingSlashAwareDataRequests":false,"unstable_previewServerPrerendering":false,"v8_middleware":false,"v8_splitRouteModules":false,"v8_viteEnvironmentApi":false},"routeDiscovery":{"mode":"initial"},"ssr":true,"isSpaMode":false}; window.__reactRouterContext.stream = new ReadableStream({ start(controller){ window.__reactRouterContext.streamController = controller; } }).pipeThrough(new TextEncoderStream()); import "https://static2.esm.town/assets/manifest-42c6a8a4.js"; import * as route0 from "https://static2.esm.town/assets/root-DsgFEc4B.js"; import * as route1 from "https://static2.esm.town/assets/_app-D96LoZnJ.js"; import * as route2 from "https://static2.esm.town/assets/route-DASihl3B.js"; import * as route3 from "https://static2.esm.town/assets/route-_rx8SiQF.js"; window.__reactRouterRouteModules = { "root": route0, "routes/_app": route1, "routes/_app.x.$handle.$name": route2, "routes/_app.x.$handle.$name._index": route3 }; import("https://static2.esm.town/assets/entry.client-BdTQ3icg.js"); requestAnimationFrame(function(){ $RT=performance.now() }); ``` -------------------------------- ### Setting up an example Node.js project Source: https://docs.val.town/llms-full.txt Steps to set up a new Node.js project for using the Val Town SDK, including creating a directory, initializing npm, and installing the SDK package. ```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 ``` -------------------------------- ### fets Router Example Source: https://www.val.town/x/valdottown/HTTP_examples/code/HTTP/exampleHTTP Sets up a GET route at the root path using fets, returning a JSON response with a 'message' property. Requires fets installed via npm. ```typescript import { createRouter, Response } from "npm:fets"; export const router = createRouter().route({ method: "GET", path: "/", schemas: { responses: { 200: { type: "object", properties: { message: { type: "string", }, }, required: ["message"], additionalProperties: false, }, }, }, handler: () => Response.json({ message: "Hello from fets!" }), }); export default ``` -------------------------------- ### Blob Storage Example Source: https://val.town/townie/system-prompt Demonstrates how to use the blob storage module for setting and getting JSON data. Ensure to import from the project-scoped '/main.ts' path. ```typescript import { blob } from "https://esm.town/v/std/blob/main.ts"; await blob.setJSON("mykey", { data: "value" }); const data = await blob.getJSON("mykey"); ``` -------------------------------- ### nhttp Example with Multiple Routes Source: https://www.val.town/x/valdottown/HTTP_examples/code/Basic_examples/headersExample Shows how to define multiple GET routes, including one that returns JSON, using nhttp. Suitable for building small web applications. ```typescript import { nhttp } from "npm:nhttp-land@1"; export const nhttpExample = async (request) => { const app = nhttp(); app.get("/", () => { return "Hello from nhttp"; }); app.get("/cat", () => { return { name: "cat" }; }); return app.handleRequest(request); }; ``` -------------------------------- ### Example: Login Route Source: https://www.val.town/x/std/oauth Example of how to initiate the OAuth login flow using the /auth/login route. ```typescript import oauth from "@valtown/oauth"; // Assuming oauthMiddleware is set up and applied to your appFetch // This route is automatically handled by oauthMiddleware // You can access it via GET /auth/login ``` -------------------------------- ### Install Val Town CLI Source: https://docs.val.town/guides/prompting/cli Installs the Val Town CLI globally using Deno. Ensure Deno is installed first. ```bash deno install -grAf jsr:@valtown/vt ``` -------------------------------- ### Retrieve Files Example Source: https://sdk.val.town/api/typescript/resources/vals/subresources/files/methods/retrieve This example demonstrates how to retrieve a list of files. It shows the expected JSON response structure. ```json { "data": [ { "id": "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e", "links": { "html": "https://example.com", "module": "https://example.com", "self": "https://example.com", "email": "dev@stainless.com", "endpoint": "https://example.com" }, "name": "name", "path": "path", "type": "directory", "updatedAt": "2019-12-27T18:11:19.117Z", "version": 0 } ], "links": { "self": "https://example.com", "next": "https://example.com", "prev": "https://example.com" } } ``` -------------------------------- ### Hono Routing Example Source: https://www.val.town/x/valdottown/HTTP_examples/code/Routing/honoExample This snippet demonstrates a basic routing setup using Hono. It defines a root route and a dynamic route. It's intended for use in edge environments. ```javascript import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => { return c.text('Hello Hono!') }) app.get('/users/:id', (c) => { const id = c.req.param('id') return c.text(`User ID: ${id}`) }) export const GET = handle(app) export const POST = handle(app) export const PUT = handle(app) export const DELETE = handle(app) ``` -------------------------------- ### Basic Prompt Example Source: https://docs.val.town/guides/prompting A simple example demonstrating how to send a prompt to a language model and receive a response. ```typescript import { prompt } from "@valtown/api"; export const main = async (name: string): Promise => { const response = await prompt(name); return `Hello, ${response}!`; }; ``` -------------------------------- ### Browserbase Puppeteer Example Source: https://www.val.town/v/browserbase/browserbasePuppeteerExample This snippet demonstrates a basic setup for using Browserbase with Puppeteer. It includes necessary imports and a function to interact with a headless browser. Ensure you have the Browserbase SDK installed. ```typescript import puppeteer from "@browserbase/puppeteer"; export default async function ( request: Request, env: Env ): Promise { const browser = await puppeteer.launch({ browserBase: { apiKey: env.BROWSERBASE_API_KEY, }, }); const page = await browser.newPage(); await page.goto("https://example.com"); const title = await page.title(); await browser.close(); return new Response(title); } ``` -------------------------------- ### itty-router Example Source: https://www.val.town/x/valdottown/HTTP_examples/code/HTML_JSX/solid Illustrates defining routes with itty-router. This example handles a GET request to the root path and returns a plain text response. ```typescript import { json, Router } from "npm:itty-router@4"; export const ittyRouterExample = async (request: Request) => { const router = Router(); router.get("/"), () => "Hi from itty-router!"); return router.handle(request).then(json); }; ``` -------------------------------- ### Hono Example Source: https://www.val.town/x/valdottown/HTTP_examples/code/HTML_JSX/solid Demonstrates setting up routes using the Hono framework. This example includes routes for the root path and '/yeah'. ```typescript import { Hono } from "npm:hono@3"; const app = new Hono(); app.get("/"), (c) => c.text("Hello from Hono!")); app.get("/yeah"), (c) => c.text("Routing!")); export default app.fetch; ``` -------------------------------- ### Val Town Application Setup Source: https://www.val.town/v/stevekrouse/sendDiscordDMExample This snippet shows the initial setup for a Val Town application, including environment variable configuration and routing module imports. It's essential for bootstrapping the application. ```javascript window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-L9G4V6JYZ1'); window.ENV = {"REACT_APP_SENTRY_DSN":"https://586020d86f05489db63a554690acf1e9@o1398359.ingest.sentry.io/6724499","VAL_RUNTIME_NAME":"prod","RENDER_GIT_COMMIT":"9b8091bec2c7db35552d7861cae336baeccbf869","RENDER_GIT_BRANCH":"main","POSTHOG_API_TOKEN":"phc_nmoyuAkStEZuUp69rYlg1DZgrIt19Gx0Y4Hwf8tGgJP","POSTHOG_API_HOST":"https://wart.val.town","WEB_API_TEMPLATE":"https://{val}.web.val.run","APP_URL":"https://www.val.town","MODULE_URL":"https://esm.town","VANITY_WEB_API_TEMPLATE":"https://{label}.val.run/","DENOLS_URL":"https://lsp.val.town","NODE_ENV":"production","CLOUDFLARE_TURNSTILE_SITE_KEY":"0x4AAAAAACtaIZJH7s9rBMZ6","GOOGLE_CLIENT_ID":"875989696899-jtsqkhlbdv5jrlsk8631p7ipjg3c6o62.apps.googleusercontent.com","API_URL":"https://api.val.town"} window.__reactRouterContext = {"basename":"/","future":{"unstable_optimizeDeps":true,"v8_passThroughRequests":false,"unstable_trailingSlashAwareDataRequests":false,"unstable_previewServerPrerendering":false,"v8_middleware":false,"v8_splitRouteModules":false,"v8_viteEnvironmentApi":false},"routeDiscovery":{"mode":"initial"},"ssr":true,"isSpaMode":false}; window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream()); import "https://static2.esm.town/assets/manifest-42c6a8a4.js"; import * as route0 from "https://static2.esm.town/assets/root-DsgFEc4B.js"; import * as route1 from "https://static2.esm.town/assets/_app-D96LoZnJ.js"; import * as route2 from "https://static2.esm.town/assets/route-DASihl3B.js"; import * as route3 from "https://static2.esm.town/assets/route-_rx8SiQF.js"; window.__reactRouterRouteModules = {"root":route0,"routes/_app":route1,"routes/_app.x.$handle.$name":route2,"routes/_app.x.$handle.$name._index":route3}; import("https://static2.esm.town/assets/entry.client-BdTQ3icg.js"); requestAnimationFrame(function(){ $RT=performance.now() }); ``` -------------------------------- ### Itty Example Routing Source: https://www.val.town/x/valdottown/HTTP_examples/code/Routing/ittyExample This example demonstrates a basic routing setup using itty-router. It defines a root route and a dynamic route for user IDs. ```javascript import { Router } from "itty-router"; const router = Router(); router.get("/", () => new Response("Hello!")); router.get("/users/:id", ({ params }) => { return new Response(`User ID: ${params.id}`); }); router.post("/", async (request) => { const data = await request.json(); return new Response(JSON.stringify(data)); }); export default router.handle; ``` -------------------------------- ### Basic HTTP Handler Example Source: https://www.val.town/x/valdottown/HTTP_examples/code/Basic_examples/headersExample A fundamental example of an HTTP handler that returns a JSON response. Serves as a basic starting point for Val Town HTTP applications. ```typescript export function handler(request: Request) { return Response.json({ ok: true ``` -------------------------------- ### Start Client-Side Application Source: https://www.val.town/v/easrng/whoami This code initiates the client-side rendering of the application by importing the main entry point script. It also records the performance timing for the application's startup. ```javascript import("https://static2.esm.town/assets/entry.client-BdTQ3icg.js"); requestAnimationFrame(function(){ $RT=performance.now() }); ``` -------------------------------- ### Main Application Setup (Hono.js) Source: https://www.val.town/x/stevekrouse/luciaMagicLinkStarter Sets up a Hono.js application for serving frontend files, handling authentication, and providing API endpoints. Includes middleware for authentication and serving static assets. ```typescript import { readFile, serveFile } from "https://esm.town/v/std/utils/index.ts"; import { sqlite } from "https://esm.town/v/std/sqlite/main.ts"; import { Hono } from "npm:hono"; import { authMiddleware } from "./auth.ts"; import { USER_TABLE } from "./database/schema.ts"; const app = new Hono(); // Serve all /frontend files app.get("/frontend/*", (c) => serveFile(c.req.path, import.meta.url)); app.use(authMiddleware); // Serve index.html at the root / with bootstrapped data app.get("/", async (c) => { let html = await readFile("/frontend/index.html", import.meta.url); const user = c.get("user"); const dataScript = `` // Insert the script right before the closing tag html = html.replace("", `${dataScript}`); return c.html(html); }); // API endpoint to update username app.post("/api/user/username", async (c) => { const user = c.get("user"); if (!user) { return c.json({ success: false, error: "Not authenticated" }, 401); } try { const { username } = await c.req.json(); if (!username || typeof username !== "string") { return c.json({ success: false, error: "Invalid username" }, 400); } // Validate username length (3-50 characters) if (username.length < 3 || username.length > 50) { return c.json({ success: false, error: "Username must be between 3 and 50 characters", }, 400); } // Validate username contains only alphanumeric characters if (!/^[a-zA-Z0-9]+$/.test(username)) { return c.json({ success: false, error: "Username contains invalid characters", }, ``` -------------------------------- ### Val Town HTTP Example Code Source: https://www.val.town/x/valdottown/HTTP_examples/code/HTTP/exampleHTTP This snippet demonstrates the basic structure and setup for an HTTP example within Val Town. It includes environment variable configuration and script imports necessary for the application to run. ```javascript window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-L9G4V6JYZ1'); ``` ```javascript window.ENV = {"REACT_APP_SENTRY_DSN":"https://586020d86f05489db63a554690acf1e9@o1398359.ingest.sentry.io/6724499","VAL_RUNTIME_NAME":"prod","RENDER_GIT_COMMIT":"9b8091bec2c7db35552d7861cae336baeccbf869","RENDER_GIT_BRANCH":"main","POSTHOG_API_TOKEN":"phc_nmoyuAkStEZuUp69rYlg1DZgrIt19Gx0Y4Hwf8tGgJP","POSTHOG_API_HOST":"https://wart.val.town","WEB_API_TEMPLATE":"https://{val}.web.val.run","APP_URL":"https://www.val.town","MODULE_URL":"https://esm.town","VANITY_WEB_API_TEMPLATE":"https://{label}.val.run/","DENOLS_URL":"https://lsp.val.town","NODE_ENV":"production","CLOUDFLARE_TURNSTILE_SITE_KEY":"0x4AAAAAACtaIZJH7s9rBMZ6","GOOGLE_CLIENT_ID":"875989696899-jtsqkhlbdv5jrlsk8631p7ipjg3c6o62.apps.googleusercontent.com","API_URL":"https://api.val.town"} ``` ```javascript window.__reactRouterContext = {"basename":"/","future":{"unstable_optimizeDeps":true,"v8_passThroughRequests":false,"unstable_trailingSlashAwareDataRequests":false,"unstable_previewServerPrerendering":false,"v8_middleware":false,"v8_splitRouteModules":false,"v8_viteEnvironmentApi":false},"routeDiscovery":{"mode":"initial"},"ssr":true,"isSpaMode":false}; window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream()); ``` ```javascript import "https://static2.esm.town/assets/manifest-42c6a8a4.js"; import * as route0 from "https://static2.esm.town/assets/root-DsgFEc4B.js"; import * as route1 from "https://static2.esm.town/assets/_app-D96LoZnJ.js"; import * as route2 from "https://static2.esm.town/assets/route-DASihl3B.js"; import * as route3 from "https://static2.esm.town/assets/route-4HN72Vax.js"; window.__reactRouterRouteModules = {"root":route0,"routes/_app":route1,"routes/_app.x.$handle.$name":route2,"routes/_app.x.$handle.$name.code.$":route3}; import("https://static2.esm.town/assets/entry.client-BdTQ3icg.js"); ``` ```javascript requestAnimationFrame(function(){ $RT=performance.now() }); ``` -------------------------------- ### Initialize Blog ATProto Records Source: https://www.val.town/x/valdottown/blog Performs one-time setup for a Val Town blog on ATProto. Uploads the blog icon and upserts the site.standard.publication record. Requires BSKY_APP_PASSWORD environment variable. ```typescript import { readFile } from "https://esm.town/v/std/utils/index.ts"; import { BLOG_DID, PUBLICATION_RKEY } from "./constants.ts"; import { createSession, putRecord, uploadBlob } from "./lib.ts"; const ICON_URL = "https://static2.esm.town/assets/vt-blackOnWhite-BBQyDB6T.png"; const accessJwt = await createSession(BLOG_DID); console.log("✓ Authenticated"); const icon = await uploadBlob(accessJwt, ICON_URL, "image/png"); console.log("✓ Icon blob uploaded"); console.log(" CID:", icon.ref.$link); const publication = JSON.parse( await readFile("atproto/site.standard.publication.json", import.meta.url), ); const expectedCID = publication.icon?.ref?.$link; if (expectedCID && expectedCID !== icon.ref.$link) { console.warn(` ⚠ Icon CID mismatch!`); console.warn(` site.standard.publication.json has: ${expectedCID}`); console.warn(` Uploaded blob CID is: ${icon.ref.$link}`); console.warn( ` Update site.standard.publication.json if you changed the icon.`, ); } else { console.log(" ✓ Icon CID matches site.standard.publication.json"); } const result = await putRecord( accessJwt, BLOG_DID, "site.standard.publication", PUBLICATION_RKEY, publication, ); console.log("✓ Publication record upserted"); console.log(" AT-URI:", result.uri); console.log(" CID: ", result.cid); ``` -------------------------------- ### Peko Router Example Source: https://www.val.town/x/valdottown/HTTP_examples/code/Basic_examples/headersExample Demonstrates basic GET route handling with Peko. Useful for simple API endpoints. ```typescript import * as Peko from "https://deno.land/x/peko@2.0.0/mod.ts"; export const pekoExample = async (request) => { const server = new Peko.Router(); server.get("/", () => new Response("Yes? Peko is also serving something at /hello")); server.get("/hello", () => new Response("Hello world!")); return server.requestHandler(request); }; ``` -------------------------------- ### Few-Shot Prompting Source: https://docs.val.town/guides/prompting Demonstrates few-shot prompting by providing examples within the prompt to guide the model's response. ```typescript import { prompt } from "@valtown/api"; export const main = async (input: string): Promise => { const response = await prompt(input, { examples: [ { input: "apple", output: "fruit" }, { input: "carrot", output: "vegetable" }, ], }); return response; }; ``` -------------------------------- ### Using the SDK in Val Town Source: https://docs.val.town/llms-full.txt Demonstrates how to initialize the SDK and retrieve user profile and val list within the Val Town environment. Authentication is handled automatically via environment variables. ```typescript import ValTown from "npm:@valtown/sdk"; const vt = new ValTown(); // print your email const me = await vt.me.profile.retrieve(); console.log(me.email); // list some of your vals const vals = await vt.me.vals.list({}); console.log(vals); ``` -------------------------------- ### Basic Authentication Setup Source: https://www.val.town/v/stevekrouse/browserbase This code snippet demonstrates setting up basic authentication for an application using the 'basic-auth' middleware. It exports the application's fetch handler. ```javascript export default basicAuth(app.fetch); ``` -------------------------------- ### itty-router Routing Example Source: https://docs.val.town/llms-full.txt Implements routing with itty-router. Defines a GET route for the root path and returns a JSON response. ```ts import { json, Router } from "npm:itty-router@4"; export const ittyRouterExample = async (request: Request) => { const router = Router(); router.get("/", () => "Hi from itty-router!"); return router.handle(request).then(json); }; ``` -------------------------------- ### Get GitHub User Stars Source: https://docs.val.town/guides/github/github-users-stars-pagination Fetches the stars for a given GitHub user. This is a basic example of interacting with the GitHub API. ```javascript import { getGithubStars } from "https://esm.town/v/vtdocs/getGithubStars"; console.log(await getGithubStars("stevekrouse")); ``` -------------------------------- ### nhttp Example Source: https://www.val.town/x/valdottown/HTTP_examples/code/HTML_JSX/solid Shows how to define routes for a web server using nhttp. Includes a route for the root path and a route that returns JSON. ```typescript import { nhttp } from "npm:nhttp-land@1"; export const nhttpExample = async (request) => { const app = nhttp(); app.get("/"), () => { return "Hello from nhttp"; }); app.get("/cat"), () => { return { name: "cat" }; }); return app.handleRequest(request); }; ``` -------------------------------- ### API Schema Response Example Source: https://www.val.town/x/nbbaier/sqliteExplorerReact This JSON structure represents the response from the GET /api/schema endpoint, detailing tables and views within the database. ```json { "tables": [ { "name": "users", "type": "table" } ], "views": [ { "name": "active_users", "type": "view" } ] } ``` -------------------------------- ### Val Town Project Initialization and Configuration Source: https://www.val.town/v/vtdocs/discordWelcomeBotMsgForwarder This snippet shows the initial setup for a Val Town project, including analytics configuration and environment variable loading. It's typically found at the entry point of the application. ```javascript window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-L9G4V6JYZ1'); ``` ```javascript window.ENV = { "REACT_APP_SENTRY_DSN": "https://586020d86f05489db63a554690acf1e9@o1398359.ingest.sentry.io/6724499", "VAL_RUNTIME_NAME": "prod", "RENDER_GIT_COMMIT": "9b8091bec2c7db35552d7861cae336baeccbf869", "RENDER_GIT_BRANCH": "main", "POSTHOG_API_TOKEN": "phc_nmoyuAkStEZuUp69rYlg1DZgrIt19Gx0Y4Hwf8tGgJP", "POSTHOG_API_HOST": "https://wart.val.town", "WEB_API_TEMPLATE": "https://{val}.web.val.run", "APP_URL": "https://www.val.town", "MODULE_URL": "https://esm.town", "VANITY_WEB_API_TEMPLATE": "https://{label}.val.run/", "DENOLS_URL": "https://lsp.val.town", "NODE_ENV": "production", "CLOUDFLARE_TURNSTILE_SITE_KEY": "0x4AAAAAACtaIZJH7s9rBMZ6", "GOOGLE_CLIENT_ID": "875989696899-jtsqkhlbdv5jrlsk8631p7ipjg3c6o62.apps.googleusercontent.com", "API_URL": "https://api.val.town" }; ``` ```javascript window.__reactRouterContext = { "basename": "/", "future": { "unstable_optimizeDeps": true, "v8_passThroughRequests": false, "unstable_trailingSlashAwareDataRequests": false, "unstable_previewServerPrerendering": false, "v8_middleware": false, "v8_splitRouteModules": false, "v8_viteEnvironmentApi": false }, "routeDiscovery": { "mode": "initial" }, "ssr": true, "isSpaMode": false }; window.__reactRouterContext.stream = new ReadableStream({ start(controller) { window.__reactRouterContext.streamController = controller; } }).pipeThrough(new TextEncoderStream()); ``` ```javascript import "https://static2.esm.town/assets/manifest-42c6a8a4.js"; import * as route0 from "https://static2.esm.town/assets/root-DsgFEc4B.js"; import * as route1 from "https://static2.esm.town/assets/_app-D96LoZnJ.js"; import * as route2 from "https://static2.esm.town/assets/route-DASihl3B.js"; import * as route3 from "https://static2.esm.town/assets/route-_rx8SiQF.js"; window.__reactRouterRouteModules = { "root": route0, "routes/_app": route1, "routes/_app.x.$handle.$name": route2, "routes/_app.x.$handle.$name._index": route3 }; ``` ```javascript import("https://static2.esm.town/assets/entry.client-BdTQ3icg.js"); ``` ```javascript requestAnimationFrame(function(){ $RT=performance.now() }); ``` -------------------------------- ### Hono Example with Two Routes Source: https://www.val.town/x/valdottown/HTTP_examples/code/Basic_examples/headersExample Demonstrates defining two GET routes using the Hono framework. Useful for creating APIs with distinct endpoints. ```typescript import { Hono } from "npm:hono@3"; const app = new Hono(); app.get("/", (c) => c.text("Hello from Hono!")); app.get("/yeah", (c) => c.text("Routing!")); export default app.fetch; ``` -------------------------------- ### Slack Bot Template Example Source: https://docs.val.town/guides/slack/bot This is the main entry point for the Slack bot example. It handles incoming requests, processes them, and sends responses back to Slack. Ensure you have the necessary environment variables configured for Slack integration. ```typescript import { serve } from "@std/http/server"; import { SlackApiError, SlackEvent, SlackInteraction, SlackMessage, SlackResponse, } from "./slack.ts"; // Environment variables const SLACK_BOT_TOKEN = Deno.env.get("SLACK_BOT_TOKEN"); const SLACK_SIGNING_SECRET = Deno.env.get("SLACK_SIGNING_SECRET"); if (!SLACK_BOT_TOKEN || !SLACK_SIGNING_SECRET) { throw new Error("Missing SLACK_BOT_TOKEN or SLACK_SIGNING_SECRET environment variables"); } // Handle Slack events async function handleEvent(event: SlackEvent): Promise { if (event.type === "url_verification") { return { challenge: event.challenge }; } if (event.event?.type === "app_mention") { const message = event.event; const text = message.text; const channel = message.channel; // Respond to mentions const response = await fetch("https://api.val.town/v1/run/charmaine/slackBotExample/response", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${SLACK_BOT_TOKEN}`, }, body: JSON.stringify({ channel, text: `You mentioned me: ${text}`, }), }); if (!response.ok) { console.error("Failed to send message to Slack:", await response.text()); return { ok: false }; } return { ok: true }; } return { ok: true }; } // Handle Slack interactions async function handleInteraction(interaction: SlackInteraction): Promise { // Handle button clicks, select menus, etc. console.log(interaction); return { ok: true }; } // Main server logic serve(async (req) => { const signature = req.headers.get("X-Slack-Signature")!; const timestamp = req.headers.get("X-Slack-Request-Timestamp")!; // Verify the request signature const isValid = await crypto.subtle.verify( { name: "HMAC", hash: "SHA-256", }, await crypto.subtle.importKey( "raw", new TextEncoder().encode(SLACK_SIGNING_SECRET), { name: "HMAC" }, false, ["verify"] ), new TextEncoder().encode(`${"v0:"}${timestamp}:${await req.text()}`), signature.replace("v0=", ""), ); if (!isValid) { return new Response("Invalid signature", { status: 401 }); } const body = await req.json(); if (body.event) { return new Response(JSON.stringify(await handleEvent(body))); } if (body.type === "interactive_message") { return new Response(JSON.stringify(await handleInteraction(body))); } return new Response("Unknown request type", { status: 400 }); }); ``` -------------------------------- ### Initialize Environment Variables Source: https://www.val.town/v/boson/discordWebhookWeatherHyd Sets up essential environment variables for the application, including API keys and URLs. ```javascript p.val.town\",\"NODE_ENV\",\"production\",\"CLOUDFLARE_TURNSTILE_SITE_KEY\",\"0x4AAAAAACtaIZJH7s9rBMZ6\",\"GOOGLE_CLIENT_ID\",\"875989696899-jtsqkhlbdv5jrlsk8631p7ipjg3c6o62.apps.googleusercontent.com\",\"API_URL\",\"https://api.val.town\",\"preferencesKeybindings\",\"default\",\"preferencesTheme\",\"light\",\"preferencesFixers\",\"preferencesCopilot\",\"preferencesSelectionAi\",\"preferencesChatPanelState\",\"preferencesDprint\",\"preferencesDenofmt\",\"notificationCount\",\"flagDenols\",\"isBusinessOrgMember\",\"businessOrgHandle\",\"isBusinessOrgAdmin\",\"isHigherTownieTier\"\ ); ``` -------------------------------- ### Handle New Assistant Thread in Slack Source: https://www.val.town/x/pmillspaugh/townie Provides a greeting and suggested prompts when a new assistant thread is started in Slack. This aims to guide the user. ```typescript import { WebClient } from "@slack/web-api"; const slack = new WebClient(process.env.SLACK_BOT_TOKEN); export async function handleThreadStarted(event: any) { const greeting = "Hello! I'm your AI assistant. How can I help you today?"; const suggestedPrompts = [ "What's the weather like?", "Tell me a joke.", "Summarize this document." ]; await slack.chat.postMessage({ channel: event.channel, text: `${greeting}\n\nSuggested prompts:\n- ${suggestedPrompts.join('\n- ')}`, thread_ts: event.ts, }); } ``` -------------------------------- ### Basic Hono Routing Example Source: https://www.val.town/x/valdottown/HTTP_examples/code/Routing/honoExample A simple Hono application demonstrating basic GET and POST route handling. This is useful for setting up a minimal web server. ```typescript import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => { return c.text('Hello Hono!') }) app.post('/', async (c) => { const body = await c.req.parseBody() return c.json({ message: 'Received POST request', data: body }) }) export default app ``` -------------------------------- ### Add MCP Server to Claude Code Source: https://docs.val.town/guides/prompting/mcp Example command to add the Val Town MCP server to Claude Code. This command assumes you have the Claude CLI installed. ```bash claude mcp add --transport http val-town https://api.val.town/v3/mcp ``` -------------------------------- ### Basic Hono Routing Setup Source: https://www.val.town/x/valdottown/blog This snippet shows the basic setup for Hono routing in the main entry point of the Val Town Blog. It includes middleware and route definitions. ```typescript import { Hono } from 'hono' import { serveStatic } from 'hono/serve-static' import { logger } from 'hono/logger' import home from './routes/home' import blog from './routes/blog' import proxy from './routes/proxy' import rss from './routes/rss' import favicon from './routes/favicon' import ogImage from './routes/og-image' const app = new Hono() app.use(logger()) // Static assets app.use('/styles/*', serveStatic({ root: './public' })) app.use('/images/*', serveStatic({ root: './public' })) // Routes app.route('/', home) app.route('/blog', blog) app.route('/proxy', proxy) app.route('/rss.xml', rss) app.route('/favicon.ico', favicon) app.route('/og-image.png', ogImage) export default app ``` -------------------------------- ### Express HTML Serving Example Source: https://www.val.town/v/stevekrouse.expressHTMLExample This snippet demonstrates a basic Express.js server setup for serving HTML content. It includes configuration for Google authentication and API endpoints. ```javascript const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('

Hello World!

'); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); }); ``` -------------------------------- ### Running index.mjs and getting profile information Source: https://docs.val.town/llms-full.txt Example output from running the Node.js script, showing the retrieved user profile details including ID, username, email, and tier. ```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' } ``` -------------------------------- ### fets Router Example with Schema Source: https://www.val.town/x/valdottown/HTTP_examples/code/Basic_examples/headersExample Shows how to define a GET route with fets, including response schema validation. Ideal for robust API development where type safety is important. ```typescript import { createRouter, Response } from "npm:fets"; export const router = createRouter().route({ method: "GET", path: "/", schemas: { responses: { 200: { type: "object", properties: { message: { type: "string", }, }, required: ["message"], additionalProperties: false, }, }, }, handler: () => Response.json({ message: "Hello from fets!" }), }); export default router.fetch; ``` -------------------------------- ### Hono Web Framework Example Source: https://www.val.town/teams A minimal example using the Hono web framework to create a simple web server. Requires 'npm:hono' import. ```typescript import { Hono } from "npm:hono" const app = new Hono() app.get('/', (c) => c.text('Hello!')) export default app.fetch; ``` -------------------------------- ### Importing from npm Source: https://val.town/townie/system-prompt Demonstrates how to import packages from npm using the 'npm:' prefix. ```typescript import { foo } from "npm:package@version"; ``` -------------------------------- ### Peko Routing Example Source: https://docs.val.town/llms-full.txt Implements routing with Peko. Sets up routes for '/' and '/hello' paths, returning different Response objects. ```ts import * as Peko from "https://deno.land/x/peko@2.0.0/mod.ts"; export const pekoExample = async (request) => { const server = new Peko.Router(); server.get("/", () => new Response("Yes? Peko is also serving something at /hello")); server.get("/hello", () => new Response("Hello world!")); return server.requestHandler(request); }; ``` -------------------------------- ### Initialize Blob Storage Client Source: https://docs.val.town/std/blob Demonstrates how to initialize the Blob Storage client. This is typically the first step before performing any storage operations. ```typescript import { blob } from "@valtown/blob"; const client = blob.client(); ``` -------------------------------- ### itty-router Example with JSON Response Source: https://www.val.town/x/valdottown/HTTP_examples/code/Basic_examples/headersExample Illustrates defining a root GET route that returns a text response, processed by itty-router's JSON handler. Good for simple API routing. ```typescript import { json, Router } from "npm:itty-router@4"; export const ittyRouterExample = async (request: Request) => { const router = Router(); router.get("/", () => "Hi from itty-router!"); return router.handle(request).then(json); }; ``` -------------------------------- ### Get Credit Additions with Filtering and Pagination Source: https://www.val.town/x/valdottown/Townie/code/prompts/system_prompt.txt Retrieves credit additions from the database, supporting filtering by user ID, start date, and end date. It also implements pagination to manage large datasets. ```typescript import { sqlite } from \"https://esm.town/v/stevekrouse/sqlite/main.tsx\"; import { CREDIT_ADDITIONS_TABLE } from \"../../schema.tsx\"; import { getPaginationParams, getPaginationSQL, calculatePagination } from \"../utils/pagination.ts\"; export interface CreditAddition { id: number; user_id: string; created_at: number; stripe_payment_intent_id: string | null; amount: number; note: string; } /** * Get credit additions with optional filtering and pagination */ export async function getCreditAdditions(url: URL) { // Parse pagination parameters const { page, pageSize } = getPaginationParams(url); // Parse filtering parameters const userId = url.searchParams.get(\"user_id\"); const startDate = url.searchParams.get(\"start_date\"); const endDate = url.searchParams.get(\"end_date\"); // Build the WHERE clause based on filters let whereClause = \"\"; const whereParams: any[] = []; if (userId) { whereClause += \" WHERE user_id = ?\"; whereParams.push(userId); } // Add date range filters if provided if (startDate) { const startTimestamp = new Date(startDate).getTime(); whereClause += whereClause ? \" AND\" : \" WHERE\"; whereClause += \" created_at >= ?\"; whereParams.push(startTimestamp); } if (endDate) { const endTimestamp = new Date(endDate).getTime(); whereClause += whereClause ? \" AND\" : \" WHERE\"; whereClause += \" created_at <= ?\"; whereParams.push(endTimestamp); } // Get total count for pagination const countResult = await sqlite.execute( `SELECT COUNT(*) as total FROM ${CREDIT_ADDITIONS_TABLE}${whereClause}`, whereParams ); const totalItems = countResult.rows[0].total; // Get paginated data const paginationSQL = getPaginationSQL(page, pageSize); // Get the credit additions with pagination const query = ` SELECT id, user_id, created_at, stripe_payment_intent_id, amount, note FROM ${CREDIT_ADDITIONS_TABLE} ${whereClause} ORDER BY created_at DESC ${paginationSQL} `; const result = await sqlite.execute( query, whereParams ); // Process the results const data: CreditAddition[] = result.rows.map(row => ({ id: row.id, user_id: row.user_id, created_at: row.created_at, stripe_payment_intent_id: row.stripe_payment_intent_id, amount: row.amount, note: row.note })); return { data, pagination: calculatePagination(page, pageSize, totalItems) }; } ```