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=92&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 20583 results for "function"(1353ms)

vtProjectSearchutils.tsx2 matches

@tallesjpโ€ขUpdated 3 days ago
1// Format date to relative time
2export function formatRelativeTime(dateString: string): string {
3 const date = new Date(dateString);
4 const now = new Date();
37
38// Format date for tooltip (full date)
39export function formatFullDate(dateString: string): string {
40 const date = new Date(dateString);
41 return date.toLocaleDateString("en-US", {

vtProjectSearchdocsearch.ts2 matches

@tallesjpโ€ขUpdated 3 days ago
62 * @param query Search query
63 */
64export async function searchDocsCount(
65 query: string
66): Promise<number> {
85 * @param fetchData Whether to fetch the full data for each result
86 */
87export async function searchDocs(
88 query: string,
89 page: number = 1,

vtProjectSearchdeno.lock4 matches

@tallesjpโ€ขUpdated 3 days ago
145 "dependencies": [
146 "es-errors",
147 "function-bind"
148 ]
149 },
230 ]
231 },
232 "function-bind@1.1.2": {
233 "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="
234 },
240 "es-errors",
241 "es-object-atoms",
242 "function-bind",
243 "get-proto",
244 "gopd",
270 "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
271 "dependencies": [
272 "function-bind"
273 ]
274 },

vtProjectSearchdb.ts23 matches

@tallesjpโ€ขUpdated 3 days ago
9
10/**
11 * Wraps an async function to measure its execution time
12 */
13export async function withTiming<T>(
14 fn: () => Promise<T>,
15): Promise<[T, number]> {
26
27// Load all usernames and project paths into memory for fast typeahead
28export async function loadTypeaheadDataIntoMemory(): Promise<void> {
29 console.log("Loading typeahead data into memory...");
30
60 * Search typeahead data by prefix
61 */
62export function searchTypeahead(query: string, limit: number = 10): string[] {
63 const lowerQuery = query.toLowerCase();
64 const results: string[] = [];
77 * Get activity data for the last 6 months
78 */
79export async function getActivityHeatmap(): Promise<{
80 date: string;
81 count: number;
114 * Get top contributors based on recency
115 */
116export async function getTopContributors(limit: number = 10): Promise<{
117 username: string;
118 projectCount: number;
152 * Get most active projects based on recency and file count
153 */
154export async function getMostActiveProjects(limit: number = 10): Promise<{
155 name: string;
156 username: string;
192 * Get database statistics for the homepage
193 */
194export async function getSearchStats(): Promise<{
195 totalProjects: number;
196 totalFiles: number;
402};
403
404// Helper functions for project and file management
405
406/**
407 * Get a user by ID
408 */
409export async function getUser(userId: string): Promise<User | null> {
410 const result = await sqlite.execute(
411 `SELECT * FROM ${tablePrefix}_users WHERE id = ?`,
426 * Insert or update a user if it's newer than existing data
427 */
428export async function upsertUser(user: User): Promise<boolean> {
429 // Check if user exists and compare timestamps
430 const existingUser = await getUser(user.id);
469 * Get a project by ID
470 */
471async function getProject(projectId: string): Promise<Project | null> {
472 const result = await sqlite.execute(
473 `SELECT * FROM ${tablePrefix}_projects WHERE id = ?`,
488 * Insert or update a project if it's newer than existing data
489 */
490export async function upsertProject(project: Project): Promise<boolean> {
491 // Convert Date object to string if needed
492 const updatedAt = project.updated_at;
540 * Get a file by ID
541 */
542async function getFile(fileId: string): Promise<File | null> {
543 const result = await sqlite.execute(
544 `SELECT * FROM ${tablePrefix}_files WHERE id = ?`,
559 * Insert or update a file if it's newer than existing data
560 */
561export async function upsertFile(file: File): Promise<boolean> {
562 // Convert Date object to string if needed
563
608 * Extract matched lines with context around matches
609 */
610function extractMatchedLines(
611 content: string,
612 searchText: string,
668 * Search for files containing specific text
669 */
670export async function searchFileContent(
671 searchText: string,
672): Promise<FileSearchResult[]> {
716 * Count total file search results
717 */
718export async function countFileSearchResults(searchText: string): Promise<number> {
719 const searchPattern = `%${searchText}%`;
720
734 * Count total project search results
735 */
736export async function countProjectSearchResults(searchText: string): Promise<number> {
737 const searchPattern = `%${searchText}%`;
738
751 * Count total user search results
752 */
753export async function countUserSearchResults(searchText: string): Promise<number> {
754 const searchPattern = `%${searchText}%`;
755
768 * Search for projects matching the query
769 */
770export async function searchProjects(
771 searchText: string,
772 page: number = 1,
803 * Search for users matching the query
804 */
805export async function searchUsers(
806 searchText: string,
807 page: number = 1,
844 * Enhanced search that returns matched content with context and pagination
845 */
846export async function searchFileContentWithContext(
847 searchText: string,
848 contextLines: number = 2,

vtProjectSearch.cursorrules12 matches

@tallesjpโ€ขUpdated 3 days ago
4
5- Ask clarifying questions when requirements are ambiguous
6- Provide complete, functional solutions rather than skeleton implementations
7- Test your logic against edge cases before presenting the final solution
8- Ensure all code follows Val Town's specific platform requirements
17- **Never bake in secrets into the code** - always use environment variables
18- Include comments explaining complex logic (avoid commenting obvious operations)
19- Follow modern ES6+ conventions and functional programming practices if possible
20
21## Types of triggers
28
29```ts
30export default async function (req: Request) {
31 return new Response("Hello World");
32}
42
43```ts
44export default async function () {
45 // Scheduled task code
46}
56
57```ts
58export default async function (email: Email) {
59 // Process email
60}
66## Val Town Standard Libraries
67
68Val Town provides several hosted services and utility functions.
69
70### Blob Storage
120```
121
122## Val Town Utility Functions
123
124Val Town provides several utility functions to help with common project tasks.
125
126### Importing Utilities
200โ”‚ โ”œโ”€โ”€ database/
201โ”‚ โ”‚ โ”œโ”€โ”€ migrations.ts # Schema definitions
202โ”‚ โ”‚ โ”œโ”€โ”€ queries.ts # DB query functions
203โ”‚ โ”‚ โ””โ”€โ”€ README.md
204โ”‚ โ””โ”€โ”€ routes/ # Route modules
219โ””โ”€โ”€ shared/
220 โ”œโ”€โ”€ README.md
221 โ””โ”€โ”€ utils.ts # Shared types and functions
222```
223
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:
229 ```ts
230 import { readFile, serveFile } from "https://esm.town/v/std/utils@85-main/index.ts";
260- Run migrations on startup or comment out for performance
261- Change table names when modifying schemas rather than altering
262- Export clear query functions with proper TypeScript typing
263
264## Common Gotchas and Solutions

vtProjectSearchcomponents.tsx14 matches

@tallesjpโ€ขUpdated 3 days ago
17
18// Define the Activity Heatmap component
19export function ActivityHeatmap({ activityData }: { activityData: { date: string; count: number }[] }) {
20 // Convert activity data to a map for easier lookup
21 const activityMap = new Map(activityData.map(item => [item.date, item.count]));
157
158// Helper to highlight the search terms in the code
159export function highlightText(text: string, searchTerm: string): JSX.Element {
160 if (!searchTerm) return <>{text}</>;
161
178
179// CodeBlock component for displaying code with line numbers
180export function CodeBlock(
181 { matchedLines, searchTerm, totalMatches: _totalMatches }: {
182 matchedLines: EnhancedSearchResult["matchedLines"];
204
205// File search result component
206export function FileSearchResultComponent(
207 { result, searchTerm }: { result: EnhancedSearchResult; searchTerm: string },
208) {
282
283// Project search result component
284export function ProjectSearchResultComponent(
285 { result, searchTerm }: { result: ProjectSearchResult; searchTerm: string },
286) {
356
357// User search result component
358export function UserSearchResultComponent(
359 { result, searchTerm }: { result: UserSearchResult; searchTerm: string },
360) {
415
416// Sub-section result for docs
417export function SubDocResultComponent(
418 { result, _searchTerm }: { result: SubDocResult; _searchTerm: string },
419) {
436
437// Doc search result component
438export function DocSearchResultComponent(
439 { result, searchTerm }: { result: DocSearchResult; searchTerm: string },
440) {
491
492// Result count tabs component
493export function ResultTypeTabs({
494 totalFileResults,
495 totalProjectResults,
539
540// Pagination component
541export function Pagination({
542 currentPage,
543 totalPages,
644
645// Sample results component for preview of other result types
646export function SampleResultsSection({
647 title,
648 linkText,
681
682// Main search page component
683export function SearchPage({
684 fileResults,
685 projectResults,
1244 <a href="?q=database" className="example-link">database</a>
1245 <a href="?q=image" className="example-link">image</a>
1246 <a href="?q=function" className="example-link">function</a>
1247 <a href="?q=discord" className="example-link">discord</a>
1248 <a href="?q=openai" className="example-link">openai</a>
1399 <a href="?q=database" className="example-link">database</a>
1400 <a href="?q=image" className="example-link">image</a>
1401 <a href="?q=function" className="example-link">function</a>
1402 <a href="?q=discord" className="example-link">discord</a>
1403 <a href="?q=openai" className="example-link">openai</a>

vtProjectSearchclient.tsx12 matches

@tallesjpโ€ขUpdated 3 days ago
1// Client-side script for typeahead and keyboard navigation
2export const clientScript = `
3 document.addEventListener('DOMContentLoaded', function() {
4 const searchInput = document.getElementById('search-input');
5 const resultsContainer = document.getElementById('typeahead-results');
11 let selectedIndex = -1;
12
13 // Function to fetch typeahead results
14 async function fetchTypeahead(query) {
15 if (query.length < 1) {
16 hideResults();
61 }
62
63 // Function to display results
64 function displayResults(results, query) {
65 // Clear previous results
66 resultsContainer.innerHTML = '';
102 }
103
104 // Function to hide results
105 function hideResults() {
106 resultsContainer.classList.remove('active');
107 selectedIndex = -1;
109
110 // Input event to trigger typeahead
111 searchInput.addEventListener('input', function() {
112 const query = this.value.trim();
113
135
136 // Handle keyboard navigation
137 searchInput.addEventListener('keydown', function(e) {
138 const items = resultsContainer.querySelectorAll('.typeahead-item');
139
167
168 // Update selection highlight
169 function updateSelection(items) {
170 items.forEach((item, i) => {
171 if (i === selectedIndex) {
178
179 // Close results when clicking outside
180 document.addEventListener('click', function(e) {
181 if (!searchInput.contains(e.target) && !resultsContainer.contains(e.target)) {
182 hideResults();
185
186 // Handle mouse movement to keep the search term item highlighted
187 resultsContainer.addEventListener('mouseover', function(e) {
188 // Find the search term item (last child)
189 const searchItem = resultsContainer.querySelector('.search-term');

vtProjectSearchapi.tsx2 matches

@tallesjpโ€ขUpdated 3 days ago
14
15// Handle typeahead API requests
16export function handleTypeahead(req: Request): Response {
17 const url = new URL(req.url);
18 const searchTerm = url.searchParams.get("q") || "";
46
47// Main request handler
48export async function handler(req: Request): Promise<Response> {
49 const url = new URL(req.url);
50

web-appindex.http.tsx1 match

@saolsenโ€ขUpdated 3 days ago
128});
129
130export default async function (req: Request): Promise<Response> {
131 return await app.fetch(req);
132}

untitled-1131hume-auth.ts1 match

@twitchardโ€ขUpdated 3 days ago
6 */
7
8export default async function(req: Request): Promise<Response> {
9 try {
10 // Get API key and Secret key from environment variables

getFileEmail4 file matches

@shouserโ€ขUpdated 3 weeks ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblkโ€ขUpdated 3 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.