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%22Image%20title%22?q=function&page=47&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 18949 results for "function"(742ms)

stevensDemo.cursorrules15 matches

@cdukeโ€ขUpdated 2 days 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

@cdukeโ€ขUpdated 2 days 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

@cdukeโ€ขUpdated 2 days 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;

HHGtoMyDaygenerateFunFacts.ts8 matches

@lm3mโ€ขUpdated 3 days 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
196 * @returns Array of parsed facts
197 */
198function parseFallbackFacts(responseText, expectedDates) {
199 // Try to extract facts using regex
200 const factPattern = /(\d{4}-\d{2}-\d{2})["']?[,:]?\s*["']?(.*?)["']?[,}]/gs;
259
260/**
261 * Main function to generate and store fun facts for the next 7 days
262 */
263export async function generateAndStoreFunFacts() {
264 try {
265 // Get previous fun facts
300 * Intended to be used as a Val Town cron job
301 */
302export default async function() {
303 console.log("Running fun facts generation cron job...");
304 return await generateAndStoreFunFacts();

HHGtoMyDaygetWeather.ts5 matches

@lm3mโ€ขUpdated 3 days ago
5const TABLE_NAME = `memories`;
6
7function summarizeWeather(weather: WeatherResponse) {
8 const summarizeDay = (day: WeatherResponse["weather"][number]) => ({
9 date: day.date,
21}
22
23async function generateConciseWeatherSummary(weatherDay) {
24 try {
25 // Get API key from environment
79}
80
81async function deleteExistingForecast(date: string) {
82 await sqlite.execute(
83 `
89}
90
91async function insertForecast(date: string, forecast: string) {
92 const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
93
108}
109
110export default async function getWeatherForecast(interval: number) {
111 const weather = await getWeather("Boston, MA");
112 console.log({ weather });

Discord_Bot_Servicesmap-vote-tallying.tsx21 matches

@ktodazโ€ขUpdated 3 days ago
1// Map Vote Tallying Function with Rate Limit Service Integration
2// This function counts emoji reactions and announces winners in a Hell Let Loose map vote
3import seedrandom from "https://esm.sh/seedrandom";
4import { DiscordRateLimitService } from "https://esm.town/v/ktodaz/Discord_Bot_Services/discord-rate-limit-service.tsx";
48
49// Enhanced Discord API request with rate limiting
50async function discordRequest(endpoint: string, options: RequestInit = {}) {
51 const token = Deno.env.get("DISCORD_BOT_TOKEN");
52 if (!token) {
104
105// Get emoji mapping to decode emoji reactions
106function getEmojiMapping() {
107 return {
108 "๐ŸŒ„": "Dawn",
119
120// Get color from string
121function getColorFromString(colorName: string): number {
122 const colorMap: Record<string, number> = {
123 "Red": 0xED4245,
139
140// Load configuration
141async function getConfiguration(): Promise<CurrentConfig> {
142 try {
143 const { success, config, error } = getCurrentConfig();
160
161// Load placeholder embed data
162export function getPlaceholderEmbedData(): Promise<PlaceholderEmbedData> {
163 return Promise.resolve({
164 Title: "The votes are in!",
171
172// Load top winners embed data
173export function getTopWinnersEmbedData(): Promise<TopWinnersEmbedData> {
174 return Promise.resolve({
175 Title: "Announcing The Top {0} Winners!",
182
183// Get all messages in a channel with rate limiting
184async function getChannelMessages(channelId: string) {
185 try {
186 let allMessages = [];
220
221// Get reactions for a specific message with rate limiting
222async function getMessageReactions(channelId: string, messageId: string, emoji: string) {
223 try {
224 const encodedEmoji = encodeURIComponent(emoji);
237
238// Get user info from Discord API with rate limiting
239async function getUserInfo(guildId: string, userId: string) {
240 try {
241 const routeKey = `/guilds/${guildId}/members`;
252
253// Send placeholder embed while counting votes
254async function sendPlaceholderEmbed(channelId: string) {
255 try {
256 const placeholderData = await getPlaceholderEmbedData();
284
285// Send winners announcement embed with rate limiting
286async function sendWinnersEmbed(
287 channelId: string,
288 winners: MapVote[],
339
340// Create a thread for full results with rate limiting
341async function createFullResultsThread(channelId: string, allVotes: MapVote[], userVotes: UserVote[]) {
342 try {
343 const channelRoutKey = `/channels/${channelId}/threads`;
474
475// Format processing time
476function formatProcessingTime(startTime: number): string {
477 const totalSeconds = Math.floor((Date.now() - startTime) / 1000);
478 const minutes = Math.floor(totalSeconds / 60);
487
488// Setup required database tables
489async function setupDatabase() {
490 // Create vote_sessions table if it doesn't exist
491 await sqlite.execute(`
528}
529
530// Main voting tallying function
531export default async function(channelId: string) {
532 console.log(`๐Ÿ”ข Starting vote tallying for channel ${channelId}`);
533 const startTime = Date.now();
594 console.log(`Processing: Embed: ${mapName} (${variant}), Reactions: ${reaction.count}`);
595
596 // Get users who reacted with this emoji - using rate limited function
597 const reactedUsers = await getMessageReactions(channelId, msg.id, emoji);
598 console.log(`Emote key ${variant}: ${reactedUsers.length} users`);
799}
800
801// Function to get previous vote results
802export async function getPreviousVoteResults(limit: number = 5) {
803 try {
804 await setupDatabase();

synced_reducermain.tsx1 match

@jeffreyyoungโ€ขUpdated 3 days ago
1export default async function(req: Request): Promise<Response> {
2 const url = new URL(req.url);
3 if (url.pathname === "/v1") {
8const CREATION_LOCK_KEY = "map_vote_creation_first_half";
9
10// Basic Discord request function with rate limiting
11async function safeDiscordRequest(endpoint: string, options: RequestInit = {}) {
12 const token = Deno.env.get("DISCORD_BOT_TOKEN");
13
43}
44
45// Simplified test function that just checks channel access
46async function testChannelAccess(channelId: string) {
47 try {
48 console.log(`Testing access to channel ${channelId}`);
73}
74
75// Main function
76export default async function() {
77 console.log("๐Ÿงช SIMPLE TEST: Map Vote Tally Channel Access Test");
78

untitled-4783main.js10 matches

@StayNullโ€ขUpdated 3 days ago
15
16// --- INITIALIZATION ---
17function init() {
18 // Scene
19 scene = new THREE.Scene();
77}
78
79function addBuilding(x, y, z, width, height, depth, color) {
80 const geometry = new THREE.BoxGeometry(width, height, depth);
81 const material = new THREE.MeshStandardMaterial({ color: color });
86
87// --- GAME LOOP & UPDATES ---
88function animate(currentTime) {
89 if (gameOver) {
90 scoreElement.innerText = `GAME OVER! Survived: ${Math.floor(gameTime / 1000)}s\nPress R to Restart`;
114let lastFrameTime = 0;
115
116function handlePlayerMovement() {
117 const moveDirection = new THREE.Vector3();
118 const rotationSpeed = playerTurnSpeed;
143}
144
145function updateCamera() {
146 const offset = new THREE.Vector3(0, 3, -6); // Camera offset from player
147 offset.applyQuaternion(player.quaternion); // Apply player's rotation to offset
150}
151
152function spawnCars(currentTime) {
153 if (currentTime - lastCarSpawnTime > CAR_SPAWN_INTERVAL) {
154 lastCarSpawnTime = currentTime;
179}
180
181function updateCars() {
182 cars.forEach((car, index) => {
183 car.position.z += car.userData.directionZ * car.userData.speed;
191}
192
193function checkCollisions() {
194 const playerBox = new THREE.Box3().setFromObject(player);
195 cars.forEach(car => {
204}
205
206function restartGame() {
207 gameOver = false;
208 gameTime = 0;
220
221// --- UTILITIES ---
222function onWindowResize() {
223 camera.aspect = window.innerWidth / window.innerHeight;
224 camera.updateProjectionMatrix();
luciaMagicLinkStarter

luciaMagicLinkStartermagic-links.ts3 matches

@stevekrouseโ€ขUpdated 3 days ago
5
6// Create a magic link token for the given email
7export async function createMagicLinkToken(userEmail: string): Promise<string> {
8 const token = generateSessionToken();
9 const now = Math.floor(Date.now() / 1000);
19
20// Send a magic link email
21export async function sendMagicLinkEmail(url: string, userEmail: string, token: string): Promise<boolean> {
22 try {
23 const magicLink = `${url}/auth/magic-link/${token}`;
47
48// Validate a magic link token and create a session
49export async function validateMagicLinkToken(token: string): Promise<{ valid: boolean; userId?: number }> {
50 const now = Math.floor(Date.now() / 1000);
51

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
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.
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": "*",