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=9&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 18483 results for "function"(1523ms)

stevensDemogetWeather.ts5 matches

@lm3m•Updated 3 hours ago
8const TABLE_NAME = `memories`;
9
10function summarizeWeather(weather: WeatherResponse) {
11 const summarizeDay = (day: WeatherResponse["weather"][number]) => ({
12 date: day.date,
25}
26
27async function generateConciseWeatherSummary(weatherDay) {
28 try {
29 // Get API key from environment
83}
84
85async function deleteExistingForecast(date: string) {
86 await sqlite.execute(
87 `
93}
94
95async function insertForecast(date: string, forecast: string) {
96 const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
97
112}
113
114export default async function getWeatherForecast(interval: number) {
115 const weather = await getWeather("Washington, DC");
116 console.log({ weather });

stevensDemogetCalendarEvents.ts6 matches

@lm3m•Updated 3 hours ago
6const LOCAL_TIMEZONE = "America/New_York";
7
8async function deleteExistingCalendarEvents() {
9 await sqlite.execute(
10 `
15}
16
17// Helper function to extract time from ISO string without timezone conversion
18function extractTimeFromISO(isoString) {
19 // Match the time portion of the ISO string
20 const timeMatch = isoString.match(/T(\d{2}):(\d{2}):/);
31}
32
33function formatEventToNaturalLanguage(event) {
34 const summary = event.summary || "Untitled event";
35
83}
84
85async function insertCalendarEvent(date, eventText) {
86 const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
87
97}
98
99export default async function getCalendarEvents() {
100 try {
101 const events = await getEvents(

stevensDemogenerateFunFacts.ts8 matches

@lm3m•Updated 3 hours ago
11 * @returns Array of previous fun facts
12 */
13async function getPreviousFunFacts() {
14 try {
15 const result = await sqlite.execute(
32 * @param dates Array of date strings in ISO format
33 */
34async function deleteExistingFunFacts(dates) {
35 try {
36 for (const date of dates) {
51 * @param factText The fun fact text
52 */
53async function insertFunFact(date, factText) {
54 try {
55 await sqlite.execute(
75 * @returns Array of generated fun facts
76 */
77async function generateFunFacts(previousFacts) {
78 try {
79 // Get API key from environment
197 * @returns Array of parsed facts
198 */
199function parseFallbackFacts(responseText, expectedDates) {
200 // Try to extract facts using regex
201 const factPattern = /(\d{4}-\d{2}-\d{2})["']?[,:]?\s*["']?(.*?)["']?[,}]/gs;
260
261/**
262 * Main function to generate and store fun facts for the next 7 days
263 */
264export async function generateAndStoreFunFacts() {
265 try {
266 // Get previous fun facts
301 * Intended to be used as a Val Town cron job
302 */
303export default async function() {
304 console.log("Running fun facts generation cron job...");
305 return await generateAndStoreFunFacts();

stevensDemo.cursorrules15 matches

@lm3m•Updated 3 hours ago
8### 1. Script Vals
9
10- Basic JavaScript/TypeScript functions
11- Can be imported by other vals
12- Example structure:
13
14```typescript
15export function myFunction() {
16 // Your code here
17}
25
26```typescript
27export default async function (req: Request) {
28 return new Response("Hello World");
29}
37
38```typescript
39export default async function () {
40 // Scheduled task code
41}
49
50```typescript
51export default async function (email: Email) {
52 // Process email
53}
57
58- Ask clarifying questions when requirements are ambiguous
59- Provide complete, functional solutions rather than skeleton implementations
60- Test your logic against edge cases before presenting the final solution
61- Ensure all code follows Val Town's specific platform requirements
70- **Never bake in secrets into the code** - always use environment variables
71- Include comments explaining complex logic (avoid commenting obvious operations)
72- Follow modern ES6+ conventions and functional programming practices if possible
73
74## Val Town Standard Libraries
75
76Val Town provides several hosted services and utility functions.
77
78### Blob Storage
124```
125
126## Val Town Utility Functions
127
128Val Town provides several utility functions to help with common project tasks.
129
130### Importing Utilities
176 {
177 name: "should add numbers correctly",
178 function: () => {
179 expect(1 + 1).toBe(2);
180 },
210│ ├── database/
211│ │ ├── migrations.ts # Schema definitions
212│ │ ├── queries.ts # DB query functions
213│ │ └── README.md
214│ ├── index.ts # Main entry point
226└── shared/
227 ├── README.md
228 └── utils.ts # Shared types and functions
229```
230
232- Hono is the recommended API framework (similar to Express, Flask, or Sinatra)
233- Main entry point should be `backend/index.ts`
234- **Static asset serving:** Use the utility functions to read and serve project files:
235 ```ts
236 // Use the serveFile utility to handle content types automatically
273- Run migrations on startup or comment out for performance
274- Change table names when modifying schemas rather than altering
275- Export clear query functions with proper TypeScript typing
276- Follow the queries and migrations pattern from the example
277

stevensDemocronDailyBrief.ts1 match

@lm3m•Updated 3 hours ago
1import { sendDailyBriefing } from "./sendDailyBrief.ts";
2
3export async function cronDailyBrief() {
4 try {
5 const chatId = Deno.env.get("TELEGRAM_CHAT_ID");

stevensDemoApp.tsx2 matches

@lm3m•Updated 3 hours ago
62};
63
64export function App() {
65 const [memories, setMemories] = useState<Memory[]>([]);
66 const [loading, setLoading] = useState(true);
139 const data = await response.json();
140
141 // Change the sorting function to show memories in chronological order
142 const sortedMemories = [...data].sort((a, b) => {
143 const dateA = a.createdDate || 0;

TodoistTesttoday_and_overdue.tsx3 matches

@lm3m•Updated 3 hours ago
3import React, { useEffect, useState } from "https://esm.sh/react@18.2.0";
4
5function App() {
6 const [tasks, setTasks] = useState<any[]>([]);
7 const [loading, setLoading] = useState(false);
114}
115
116function client() {
117 createRoot(document.getElementById("root")).render(<App />);
118}
119if (typeof document !== "undefined") { client(); }
120
121export default async function server(request: Request): Promise<Response> {
122 // Todoist API endpoint
123 const TODOIST_API_BASE = "https://api.todoist.com/rest/v2";

untitled-2512new-file-9861.tsx13 matches

@Get•Updated 3 hours ago
74
75// --- HTML Generation for UI (with Glassmorphic Styling and Upload Form) ---
76function generateViewerHtml(tagsData: StoredTag[], dbError?: string): string {
77 const tagsJson = JSON.stringify(tagsData);
78 const sourceUrl = import.meta.url.replace("esm.town", "val.town");
373 const sourceApiUrl = "${sourceUrl}"; // For form submission
374
375        function escapeHtml(unsafe) {
376            if (unsafe === null || typeof unsafe === 'undefined') return '';
377            return unsafe
384        }
385
386        function renderTable(filteredData) {
387            const container = document.getElementById('tagsTableContainer');
388            if (!container) return;
406        }
407
408        function renderTagsByDocument(data) {
409            const container = document.getElementById('tagsByDocumentContainer');
410            if (!container) return;
474
475            if (uploadForm && uploadStatusDiv) {
476              uploadForm.addEventListener('submit', async function(event) {
477                  event.preventDefault();
478                  uploadStatusDiv.style.display = 'block';
552}
553
554// --- SQLite Helper Functions (Refactored) ---
555// ... (ensureTableExists and storeTags remain the same)
556async function ensureTableExists(log: LogEntry[]) {
557 const agent = "SQLite Agent";
558 try {
575}
576
577async function storeTags(documentIdentifier: string, tags: string[], log: LogEntry[]) {
578 const agent = "SQLite Agent";
579 if (!tags || tags.length === 0) {
623
624// --- Main Val Export ---
625export default async function(req: Request) {
626 // --- Dynamic Imports (Inside Handler for Val Town) ---
627 const { OpenAI } = await import("https://esm.town/v/std/openai");
631
632 // ---Extract Text using pdf.js-extract ---
633 async function extractPdfTextNative(data: ArrayBuffer, fileName: string, log: LogEntry[]): Promise<string | null> {
634 const agent = "PDF Extraction Agent";
635 log.push({ agent, type: "step", message: `Processing PDF: ${fileName}...` });
653 }
654
655 // --- Helper Function: Call OpenAI API ---
656 async function callOpenAI(
657 openai: OpenAI,
658 systemPrompt: string,
690
691 // --- Main Agent Flow Logic ---
692 async function runExtractionWorkflow(
693 input: { documentUrl?: string; documentText?: string; documentFile?: File },
694 log: LogEntry[],

Townieschema.tsx2 matches

@valdottown•Updated 4 hours ago
21}
22
23async function createTables() {
24 // archive a table
25 // await sqlite.execute(
51}
52
53async function deleteTables() {
54 await sqlite.execute(`DROP TABLE IF EXISTS ${USAGE_TABLE}`);
55}

EEPMOnitoringnewsArticle.tsx5 matches

@solomonferede•Updated 4 hours ago
428
429// Main Component for the News Article Tab - Adapted to use inline styles and MediaMonitoringTab patterns
430export function NewsArticleTab({ user }) {
431 const [articles, setArticles] = useState([]);
432 const [title, setTitle] = useState("");
601 };
602
603 // Function to open the edit modal - Similar pattern to MediaMonitoringTab
604 const handleEditClick = (article) => {
605 // Assuming article properties match backend column names (e.g., main_idea)
617 };
618
619 // Function to close the edit modal - Similar pattern to MediaMonitoringTab
620 const handleCloseEditModal = () => {
621 setIsEditModalOpen(false);
631 };
632
633 // Function to handle changes in the edit modal form - Similar pattern to MediaMonitoringTab
634 const handleEditFormChange = (e) => {
635 const { name, value } = e.target;
640 };
641
642 // Function to save the edited entry - Similar pattern to MediaMonitoringTab
643 const handleSaveEdit = async () => {
644 // Validate required fields from editFormData

getFileEmail4 file matches

@shouser•Updated 2 weeks ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblk•Updated 2 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.