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/$%7BsvgDataUrl%7D?q=api&page=16&format=json

For typeahead suggestions, use the /typeahead endpoint:

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

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

Found 19245 results for "api"(1978ms)

Louai_performance_api.ts15 matches

@jeffvincentβ€’Updated 2 hours ago
1/**
2 * AI Team Performance Analysis HTTP API
3 *
4 * Provides HTTP endpoints for triggering analysis and accessing results
15
16/**
17 * Main HTTP handler for AI performance analysis API
18 *
19 * Supported endpoints:
71
72 if (method === "GET" && pathname === "/") {
73 return await handleApiDocumentation(corsHeaders);
74 }
75
94 );
95 } catch (error) {
96 console.error("API Error:", error);
97 return new Response(
98 JSON.stringify({
131 }
132
133 console.log(`πŸš€ API: Starting analysis for user ${userId}, league ${leagueId}`);
134 const startTime = Date.now();
135
159 }
160
161 console.log(`βœ… API: Analysis complete in ${executionTime}ms`);
162
163 // Return structured response
205async function handleGetAnalysis(userId: string, corsHeaders: Record<string, string>): Promise<Response> {
206 try {
207 console.log(`πŸ“Š API: Retrieving latest analysis for user ${userId}`);
208
209 const latestAnalysis = await getLatestAnalysis(userId);
259 timestamp: new Date().toISOString(),
260 services: {
261 api: "operational",
262 scheduler: schedulerSummary.error ? "degraded" : "operational",
263 storage: "operational",
319 await addSchedulerConfig(schedulerConfig);
320
321 console.log(`⏰ API: Scheduler config added for user ${config.userId}`);
322
323 return new Response(
363 await removeSchedulerConfig(userId, leagueId);
364
365 console.log(`πŸ—‘οΈ API: Scheduler config removed for user ${userId}`);
366
367 return new Response(
398 summary,
399 nextRun: "Configured in Val.town cron settings",
400 documentation: "See API docs for scheduling configuration",
401 };
402
417
418/**
419 * Handle API documentation request
420 * GET /
421 */
422async function handleApiDocumentation(corsHeaders: Record<string, string>): Promise<Response> {
423 const docs = {
424 title: "AI Fantasy Baseball Performance Analysis API",
425 version: "1.0.0",
426 description: "API for triggering AI-powered fantasy baseball analysis and waiver wire recommendations",
427 endpoints: {
428 "POST /analyze": {

Loudaily_lineup_scheduler.tsx26 matches

@jeffvincentβ€’Updated 2 hours ago
90}
91
92export interface YahooAPIConfig {
93 access_token: string;
94 refresh_token: string;
167 }
168
169 // Initialize Yahoo Fantasy API client
170 const yahooAPI = new YahooFantasyAPIClient(tokenData, this.tokenStorage, userId);
171
172 // Get user's leagues
173 const leagues = await yahooAPI.getUserLeagues(userId);
174 console.log(`🏟️ Found ${leagues.length} leagues for user ${userId}`);
175
179
180 // Get user's team in this league
181 const teamKey = await yahooAPI.getTeamKey(userId, league.league_id);
182 if (!teamKey) {
183 throw new Error(`Could not find team key for league ${league.league_id}`);
185
186 // Schedule pitchers for today
187 const scheduleResult = await this.schedulePitchersForTeam(yahooAPI, teamKey, date);
188
189 results.leagues_processed.push({
207 }
208
209 private async schedulePitchersForTeam(yahooAPI: YahooFantasyAPIClient, teamKey: string, date: Date) {
210 // Get today's probable pitchers from MLB API
211 const probablePitchers = await this.getTodaysProbablePitchers(date);
212 console.log(`🎯 Found ${probablePitchers.length} probable pitchers for ${date.toDateString()}`);
213
214 // Get current team roster
215 const roster = await yahooAPI.getTeamRoster(teamKey);
216 console.log(`πŸ‘₯ Team roster has ${roster.length} players`);
217
234 for (const change of optimization.changes) {
235 try {
236 await yahooAPI.setPlayerPosition(teamKey, change.playerId, change.newPosition);
237 results.pitchers_scheduled.push(change.playerId);
238 results.changes_made.push(change);
254 ): Promise<Array<{ name: string; team: string; game_time?: string }>> {
255 try {
256 // Call MLB Stats API for probable pitchers
257 const dateStr = date.toISOString().split("T")[0];
258 const response = await fetch(
259 `https://statsapi.mlb.com/api/v1/schedule?sportId=1&date=${dateStr}&hydrate=probablePitcher`,
260 );
261
262 if (!response.ok) {
263 throw new Error(`MLB API error: ${response.status}`);
264 }
265
508}
509
510// Simplified Yahoo Fantasy API client for Val.town
511export class YahooFantasyAPIClient {
512 private config: YahooAPIConfig;
513 private baseUrl = "https://fantasysports.yahooapis.com/fantasy/v2";
514 private tokenStorage: LouTokenStorage;
515 private userId: string;
516
517 constructor(config: YahooAPIConfig, tokenStorage: LouTokenStorage, userId: string) {
518 this.config = config;
519 this.tokenStorage = tokenStorage;
533 private async refreshAccessToken(): Promise<void> {
534 try {
535 const response = await fetch("https://api.login.yahoo.com/oauth2/get_token", {
536 method: "POST",
537 headers: {
619
620 if (!retryResponse.ok) {
621 throw new Error(`Yahoo API error after refresh: ${retryResponse.status} ${retryResponse.statusText}`);
622 }
623
626
627 if (!response.ok) {
628 throw new Error(`Yahoo API error: ${response.status} ${response.statusText}`);
629 }
630
812 await this.ensureValidToken();
813
814 // Yahoo Fantasy API requires XML for roster changes
815 const dateStr = new Date().toISOString().split("T")[0];
816
844 if (!response.ok) {
845 const responseText = await response.text();
846 console.error(`❌ Yahoo API error response: ${responseText}`);
847 throw new Error(`Failed to set player position: ${response.status} ${response.statusText}`);
848 }
1092 // Get player stats if available
1093 const seasonStats: Record<string, string | number> = {};
1094 // Note: Individual player stats would require separate API calls
1095 // For waiver wire, we focus on basic availability and position info
1096
1148
1149 // Check if player has ownership information
1150 // Yahoo API doesn't directly provide ownership percentage, so we estimate based on availability
1151 let ownershipPercentage = 0;
1152 let isAvailable = true;
1391
1392 // Store results in Val.town's blob storage for history
1393 await fetch("https://api.val.town/v1/blob/scheduler_results", {
1394 method: "POST",
1395 headers: {

Louai_team_performance_review.ts46 matches

@jeffvincentβ€’Updated 2 hours ago
7 TeamPerformanceStats,
8 WaiverWirePlayer,
9 YahooFantasyAPIClient,
10} from "../daily_lineup_scheduler.tsx";
11import { LouTokenStorage } from "../token_storage.tsx";
135 review?: AITeamPerformanceReview;
136 error?: {
137 type: "AUTH_ERROR" | "API_ERROR" | "ANALYSIS_ERROR" | "VALIDATION_ERROR" | "UNKNOWN_ERROR";
138 message: string;
139 details?: any;
141 execution_stats: {
142 duration_ms: number;
143 api_calls_made: number;
144 tokens_used?: number;
145 rate_limited: boolean;
213 ): Promise<ReviewExecutionResult> {
214 const startTime = Date.now();
215 let apiCallsCounter = 0;
216 let rateLimited = false;
217
226 "No valid authentication tokens found",
227 startTime,
228 apiCallsCounter,
229 rateLimited,
230 );
231 }
232
233 // Step 2: Initialize Yahoo API client
234 const yahooAPI = new YahooFantasyAPIClient(tokenData, this.tokenStorage, userId);
235
236 // Step 3: Get team key if not provided
237 if (!teamKey) {
238 teamKey = await yahooAPI.getTeamKey(userId, leagueId);
239 apiCallsCounter++;
240
241 if (!teamKey) {
242 return this.createErrorResult(
243 "API_ERROR",
244 "Could not determine team key for user in league",
245 startTime,
246 apiCallsCounter,
247 rateLimited,
248 );
254 // Step 4: Gather comprehensive performance data
255 console.log("πŸ“Š Gathering performance data...");
256 const performanceData = await this.gatherPerformanceData(yahooAPI, teamKey, leagueId);
257 apiCallsCounter += performanceData.apiCalls;
258 rateLimited = rateLimited || performanceData.rateLimited;
259
260 if (!performanceData.success) {
261 return this.createErrorResult(
262 "API_ERROR",
263 "Failed to gather performance data",
264 startTime,
265 apiCallsCounter,
266 rateLimited,
267 performanceData.error,
277 `Data validation failed: ${validationResult.errors.join(", ")}`,
278 startTime,
279 apiCallsCounter,
280 rateLimited,
281 );
296 "Failed to generate performance analysis report",
297 startTime,
298 apiCallsCounter,
299 rateLimited,
300 );
309 "AI analysis failed",
310 startTime,
311 apiCallsCounter,
312 rateLimited,
313 aiAnalysisResult.error,
326 "Waiver analysis failed",
327 startTime,
328 apiCallsCounter,
329 rateLimited,
330 waiverAnalysisResult.error,
349 execution_stats: {
350 duration_ms: duration,
351 api_calls_made: apiCallsCounter,
352 rate_limited: rateLimited,
353 },
359 error instanceof Error ? error.message : "Unknown error occurred",
360 startTime,
361 apiCallsCounter,
362 rateLimited,
363 error,
419 results: {
420 authentication: boolean;
421 yahooAPI: boolean;
422 openAI: boolean;
423 performanceAnalyzer: boolean;
429 const results = {
430 authentication: false,
431 yahooAPI: false,
432 openAI: false,
433 performanceAnalyzer: false,
445 }
446
447 // Test 2: OpenAI API
448 try {
449 const openAITest = await this.openaiClient.testConnection();
468 }
469
470 // Test 4: Yahoo API (requires valid tokens, so just test instantiation)
471 try {
472 const testTokens = { access_token: "test", refresh_token: "test", expires_at: Date.now() + 3600000 };
473 const yahooAPI = new YahooFantasyAPIClient(testTokens, this.tokenStorage, "test_user");
474 results.yahooAPI = true; // If instantiation succeeds
475 console.log("βœ… Yahoo API test passed");
476 } catch (error) {
477 errors.push(`Yahoo API test failed: ${error}`);
478 console.log("❌ Yahoo API test failed");
479 }
480
497 */
498 private async gatherPerformanceData(
499 yahooAPI: YahooFantasyAPIClient,
500 teamKey: string,
501 leagueId: string,
508 leagueContext?: any;
509 };
510 apiCalls: number;
511 rateLimited: boolean;
512 error?: any;
513 }> {
514 let apiCalls = 0;
515 let rateLimited = false;
516
517 try {
518 // Get team performance stats
519 const teamStats = await yahooAPI.getTeamPerformanceStats(teamKey, leagueId);
520 apiCalls++;
521
522 if (!teamStats) {
525
526 // Get team roster
527 const roster = await yahooAPI.getTeamRoster(teamKey);
528 apiCalls++;
529
530 // Get detailed player performance (batch process to avoid rate limits)
534 for (let i = 0; i < roster.length; i += batchSize) {
535 const batch = roster.slice(i, i + batchSize);
536 const batchPromises = batch.map(player => yahooAPI.getPlayerPerformanceStats(player.player_id, leagueId));
537
538 try {
539 const batchResults = await Promise.allSettled(batchPromises);
540 apiCalls += batch.length;
541
542 for (const result of batchResults) {
557
558 // Get waiver wire players
559 const waiverPlayers = await yahooAPI.getWaiverWirePlayers(
560 leagueId,
561 undefined, // No position filter
562 undefined, // No ownership threshold
563 );
564 apiCalls++;
565
566 // Limit waiver candidates to avoid token overflow
578 teamKey,
579 );
580 // Note: This doesn't count as additional API calls since it uses cached data
581 } catch (error) {
582 console.log("⚠️ Could not gather league context:", error);
592 leagueContext,
593 },
594 apiCalls,
595 rateLimited,
596 };
598 return {
599 success: false,
600 apiCalls,
601 rateLimited,
602 error,
832 message: string,
833 startTime: number,
834 apiCalls: number,
835 rateLimited: boolean,
836 details?: any,
841 execution_stats: {
842 duration_ms: Date.now() - startTime,
843 api_calls_made: apiCalls,
844 rate_limited: rateLimited,
845 },
15Use GlobalRateLimitedChatOpenAI(model, requestsPerSecond) to enforce a global rate limit on chat completions, suitable for shared or public-facing endpoints.
16Val Town/Platform Notes
17Uses Val Town’s standard SQLite API for persistent storage.
18Designed for server-side use (no browser-specific code).
19No secrets are hardcoded; OpenAI API keys are managed by the OpenAI SDK/environment.

openai-clientopenai-client.mdc2 matches

@cricks_unmixed4uβ€’Updated 2 hours ago
15Use GlobalRateLimitedChatOpenAI(model, requestsPerSecond) to enforce a global rate limit on chat completions, suitable for shared or public-facing endpoints.
16Val Town/Platform Notes
17Uses Val Town’s standard SQLite API for persistent storage.
18Designed for server-side use (no browser-specific code).
19No secrets are hardcoded; OpenAI API keys are managed by the OpenAI SDK/environment.

sqliteExplorerApp1README.md1 match

@tmcwβ€’Updated 2 hours ago
13## Authentication
14
15Login to your SQLite Explorer with [password authentication](https://www.val.town/v/pomdtr/password_auth) with your [Val Town API Token](https://www.val.town/settings/api) as the password.
16
17## Todos / Plans

sqliteExplorerApp1main.tsx2 matches

@tmcwβ€’Updated 2 hours ago
27 <head>
28 <title>SQLite Explorer</title>
29 <link rel="preconnect" href="https://fonts.googleapis.com" />
30
31 <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
32 <link
33 href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@300..700&family=Source+Sans+3:ital,wght@0,200..900;1,200..900&display=swap"
34 rel="stylesheet"
35 />

openai-client.cursorrules10 matches

@cricks_unmixed4uβ€’Updated 2 hours ago
13- Generate code in TypeScript or TSX
14- Add appropriate TypeScript types and interfaces for all data structures
15- Prefer official SDKs or libraries than writing API calls directly
16- Ask the user to supply API or library documentation if you are at all unsure about it
17- **Never bake in secrets into the code** - always use environment variables
18- Include comments explaining complex logic (avoid commenting obvious operations)
23### 1. HTTP Trigger
24
25- Create web APIs and endpoints
26- Handle HTTP requests and responses
27- Example structure:
173However, it's *extremely importing* to note that `parseProject` and other Standard Library utilities ONLY RUN ON THE SERVER.
174If you need access to this data on the client, run it in the server and pass it to the client by splicing it into the HTML page
175or by making an API request for it.
176
177## Val Town Platform Specifics
181- **AI Image:** To inline generate an AI image use: `<img src="https://maxm-imggenurl.web.val.run/the-description-of-your-image" />`
182- **Storage:** DO NOT use the Deno KV module for storage
183- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
184- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
185- **View Source:** Add a view source link by importing & using `import.meta.url.replace("ems.sh", "val.town)"` (or passing this data to the client) and include `target="_top"` attribute
186- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
187- **Error Handling:** Only use try...catch when there's a clear local resolution; Avoid catches that merely log or return 500s. Let errors bubble up with full context
188- **Environment Variables:** Use `Deno.env.get('keyname')` when you need to, but generally prefer APIs that don't require keys
189- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
190- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
224### Backend (Hono) Best Practices
225
226- Hono is the recommended API framework
227- Main entry point should be `backend/index.ts`
228- **Static asset serving:** Use the utility functions to read and serve project files:
248 });
249 ```
250- Create RESTful API routes for CRUD operations
251- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
252 ```ts
285 - For files in the project, use `readFile` helpers
286
2875. **API Design:**
288 - `fetch` handler is the entry point for HTTP vals
289 - Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`

openai-clientknowledge.md10 matches

@cricks_unmixed4uβ€’Updated 2 hours ago
13- Generate code in TypeScript or TSX
14- Add appropriate TypeScript types and interfaces for all data structures
15- Prefer official SDKs or libraries than writing API calls directly
16- Ask the user to supply API or library documentation if you are at all unsure about it
17- **Never bake in secrets into the code** - always use environment variables
18- Include comments explaining complex logic (avoid commenting obvious operations)
23### 1. HTTP Trigger
24
25- Create web APIs and endpoints
26- Handle HTTP requests and responses
27- Example structure:
173However, it's *extremely importing* to note that `parseProject` and other Standard Library utilities ONLY RUN ON THE SERVER.
174If you need access to this data on the client, run it in the server and pass it to the client by splicing it into the HTML page
175or by making an API request for it.
176
177## Val Town Platform Specifics
181- **AI Image:** To inline generate an AI image use: `<img src="https://maxm-imggenurl.web.val.run/the-description-of-your-image" />`
182- **Storage:** DO NOT use the Deno KV module for storage
183- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
184- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
185- **View Source:** Add a view source link by importing & using `import.meta.url.replace("ems.sh", "val.town)"` (or passing this data to the client) and include `target="_top"` attribute
186- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
187- **Error Handling:** Only use try...catch when there's a clear local resolution; Avoid catches that merely log or return 500s. Let errors bubble up with full context
188- **Environment Variables:** Use `Deno.env.get('keyname')` when you need to, but generally prefer APIs that don't require keys
189- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
190- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
224### Backend (Hono) Best Practices
225
226- Hono is the recommended API framework
227- Main entry point should be `backend/index.ts`
228- **Static asset serving:** Use the utility functions to read and serve project files:
248 });
249 ```
250- Create RESTful API routes for CRUD operations
251- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
252 ```ts
285 - For files in the project, use `readFile` helpers
286
2875. **API Design:**
288 - `fetch` handler is the entry point for HTTP vals
289 - Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`

quizMastergemini.tsx1 match

@affanβ€’Updated 3 hours ago
1import { GoogleGenAI, Type } from "npm:@google/genai";
2
3const ai = new GoogleGenAI({ apiKey: "AIzaSyDcuswpF8sAUBVTvrUlnpADXF4gHjTTAxA" });
4
5const _prompt = `Parse the image and extract the question and options, also find the answer if given otherwise return "".

api_ianmenethil_com133 file matches

@ianmenethilβ€’Updated 1 hour ago

api_ianmenethil_com74 file matches

@ianmenethilβ€’Updated 8 hours ago
apiry
snartapi