Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run//%22?q=function&page=4&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=function

Returns an array of strings in format "username" or "username/projectName"

Found 40461 results for "function"(1168ms)

1export default async function(req: Request): Promise<Response> {
2 const html = `<!DOCTYPE html>
3<html lang="en">
237 <script>
238 // Cookie utilities
239 function setCookie(name, value, days = 30) {
240 const expires = new Date();
241 expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
243 }
244
245 function getCookie(name) {
246 const nameEQ = name + "=";
247 const ca = document.cookie.split(';');
254 }
255
256 // Enhanced error display function
257 function displayError(error, context = {}) {
258 const responseDiv = document.getElementById('responseContent');
259
330
331 // Load saved values
332 function loadSavedValues() {
333 // Load API key from cookie
334 const savedApiKey = getCookie('nvidia_api_key');
361
362 // Save current form values
363 function saveCurrentValues() {
364 const form = document.getElementById('apiForm');
365 const formData = new FormData(form);
397 }
398
399 // Enhanced API request function
400 async function makeApiRequest(requestData, apiKey) {
401 const requestHeaders = {
402 'Authorization': \`Bearer \${apiKey}\`,
455
456 // Handle streaming response with better error handling
457 async function handleStreamingResponse(response) {
458 const reader = response.body.getReader();
459 const decoder = new TextDecoder();
493
494 // Handle non-streaming response with detailed info
495 async function handleNonStreamingResponse(response) {
496 const responseDiv = document.getElementById('responseContent');
497

boombox-generatorog.tsx1 match

@danfishgoldโ€ขUpdated 11 hours ago
3import { ImageResponse } from "npm:@vercel/og";
4
5export function generateOgImageResponse(code: string | undefined) {
6 try {
7 const bb = boomboxData();

test-render-haproxymain.ts1 match

@stevekrouseโ€ขUpdated 11 hours ago
1// Learn more: https://docs.val.town/vals/http/
2export default async function (req: Request): Promise<Response> {
3 return Response.json({ ok: true })
4}

untitled-8620main.ts6 matches

@knowโ€ขUpdated 11 hours ago
59const openai = new OpenAI();
60
61async function callAI(fact: string, prompt: string): Promise<Prerequisite[]> {
62 try {
63 const completion = await openai.chat.completions.create({
83 * Tracks processed nodes to avoid redundant API calls and circular dependencies.
84 */
85async function buildTreeInBackground(jobId: string, rootNode: FactNode) {
86 try {
87 // This Map will store all nodes ever created, keyed by their fact string.
160// --- FRONTEND & ROUTER (No changes needed below this line) ---
161
162function generateHtml(sourceUrl: string): string {
163 return `<!DOCTYPE html>
164<html lang="en">
347 const POLLING_INTERVAL = 2000;
348
349 function TreeNode({ node, seenIds = new Set() }) {
350 const [isCollapsed, setIsCollapsed] = useState(false);
351
395 }
396
397 function App() {
398 const [view, setView] = useState('input'); // 'input', 'processing', 'tree'
399 const [jobId, setJobId] = useState(null);
534}
535
536export default async function (req: Request): Promise<Response> {
537 const url = new URL(req.url);
538 const path = url.pathname;

untitled-8264main.ts12 matches

@ziggywareโ€ขUpdated 11 hours ago
1export default async function (req: Request): Promise<Response> {
2 const html = `<!DOCTYPE html>
3<html lang="en">
48const startBtn = document.getElementById("startBtn");
49const errorBox = document.getElementById("errorBox");
50function showError(e) {
51 console.error(e);
52 errorBox.style.display = "block";
55const gl = canvas.getContext("webgl2", { antialias: true, alpha: false });
56if (!gl) { showError("WebGL2 not supported."); overlay.classList.add("hidden"); return; }
57function resize() {
58 const dpr = Math.min(window.devicePixelRatio || 1, 2);
59 const w = Math.floor(window.innerWidth * dpr);
154 fragColor = vec4(col * sprite, alpha);
155}\`;
156function compileShader(type, src) {
157 const s = gl.createShader(type);
158 gl.shaderSource(s, src);
184
185// Helper to create attribute buffers
186function createAttrib(data, name, usage) {
187 const loc = gl.getAttribLocation(program, name);
188 if (loc === -1) throw new Error("Attrib not found: " + name);
212
213// Matrix helpers
214function mat4Perspective(fovDeg, aspect, near, far) {
215 const f = 1.0 / Math.tan((fovDeg * Math.PI) / 360);
216 const nf = 1 / (near - far);
223 return out;
224}
225function subtract(a, b) { return [a[0]-b[0], a[1]-b[1], a[2]-b[2]]; }
226function normalize(v) { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0]/l, v[1]/l, v[2]/l]; }
227function cross(a, b) { return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]]; }
228function dot(a, b) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; }
229function mat4LookAt(eye, target, up) {
230 const z = normalize(subtract(eye, target));
231 const x = normalize(cross(up, z));
245const alphaRelease = 0.12;
246
247function render(ts) {
248 if (analyser) {
249 analyser.getByteFrequencyData(fftBuffer);

qbatREADME.md2 matches

@wilhelmโ€ขUpdated 11 hours ago
20- **Apple Collection**: Red apples scattered around the maze provide bonus moves
21- **Win/Lose Conditions**: Clear victory and failure states
22- **Restart Functionality**: Easy game restart with a single button click
23- **Board Sharing**: Copy/paste board states using emoji-based text representation
24- **Custom Levels**: Load custom board configurations by pasting text
53 โ”œโ”€โ”€ index.tsx # Game implementation
54 โ”œโ”€โ”€ style.css # Styling including login component styles
55 โ”œโ”€โ”€ bluesky-oauth.ts # Bluesky OAuth functionality
56 โ”œโ”€โ”€ login-component.ts # Login UI component
57 โ””โ”€โ”€ favicon.svg # Game icon
60โ”œโ”€โ”€ shared/ # Shared utilities and types
61โ”‚ โ”œโ”€โ”€ types.ts # TypeScript interfaces for Notion data
62โ”‚ โ”œโ”€โ”€ utils.ts # Shared utility functions
63โ”‚ โ””โ”€โ”€ README.md
64โ””โ”€โ”€ main.tsx # Application entry point with static file serving
73- Extracts parameters from requests
74- Applies authentication middleware
75- Calls controller functions and formats responses
76- Manages HTTP status codes and error responses
77
89
90### Response Format
91All controller functions return a consistent structure:
92```typescript
93{
137
138#### **User Experience**
139- **Error Handling**: Graceful error states with retry functionality
140- **Loading States**: Smooth loading indicators
141- **Navigation**: Easy return to dashboard
208- Filter out button properties from Notion page data
209- Return standardized JSON responses (except authentication routes which redirect or show HTML)
210- Use the same controller functions as the API endpoints for consistency
211
212### New User Registration Flow
432## Environment Variables
433
434Configure these environment variables for full functionality:
435- `GLANCE_DEMOS_DB_ID` - Notion database ID for demos
436- `GLANCE_CONTENT_DB_ID` - Notion database ID for content
14 * Update viewing status for a page in blob storage
15 */
16export async function updateViewingStatus(
17 pageId: string,
18 viewing: boolean,
111 * Sync viewing data to Notion page properties
112 */
113async function syncViewingToNotion(pageId: string, viewingData: any, oldViewingState?: boolean) {
114 // Derive viewing state from sessionStart
115 const currentlyViewing = viewingData.sessionStart !== null;
156 * Get current viewing status for a page
157 */
158export async function getViewingStatus(pageId: string): Promise<ViewingResponse> {
159 try {
160 // Validate page ID using existing helper
227 * Clean up stale viewing sessions (called by cron)
228 */
229export async function cleanupStaleViewingSessions(): Promise<ViewingResponse> {
230 try {
231 const blobsResult = await listBlobKeys(generateBlobKeyPrefix("viewing"));
337 * Get viewing statistics for a page (simplified - mostly transforms getViewingStatus)
338 */
339export async function getViewingStats(pageId: string): Promise<ViewingResponse> {
340 try {
341 // Validate page ID using existing helper
1/**
2 * Viewing-specific utility functions
3 */
4
16 * Migrate old blob structure to new unified sessionStart format
17 */
18export function migrateOldBlobStructure(data: any): any {
19 if (!data || typeof data !== 'object') {
20 return data;
32 * Derive viewing state from sessionStart property
33 */
34export function deriveViewingState(data: any): boolean {
35 if (!data || typeof data !== 'object') {
36 return false;
42 * Check if blob data is stale based on lastUpdate timestamp
43 */
44export function isDataStale(data: any, thresholdMinutes: number): boolean {
45 if (!data?.lastUpdate) {
46 return true; // No lastUpdate means stale

itsOnRendermain.tsx3 matches

@maxmโ€ขUpdated 12 hours ago
1// export default async function(req: Request): Promise<Response> {
2// return Response.json({ ok: true, headers: [...req.headers.entries()] });
3// }
5const msg = new TextEncoder().encode("๐Ÿ’ฉ");
6const initialDelay = 20;
7export default async function (req: Request): Promise<Response> {
8 let timerId: number | undefined;
9 const body = new ReadableStream({
10 start(controller) {
11 let currentDelay = initialDelay;
12 function writeToStream() {
13 currentDelay *= 1.03;
14 controller.enqueue(msg);

ratelimit4 file matches

@unkeyโ€ขUpdated 1 month ago
Rate limit your serverless functions

discordWebhook2 file matches

@stevekrouseโ€ขUpdated 2 months ago
Helper function to send Discord messages
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.