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/image-url.jpg%20%22Optional%20title%22?q=function&page=23&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 33110 results for "function"(3853ms)

2 * Import Web SDK
3 */
4async function loadKlarnaSdk() {
5 const { KlarnaSDK } = await import("https://js.klarna.com/web-sdk/v2/klarna.mjs");
6
25 * Create payment intent with acquirer
26 */
27app.get("/order", async function(c) {
28 const { amount, currency, interoperabilityToken, returnUrl } = c.req.query();
29 const resp = await fetch(
35});
36
37app.get("/paymentRequest", async function(c) {
38 const { amount, currency, returnUrl } = c.req.query();
39 const apiKey = process.env.API_KEY;

log-beelinemain.tsx1 match

@pugioβ€’Updated 2 days ago
5import { sqlite } from "https://esm.town/v/std/sqlite"; // Val Town’s built-in client [oai_citation:0‑docs.val.town](https://docs.val.town/std/sqlite/usage/?utm_source=chatgpt.com)
6
7export default async function handler(req: Request): Promise<Response> {
8 const { pathname } = new URL(req.url);
9

ChatuseAnthropicStream.tsx6 matches

@c15rβ€’Updated 2 days ago
24
25/** merge delta (unchanged) */
26function mergeDelta(block: any, delta: any) {
27 if (!delta) return;
28 switch (delta.type) {
40
41/** build request body helpers */
42async function buildBody(config: AppConfig, history: Message[], userText: string, clientPool: MCPClientPool) {
43 const mcp = config.mcpServers
44 .filter((s) => s.enabled && s.url)
70
71/** final assembly */
72function assembleMessage(blocks: Record<number, any>): AssistantMsg {
73 Object.values(blocks).forEach((b) => {
74 if (b._input_json_str !== undefined) {
94
95/** Execute a tool call */
96async function executeToolCall(
97 toolName: string,
98 input: any,
111/* ──────────────────────────── useAnthropicStream ─────────────────────────── */
112
113export default function useAnthropicStream(
114 config: AppConfig,
115 clientPool: MCPClientPool,
262 );
263
264 /* Main send/stream function with tool use loop */
265 const send = React.useCallback(
266 async (history: Message[], userText: string): Promise<Message[]> => {

ZenServermain.ts7 matches

@ianmenethilβ€’Updated 2 days ago
41 * Initializes the entire SafeHash V2 application.
42 */
43async function initializeApplication(): Promise<void> {
44 try {
45 logInfo('πŸš€ Starting SafeHash V2 initialization...', 'app_init_start');
93 * Starts the HTTP server.
94 */
95function startServer():
96 | void
97 | ((
149 * Gracefully shuts down the application.
150 */
151async function shutdownApplication(signal?: string): Promise<void> {
152 if (appState.isShuttingDown) {
153 logWarn('Shutdown already in progress', 'shutdown_already_in_progress');
194 * Performs cleanup tasks during shutdown.
195 */
196async function cleanupOnShutdown(): Promise<void> {
197 try {
198 // Export any remaining tracing spans
228 * Only uses signals supported by the current OS.
229 */
230function setupSignalHandlers(): void {
231 if (typeof Deno !== 'undefined') {
232 const isWindows = Deno.build?.os === 'windows';
268 * Main application entry point.
269 */
270async function main(): Promise<
271 | ((request: Request, env?: Record<string, unknown>, executionCtx?: ExecutionContext) => Response | Promise<Response>)
272 | void
286
287 // For Val Town deployment, return the fetch handler
288 if (fetchHandler && typeof fetchHandler === 'function') {
289 return fetchHandler;
290 }

ZenServervalidation.ts19 matches

@ianmenethilβ€’Updated 2 days ago
186 * Throws error for invalid input types to ensure type safety.
187 */
188export function sanitizeSQL(str: string): string {
189 if (typeof str !== 'string') {
190 throw new Error('sanitizeSQL expects a string input');
212 * Validates nonce format using the pattern from constants.
213 */
214export function isValidNonceFormat(nonce: string): boolean {
215 try {
216 NonceSchema.parse(nonce);
224 * Validates booking ID format using the pattern from constants.
225 */
226export function isValidBookingId(id: string): boolean {
227 try {
228 BookingIdSchema.parse(id);
236 * Validates payment timestamp format.
237 */
238export function isValidPaymentTimestamp(timestamp: string): boolean {
239 try {
240 PaymentTimestampSchema.parse(timestamp);
248 * Validates timestamp for replay attack prevention.
249 */
250export function isRequestTimestampValid(
251 timestamp: string | undefined,
252 toleranceMs: number = 5 * 60 * 1000, // 5 minutes
273 * Validates payment mode value.
274 */
275export function isValidPaymentMode(mode: any): mode is PaymentMode {
276 try {
277 PaymentModeSchema.parse(mode);
285 * Validates payment amount (no decimals, positive integer).
286 */
287export function isValidPaymentAmount(amount: any): boolean {
288 try {
289 PaymentAmountSchema.parse(amount);
297 * Validates that payment amount string doesn't contain decimals.
298 */
299export function hasNoDecimals(amountString: string): boolean {
300 return !/[.,]/.test(amountString);
301}
308 * Validates email_verify field for honeypot detection.
309 */
310export function isHoneypotTriggered(emailVerify: string | undefined): boolean {
311 // Honeypot is triggered if the field is filled (it should be empty)
312 return !!(emailVerify && emailVerify.trim().length > 0);
316 * Validates origin header against allowed origins.
317 */
318export function isValidOrigin(origin: string | null, allowedOrigins: string[]): boolean {
319 if (!origin) return false;
320 return allowedOrigins.includes(origin);
324 * Validates referer header against origin.
325 */
326export function isValidReferer(referer: string | null, origin: string | null): boolean {
327 if (!referer || !origin) return false;
328 try {
336 * Validates host header against expected host.
337 */
338export function isValidHost(host: string | null, expectedHost: string): boolean {
339 if (!host) return false;
340 return host === expectedHost;
344 * Validates IP address format and extracts from headers.
345 */
346export function extractAndValidateIP(headers: Headers): string {
347 // Check for Cloudflare headers first
348 const cfConnectingIP = headers.get('cf-connecting-ip');
388 * Formats Zod validation errors into user-friendly messages.
389 */
390export function formatValidationErrors(error: z.ZodError): string[] {
391 return error.errors.map((err) => {
392 const path = err.path.length > 0 ? `${err.path.join('.')}: ` : '';
398 * Validates request data and returns formatted errors if validation fails.
399 */
400export function validateRequestData<T>(
401 schema: z.ZodSchema<T>,
402 data: unknown,
416 * Validates required fields are present in request.
417 */
418export function checkRequiredFields<T extends Record<string, any>>(
419 data: T,
420 requiredFields: string[],
446 * Creates a custom Zod schema for conditional validation.
447 */
448export function conditionalValidation<T>(
449 condition: (data: any) => boolean,
450 schema: z.ZodSchema<T>,
466 * Creates a Zod schema for array validation with size limits.
467 */
468export function createArraySchema<T>(
469 itemSchema: z.ZodSchema<T>,
470 minItems: number = 0,
487 BookingIdSchema,
488
489 // Validation functions
490 isValidNonceFormat,
491 isValidBookingId,

ZenServertracing.ts30 matches

@ianmenethilβ€’Updated 2 days ago
21 * Initializes the tracing system.
22 */
23export function initializeTracing(): void {
24 const config = getConfig();
25 tracingConfig = config.tracing || null;
39 * Checks if tracing is enabled and should sample this request.
40 */
41function shouldTrace(): boolean {
42 if (!isTracingEnabled || !tracingConfig) {
43 return false;
55 * Generates a unique span ID.
56 */
57function generateSpanId(): string {
58 const bytes = crypto.getRandomValues(new Uint8Array(8));
59 return Array.from(bytes)
65 * Generates a unique trace ID.
66 */
67function generateTraceId(): string {
68 const bytes = crypto.getRandomValues(new Uint8Array(16));
69 return Array.from(bytes)
75 * Creates a new trace span.
76 */
77export function createSpan(
78 operationName: string,
79 parentSpan?: TraceSpan,
124 * Finishes a trace span.
125 */
126export function finishSpan(span: TraceSpan | null, tags: Record<string, any> = {}): void {
127 if (!span || !isTracingEnabled) {
128 return;
171 * Adds a log entry to a span.
172 */
173export function addSpanLog(
174 span: TraceSpan | null,
175 level: string,
194 * Adds tags to a span.
195 */
196export function addSpanTags(span: TraceSpan | null, tags: Record<string, any>): void {
197 if (!span || !isTracingEnabled) {
198 return;
205 * Sets an error tag on a span.
206 */
207export function setSpanError(span: TraceSpan | null, error: Error): void {
208 if (!span || !isTracingEnabled) {
209 return;
222
223// ========================================
224// High-Level Tracing Functions
225// ========================================
226
228 * Traces an HTTP request.
229 */
230export function traceHttpRequest(
231 method: string,
232 path: string,
246 * Traces an HTTP response.
247 */
248export function traceHttpResponse(
249 span: TraceSpan | null,
250 status: number,
269 * Traces a database operation.
270 */
271export function traceDatabaseOperation(
272 operation: string,
273 table: string,
284 * Traces a security check.
285 */
286export function traceSecurityCheck(
287 checkType: string,
288 parentSpan?: TraceSpan,
296 * Traces a crypto operation.
297 */
298export function traceCryptoOperation(
299 operation: string,
300 algorithm: string,
310 * Traces a business logic operation.
311 */
312export function traceBusinessOperation(
313 operation: string,
314 parentSpan?: TraceSpan,
322
323// ========================================
324// Async Function Tracing
325// ========================================
326
327/**
328 * Wraps an async function with tracing.
329 */
330export function withTracing<T extends any[], R>(
331 operationName: string,
332 fn: (...args: T) => Promise<R>,
352
353/**
354 * Executes a function with a new span context.
355 */
356export async function inSpan<T>(
357 operationName: string,
358 fn: (span: TraceSpan | null) => Promise<T> | T,
384 * Sets the root span for a request context.
385 */
386export function setRequestSpan(correlationId: string, span: TraceSpan | null): void {
387 if (span) {
388 requestContexts.set(correlationId, span);
395 * Gets the root span for a request context.
396 */
397export function getRequestSpan(correlationId: string): TraceSpan | null {
398 return requestContexts.get(correlationId) || null;
399}
402 * Clears the request context.
403 */
404export function clearRequestContext(correlationId: string): void {
405 const span = requestContexts.get(correlationId);
406 if (span) {
417 * Exports a span to the configured tracing endpoint.
418 */
419async function exportSpan(span: TraceSpan): Promise<void> {
420 if (!tracingConfig?.endpoint) {
421 return;
462 * Exports all active spans (useful for shutdown).
463 */
464export async function exportAllSpans(): Promise<void> {
465 if (!tracingConfig?.endpoint || activeSpans.size === 0) {
466 return;
492 * Gets tracing statistics.
493 */
494export function getTracingStats(): {
495 enabled: boolean;
496 activeSpans: number;
511 * Gets the current root span.
512 */
513export function getRootSpan(): TraceSpan | null {
514 return rootSpan;
515}
518 * Gets all active spans.
519 */
520export function getActiveSpans(): TraceSpan[] {
521 return Array.from(activeSpans.values());
522}
529 * Cleans up expired spans (older than 1 hour).
530 */
531export function cleanupExpiredSpans(): void {
532 const oneHourAgo = performance.now() - (60 * 60 * 1000);
533 const expiredSpanIds: string[] = [];

ZenServerlogging.ts31 matches

@ianmenethilβ€’Updated 2 days ago
19 * Initializes the logging system with configuration.
20 */
21export async function initializeLogging(): Promise<void> {
22 if (isInitialized) {
23 return;
68 * Generates a new correlation ID for request tracking.
69 */
70export function generateCorrelationId(): string {
71 return crypto.randomUUID();
72}
75 * Sets the correlation ID for the current context.
76 */
77export function setCorrelationId(correlationId: string): void {
78 currentCorrelationId = correlationId;
79}
82 * Gets the current correlation ID.
83 */
84export function getCorrelationId(): string | null {
85 return currentCorrelationId;
86}
89 * Clears the current correlation ID.
90 */
91export function clearCorrelationId(): void {
92 currentCorrelationId = null;
93}
94
95/**
96 * Executes a function with a specific correlation ID context.
97 */
98export async function withCorrelationId<T>(
99 correlationId: string,
100 fn: () => Promise<T> | T,
170 * Formats log entry as JSON.
171 */
172function formatAsJSON(logRecord: LogRecord): string {
173 const config = getConfig('logging');
174
196 * Formats log entry as human-readable text.
197 */
198function formatAsText(logRecord: LogRecord): string {
199 const config = getConfig('logging');
200 const timestamp = new Date().toISOString();
221
222// ========================================
223// Core Logging Functions
224// ========================================
225
227 * Creates a structured log entry.
228 */
229function createLogEntry(
230 level: LogLevel,
231 message: string,
277 * Logs debug information.
278 */
279export function logDebug(
280 message: string,
281 operation?: string,
288 * Logs general information.
289 */
290export function logInfo(
291 message: string,
292 operation?: string,
299 * Logs warning messages.
300 */
301export function logWarn(
302 message: string,
303 operation?: string,
310 * Logs error messages.
311 */
312export function logError(
313 message: string,
314 error?: Error,
320
321// ========================================
322// Specialized Logging Functions
323// ========================================
324
326 * Logs HTTP request information.
327 */
328export function logHttpRequest(
329 method: string,
330 path: string,
347 * Logs HTTP response information.
348 */
349export function logHttpResponse(
350 method: string,
351 path: string,
372 * Logs security events.
373 */
374export function logSecurityEvent(event: SecurityEvent): void {
375 const level = event.severity === 'critical' || event.severity === 'high' ? 'ERROR' : 'WARN';
376
392 * Logs performance events.
393 */
394export function logPerformanceEvent(event: PerformanceEvent): void {
395 const level = event.success ? 'DEBUG' : 'WARN';
396
411 * Logs database operations.
412 */
413export function logDatabaseOperation(
414 operation: string,
415 table: string,
437 * Logs nonce operations.
438 */
439export function logNonceOperation(
440 operation: 'generate' | 'validate' | 'expire' | 'reuse',
441 nonce: string,
466 * Logs authentication events.
467 */
468export function logAuthEvent(
469 type: 'success' | 'failure' | 'generate' | 'validate' | 'exchange' | 'refresh' | 'internal',
470 method: string,
491 * Logs crypto operations.
492 */
493export function logCryptoOperation(
494 operation: 'hash' | 'sign' | 'verify' | 'random',
495 algorithm: string,
523 * Measures and logs the duration of an operation.
524 */
525export async function measureAndLog<T>(
526 operation: string,
527 fn: () => Promise<T> | T,
563 * Creates a performance timer for manual measurement.
564 */
565export function createTimer(operation: string) {
566 const startTime = performance.now();
567
586 * Creates request logging data for middleware.
587 */
588export function createRequestLog(request: Request): {
589 correlationId: string;
590 startTime: number;
610 * Logs request completion.
611 */
612export function logRequestCompletion(
613 logData: Record<string, any>,
614 response: Response,
632 * Logs application startup.
633 */
634export function logStartup(version: string, environment: string): void {
635 logInfo(
636 `SafeHash API v${version} starting in ${environment} mode`,
643 * Logs application shutdown.
644 */
645export function logShutdown(reason: string): void {
646 logInfo(
647 `SafeHash API shutting down: ${reason}`,
654 * Logs health check results.
655 */
656export function logHealthCheck(
657 service: string,
658 healthy: boolean,

ZenServercrypto.ts17 matches

@ianmenethilβ€’Updated 2 days ago
42 /**
43 * Generates HMAC signature for server responses using proper HMAC construction.
44 * Uses SHA3-256 as the underlying hash function.
45 */
46 generateHMAC(data: any, timestamp: string): string {
112 * Generates a secure nonce (32 hex characters).
113 */
114export function generateNonce(): string {
115 const bytes = crypto.getRandomValues(new Uint8Array(16));
116 return Array.from(bytes)
122 * Generates a secure random UUID v4.
123 */
124export function generateUUID(): string {
125 return crypto.randomUUID();
126}
129 * Generates a secure random string of specified length using given character set.
130 */
131export function generateRandomString(
132 length: number,
133 charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
147 * Uses Deno's built-in crypto API for PBKDF2.
148 */
149export async function hashPassword(password: string, salt?: string): Promise<{
150 hash: string;
151 salt: string;
189 * Verifies a password against a hash.
190 */
191export async function verifyPassword(
192 password: string,
193 hash: string,
216 * Creates a SHA-256 hash of data using Deno's built-in crypto.
217 */
218export async function sha256(data: string): Promise<string> {
219 const encoder = new TextEncoder();
220 const dataBuffer = encoder.encode(data);
230 * Creates a SHA-512 hash of data using Deno's built-in crypto.
231 */
232export async function sha512(data: string): Promise<string> {
233 const encoder = new TextEncoder();
234 const dataBuffer = encoder.encode(data);
244 * Generates cryptographically secure random bytes.
245 */
246export function getRandomBytes(length: number): Uint8Array {
247 if (length <= 0 || !Number.isInteger(length)) {
248 throw new Error('Length must be a positive integer');
255 * Generates a secure timestamp-based token.
256 */
257export function generateTimestampToken(): string {
258 const timestamp = Date.now().toString();
259 const randomBytes = getRandomBytes(8);
268 * Validates a timestamp token and extracts the timestamp.
269 */
270export function validateTimestampToken(
271 token: string,
272 maxAgeMs: number = 15 * 60 * 1000,
299 * Creates an encrypted token using AES-GCM.
300 */
301export async function encryptToken(
302 data: string,
303 key: CryptoKey,
330 * Decrypts a token using AES-GCM.
331 */
332export async function decryptToken(
333 encrypted: string,
334 iv: string,
360 * Generates an AES-GCM key for encryption/decryption.
361 */
362export async function generateEncryptionKey(): Promise<CryptoKey> {
363 return await crypto.subtle.generateKey(
364 {
374 * Imports an encryption key from raw bytes.
375 */
376export async function importEncryptionKey(keyBytes: Uint8Array): Promise<CryptoKey> {
377 return await crypto.subtle.importKey(
378 'raw',
388
389// ========================================
390// Factory Function
391// ========================================
392
394 * Creates a new CryptoService instance.
395 */
396export function createCryptoService(): CryptoService {
397 return new CryptoServiceImpl();
398}

ZenServersecurity-service.ts12 matches

@ianmenethilβ€’Updated 2 days ago
421
422 /**
423 * Clears rate limit for a key (admin function).
424 */
425 clearRateLimit(key: string): boolean {
506
507 /**
508 * Gets list of blocked IPs (admin function).
509 */
510 getBlockedIPs(): string[] {
513
514 /**
515 * Gets list of suspicious IPs (admin function).
516 */
517 getSuspiciousIPs(): string[] {
520
521 /**
522 * Unblocks an IP address (admin function).
523 */
524 unblockIP(ip: string): boolean {
535
536 /**
537 * Clears suspicious status for an IP (admin function).
538 */
539 clearSuspiciousIP(ip: string): boolean {
551
552// ========================================
553// Utility Functions
554// ========================================
555
557 * Creates a rate limit key for IP and endpoint.
558 */
559export function createRateLimitKey(
560 ip: string,
561 endpoint: string,
567 * Validates security headers comprehensively.
568 */
569export function validateSecurityHeaders(headers: Headers): {
570 valid: boolean;
571 issues: string[];
615 * Checks if request is from a known bot/crawler.
616 */
617export function isKnownBot(userAgent: string): boolean {
618 const botPatterns = [
619 /googlebot/i,
637 * Extracts geolocation info from IP (placeholder).
638 */
639export function getIPGeolocation(ip: string): {
640 country?: string;
641 region?: string;
672
673// ========================================
674// Factory Function
675// ========================================
676
678 * Creates a new security service instance.
679 */
680export function createSecurityService(): SecurityService {
681 return new SecurityServiceImpl();
682}

discordWebhook2 file matches

@stevekrouseβ€’Updated 3 days ago
Helper function to send Discord messages
tuna

tuna9 file matches

@jxnblkβ€’Updated 4 weeks ago
Simple functional CSS library for Val Town
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.