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$%7Burl%7D/%22https:/esm.town/v/std/catch//%22?q=api&page=1&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 25519 results for "api"(1453ms)

location-feed-generatorcheckins.ts8 matches

@tijs•Updated 58 mins ago
1// Checkin creation API endpoint for Anchor
2import type { Context } from "jsr:@hono/hono@4.9.6";
3import { OverpassService } from "../services/overpass-service.ts";
17 */
18/**
19 * Convert API PlaceInput to proper Place object
20 */
21function _sanitizePlaceInput(input: PlaceInput): Place {
123}
124
125// API input format - coordinates might be strings
126interface PlaceInput {
127 name: string;
129 longitude: number | string;
130 tags: Record<string, string>;
131 // Optional fields that might be missing from API input
132 id?: string;
133 elementType?: "node" | "way" | "relation";
237 const { message } = body;
238
239 // Convert API input to proper Place object and validate coordinates
240 const place = _sanitizePlaceInput(body.place);
241 const lat = place.latitude;
255 console.log("🚀 Starting checkin creation process...");
256
257 // Get sessions instance for clean OAuth API access
258 const { sessions } = await import("../routes/oauth.ts");
259
295}
296
297// Create address and checkin records via AT Protocol using clean OAuth API
298async function createAddressAndCheckin(
299 sessions: OAuthSessionsInterface,
307 console.log(`🔰 Getting OAuth session for DID: ${did}`);
308
309 // Use the clean API to get a ready-to-use OAuth session
310 const oauthSession = await sessions.getOAuthSession(did);
311 if (!oauthSession) {

location-feed-generatorsettings.local.json2 matches

@tijs•Updated 58 mins ago
9 "Bash(/Users/tijs/projects/Anchor/location-feed-generator/scripts/test.sh:*)",
10 "Bash(./scripts/test.sh:*)",
11 "Bash(./scripts/test-api.sh:*)",
12 "Bash(vt list:*)",
13 "Bash(vt browse:*)",
14 "Bash(ls:*)",
15 "Bash(./scripts/monitor-api.sh:*)",
16 "Bash(swift test:*)",
17 "Bash(swift build:*)",

zoomtest.cursorrules10 matches

@yawnxyz•Updated 1 hour 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`

chatterchatStream.js7 matches

@yawnxyz•Updated 1 hour ago
3// import { buildSearchPrompt, routeQueryMode } from "../../chatCompletion.js"; // routing disabled
4// import { extractOrRepairJsonResults, extractResultsFromToolOutputs, sanitizeResults, synthesizeResultsFromContext } from "../../jsonUtils.js"; // links/results disabled
5import { serverApiKey } from "../config.js";
6
7function collectToolTextFromArray(toolArray) {
24
25export function registerChatStreamRoute(app) {
26 app.post('/api/chatStream', async (c) => {
27 try {
28 let body = {};
30
31 const {
32 userApiKey,
33 messages,
34 query,
49 } = body || {};
50
51 const apiKey = serverApiKey || userApiKey || (typeof Deno !== 'undefined' ? Deno.env.get('GROQ_API_KEY') : null);
52 if (!apiKey && !base_url) {
53 return c.json({ error: 'No Groq API key available. Please provide your own key.' }, 400);
54 }
55
114 }
115 }
116 const aggregates = await streamChatAndAggregate(apiKey, payload, { logSse: false, endpoint });
117 // links/results extraction disabled — return only collapsed chat aggregates
118 console.log('>> [chatStream] textContent:', aggregates?.collapsed?.content || '');

chatterjobs.js13 matches

@yawnxyz•Updated 1 hour ago
1// Generic Jobs API with SSE updates
2// import { buildSearchPrompt, routeQueryMode } from "../../chatCompletion.js"; // routing disabled
3// import { extractOrRepairJsonResults, extractResultsFromToolOutputs, sanitizeResults, synthesizeResultsFromContext } from "../../jsonUtils.js"; // links/results disabled
4import { serverApiKey } from "../config.js";
5
6/**
94 const input = job.input || {};
95 const {
96 userApiKey,
97 messages,
98 query,
112 } = input;
113
114 const apiKey = serverApiKey || userApiKey || (typeof Deno !== "undefined" ? Deno.env.get("GROQ_API_KEY") : null);
115 if (!apiKey && !base_url) {
116 failJob(job, "No API key (or base_url) provided");
117 return;
118 }
171
172 const baseUrl = (typeof base_url === "string" && base_url.trim()) ? base_url.trim().replace(/\/$/, "") : "";
173 let endpoint = "https://api.groq.com/openai/v1/chat/completions";
174 if (baseUrl) {
175 if (/(\/v\d+)?\/(chat\/)?completions$/i.test(baseUrl)) {
184 const headers = {
185 "Content-Type": "application/json",
186 ...(apiKey ? { "Authorization": "Bearer " + apiKey } : {}),
187 };
188
306export function registerJobsRoutes(app) {
307 // Create job
308 app.post('/api/jobs', async (c) => {
309 try {
310 let body = {};
327
328 // Get job
329 app.get('/api/jobs/:id', (c) => {
330 const id = c.req.param('id');
331 const job = getJob(id);
335
336 // List jobs (optionally filter by status)
337 app.get('/api/jobs', (c) => {
338 const status = c.req.query('status');
339 const out = [];
346
347 // Cancel job
348 app.post('/api/jobs/:id/cancel', (c) => {
349 const id = c.req.param('id');
350 const job = getJob(id);
356
357 // Stream job updates via SSE
358 app.get('/api/jobs/:id/stream', (c) => {
359 const id = c.req.param('id');
360 const job = getJob(id);

chatterchatCompletion.js14 matches

@yawnxyz•Updated 1 hour ago
1// Minimal Groq Chat Completions client using fetch
2import { extractOrRepairJsonResults, extractStructuredSummary, renderStructuredSummaryToHtml } from "./jsonUtils.js";
3export async function groqChatCompletion(apiKey, payload) {
4 console.log('>>> [groqChatCompletion] Payload:', payload);
5 const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
6 method: 'POST',
7 headers: {
8 'Content-Type': 'application/json',
9 'Authorization': `Bearer ${apiKey}`,
10 },
11 body: JSON.stringify(payload),
13 if (!response.ok) {
14 const text = await response.text();
15 throw new Error(`Groq API error: ${response.status} ${text}`);
16 }
17 // console.log('>>> [groqChatCompletion] Response:', response);
50
51// Lightweight router: decide between 'links' (JSON list) and 'text' (short answer)
52export async function routeQueryMode(apiKey, query) {
53 // Routing disabled: force plain chat mode
54 return 'text';
55 /*
56 try {
57 const res = await groqChatCompletion(apiKey, {
58 model: 'openai/gpt-oss-120b',
59 messages: [
77}
78
79export async function performSearch({ apiKey, query, dateRange, source, language, offset = 0, model, stream, reasoningEffort, forceLinksRoute = false }) {
80 // const prompt = buildSearchPrompt(query, source, dateRange, language, offset);
81 // const start = Date.now();
82 // const route = forceLinksRoute ? 'links' : await routeQueryMode(apiKey, query);
83 // const response = await groqChatCompletion(apiKey, {
84 // model,
85 // messages: route === 'text'
116 // } catch (_) {
117 // // as a fallback, attempt repair pass
118 // results = await extractOrRepairJsonResults(contentText, apiKey, language);
119 // }
120 // } else {
142- If this is a research paper, use the RESEARCH format below.
143- If this is a news/blog/listing/discussion page (e.g., HN, Reddit, news site), use the GENERAL format below.
144- DO NOT include any citations, reference numbers, or raw scraping artifacts.
145- Write in clear prose without formatting artifacts.
146- The opening line of the summary must not simply repeat the title; avoid mirroring the title.
167}
168
169export async function summarizeUrl({ apiKey, url, title, language, model, stream, reasoningEffort }) {
170 const summaryPrompt = buildSummaryPrompt(url, title, language);
171 const start = Date.now();
172 const response = await groqChatCompletion(apiKey, {
173 model,
174 messages: [
194 try {
195 const inner = (responseText.match(/<summary>([\s\S]*?)<\/summary>/) || [null, responseText])[1];
196 const structured = await extractStructuredSummary(inner, apiKey);
197 if (structured) {
198 cleanedHtml = renderStructuredSummaryToHtml(structured);

chatterchatStreamSSE.js13 matches

@yawnxyz•Updated 1 hour ago
2// import { buildSearchPrompt, routeQueryMode } from "../../chatCompletion.js"; // routing disabled
3// import { extractOrRepairJsonResults, sanitizeResults, synthesizeResultsFromContext, extractResultsFromToolOutputs } from "../../jsonUtils.js"; // links/results disabled
4import { serverApiKey } from "../config.js";
5
6function collectToolTextFromArray(toolArray) {
23
24export function registerChatStreamSSERoute(app) {
25 app.post('/api/chatStreamSSE', async (c) => {
26 try {
27 let body = {};
29
30 const {
31 userApiKey,
32 messages,
33 query,
48 } = body || {};
49
50 const apiKey = serverApiKey || userApiKey || (typeof Deno !== 'undefined' ? Deno.env.get('GROQ_API_KEY') : null);
51 if (!apiKey && !base_url) {
52 return c.json({ error: 'No Groq API key available. Please provide your own key.' }, 400);
53 }
54
108 const encoder = new TextEncoder();
109 const baseUrl = (typeof base_url === 'string' && base_url.trim()) ? base_url.trim().replace(/\/$/, '') : '';
110 let endpoint = 'https://api.groq.com/openai/v1/chat/completions';
111 if (baseUrl) {
112 if (/(\/v\d+)?\/(chat\/)?completions$/i.test(baseUrl)) {
123 const headers = {
124 'Content-Type': 'application/json',
125 ...(apiKey ? { 'Authorization': 'Bearer ' + apiKey } : {}),
126 };
127 const upstream = await fetch(endpoint, {
157 // if (selectedRoute !== 'text') {
158 // if (finalContent && finalContent.trim()) {
159 // results = await extractOrRepairJsonResults(finalContent, apiKey, language);
160 // }
161 // if ((!results || results.length === 0)) {
167 // reasoningText: '',
168 // existingResults: []
169 // }, apiKey);
170 // if (Array.isArray(synthesized) && synthesized.length > 0) {
171 // results = synthesized;
239 // const textForExtraction = (collapsedContent && collapsedContent.trim()) ? collapsedContent : ((collapsedReasoning && collapsedReasoning.trim()) ? collapsedReasoning : '');
240 // if (toolText && toolText.trim()) {
241 // results = await extractResultsFromToolOutputs(toolText, apiKey, language);
242 // }
243 // if ((!results || results.length === 0) && textForExtraction) {
244 // results = await extractOrRepairJsonResults(textForExtraction, apiKey, language);
245 // }
246 // if ((!results || results.length === 0)) {
252 // reasoningText: String(collapsedReasoning || ''),
253 // existingResults: []
254 // }, apiKey);
255 // if (Array.isArray(synthesized) && synthesized.length > 0) {
256 // results = synthesized;

untitled-1522api.ts16 matches

@jessicaocean•Updated 1 hour ago
29} from "../database/queries.ts";
30
31const api = new Hono();
32const openai = new OpenAI();
33
34// Middleware to ensure user is authenticated
35api.use('*', async (c, next) => {
36 const email = c.req.header('X-LastLogin-Email');
37 if (!email) {
47
48// Get user's conversations
49api.get('/conversations', async (c) => {
50 const user = c.get('user');
51 const conversations = await getUserConversationsWithParticipants(user.id);
54
55// Debug endpoint to check user status in a conversation
56api.get('/conversations/:id/status', async (c) => {
57 const user = c.get('user');
58 const conversationId = parseInt(c.req.param('id'));
78
79// Get specific conversation with messages
80api.get('/conversations/:id', async (c) => {
81 const user = c.get('user');
82 const conversationId = parseInt(c.req.param('id'));
99
100// Create new conversation
101api.post('/conversations', async (c) => {
102 const user = c.get('user');
103 const { title } = await c.req.json();
112
113// Delete conversation
114api.delete('/conversations/:id', async (c) => {
115 const user = c.get('user');
116 const conversationId = parseInt(c.req.param('id'));
130
131// Get conversation participants
132api.get('/conversations/:id/participants', async (c) => {
133 const user = c.get('user');
134 const conversationId = parseInt(c.req.param('id'));
152
153// Invite user to conversation
154api.post('/conversations/:id/invite', async (c) => {
155 const user = c.get('user');
156 const conversationId = parseInt(c.req.param('id'));
194
195 // Send invitation email
196 const inviteUrl = `${c.req.url.split('/api')[0]}/invite/${invite.invite_token}`;
197
198 try {
218
219// Remove participant from conversation
220api.delete('/conversations/:id/participants/:userId', async (c) => {
221 const user = c.get('user');
222 const conversationId = parseInt(c.req.param('id'));
248
249// Send chat message
250api.post('/chat', async (c) => {
251 const user = c.get('user');
252 const { message, conversationId }: ChatRequest = await c.req.json();
326
327// Get invite details (public endpoint)
328api.get('/invites/:token', async (c) => {
329 const token = c.req.param('token');
330
348
349// Accept invitation
350api.post('/invites/:token/accept', async (c) => {
351 const user = c.get('user');
352 const token = c.req.param('token');
381
382// Server-Sent Events for real-time updates
383api.get('/conversations/:id/stream', async (c) => {
384 const user = c.get('user');
385 const conversationId = parseInt(c.req.param('id'));
437});
438
439export default api;

untitled-1522README.md16 matches

@jessicaocean•Updated 1 hour ago
1# Backend
2
3Hono-based API server with LastLogin authentication, SQLite database, and group chat functionality.
4
5## Structure
7- `index.ts` - Main HTTP handler with LastLogin wrapper
8- `database/` - Database migrations and query functions
9- `routes/` - API route handlers
10
11## API Endpoints
12
13### Authentication
14- All API routes require authentication via LastLogin
15- User email is extracted from `X-LastLogin-Email` header
16
17### Conversations
18- `GET /api/conversations` - Get user's conversations (with participant info)
19- `GET /api/conversations/:id` - Get specific conversation with messages
20- `POST /api/conversations` - Create new conversation
21- `DELETE /api/conversations/:id` - Delete conversation (admin only)
22
23### Group Chat Features
24- `GET /api/conversations/:id/participants` - Get conversation participants
25- `POST /api/conversations/:id/invite` - Invite user by email (admin only)
26- `DELETE /api/conversations/:id/participants/:userId` - Remove participant (admin only)
27
28### Invitations
29- `GET /api/invites/:token` - Get invitation details (public)
30- `POST /api/invites/:token/accept` - Accept invitation and join conversation
31
32### Chat & Real-time
33- `POST /api/chat` - Send message and get ChatGPT response
34- `GET /api/conversations/:id/stream` - Server-Sent Events for real-time updates
35
36## Database Schema
49- **Automatic user creation** on first login
50- **Conversation history storage** with full message history
51- **ChatGPT integration** via OpenAI API
52- **Group chat functionality** with role-based permissions
53- **Email invitations** with secure tokens

untitled-1522README.md1 match

@jessicaocean•Updated 1 hour ago
31## Project Structure
32
33- `backend/` - Hono API server with authentication and group chat
34- `frontend/` - React chat interface with group features
35- `shared/` - Shared TypeScript types

PixelPixelApiMonitor1 file match

@selfire1•Updated 21 hours ago
Regularly polls the API and messages on an error.

weatherApp1 file match

@dcm31•Updated 1 day ago
A simple weather app with dropdown cities using Open-Meteo API
fapian
<("<) <(")> (>")>
Kapil01