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/$1?q=function&page=5&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 23725 results for "function"(807ms)

tourguideApp.tsx1 match

@neverstew•Updated 5 hours ago
17}
18
19export default function App() {
20 const [state, setState] = useState<AppState>({
21 view: 'search',

tourguidesw.js1 match

@neverstew•Updated 5 hours ago
122});
123
124async function syncData() {
125 // Get pending data from IndexedDB and sync when online
126 console.log('Background sync triggered');

tourguideitinerary.ts1 match

@neverstew•Updated 5 hours ago
14const openai = new OpenAI();
15
16function generateId(): string {
17 return Math.random().toString(36).substring(2) + Date.now().toString(36);
18}

tourguidequeries.ts6 matches

@neverstew•Updated 5 hours ago
3import type { Itinerary, TourProgress } from "../../shared/types.ts";
4
5export async function saveItinerary(itinerary: Itinerary): Promise<void> {
6 await sqlite.execute(`
7 INSERT INTO ${ITINERARIES_TABLE} (
25}
26
27export async function getItinerary(id: string): Promise<Itinerary | null> {
28 const result = await sqlite.execute(`
29 SELECT * FROM ${ITINERARIES_TABLE} WHERE id = ?
49}
50
51export async function getAllItineraries(): Promise<Itinerary[]> {
52 const result = await sqlite.execute(`
53 SELECT * FROM ${ITINERARIES_TABLE} ORDER BY created_at DESC
70}
71
72export async function deleteItinerary(id: string): Promise<boolean> {
73 const result = await sqlite.execute(`
74 DELETE FROM ${ITINERARIES_TABLE} WHERE id = ?
78}
79
80export async function saveTourProgress(progress: TourProgress): Promise<void> {
81 await sqlite.execute(`
82 INSERT OR REPLACE INTO ${TOUR_PROGRESS_TABLE} (
93}
94
95export async function getTourProgress(itineraryId: string): Promise<TourProgress | null> {
96 const result = await sqlite.execute(`
97 SELECT * FROM ${TOUR_PROGRESS_TABLE} WHERE itinerary_id = ?

tourguidemigrations.ts1 match

@neverstew•Updated 5 hours ago
4const TOUR_PROGRESS_TABLE = 'tour_guide_progress_v1';
5
6export async function runMigrations() {
7 // Create itineraries table
8 await sqlite.execute(`

charmaineValSearchdb.ts25 matches

@charmaine•Updated 6 hours 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,
1049 * Get most recently edited vals (files) within a time period for newsletter curation
1050 */
1051export async function getMostEditedVals(
1052 daysBack: number = 30,
1053 limit: number = 50
1113 * Activity is measured by number of distinct edit sessions, not total file changes
1114 */
1115export async function getMostActiveProjectsForNewsletter(
1116 daysBack: number = 30,
1117 limit: number = 50

charmaineValSearchcomponents.tsx25 matches

@charmaine•Updated 6 hours ago
19
20// Define the Activity Heatmap component
21export function ActivityHeatmap({ activityData }: { activityData: { date: string; count: number }[] }) {
22 // Convert activity data to a map for easier lookup
23 const activityMap = new Map(activityData.map(item => [item.date, item.count]));
159
160// Helper to highlight the search terms in the code
161export function highlightText(text: string, searchTerm: string): JSX.Element {
162 if (!searchTerm) return <>{text}</>;
163
180
181// CodeBlock component for displaying code with line numbers
182export function CodeBlock(
183 { matchedLines, searchTerm, totalMatches: _totalMatches }: {
184 matchedLines: EnhancedSearchResult["matchedLines"];
206
207// File search result component
208export function FileSearchResultComponent(
209 { result, searchTerm }: { result: EnhancedSearchResult; searchTerm: string },
210) {
270
271// Project search result component
272export function ProjectSearchResultComponent(
273 { result, searchTerm }: { result: ProjectSearchResult; searchTerm: string },
274) {
336
337// User search result component
338export function UserSearchResultComponent(
339 { result, searchTerm }: { result: UserSearchResult; searchTerm: string },
340) {
395
396// Sub-section result for docs
397export function SubDocResultComponent(
398 { result, _searchTerm }: { result: SubDocResult; _searchTerm: string },
399) {
416
417// Doc search result component
418export function DocSearchResultComponent(
419 { result, searchTerm }: { result: DocSearchResult; searchTerm: string },
420) {
471
472// Result count tabs component
473export function ResultTypeTabs({
474 totalFileResults,
475 totalProjectResults,
519
520// Pagination component
521export function Pagination({
522 currentPage,
523 totalPages,
624
625// Sample results component for preview of other result types
626export function SampleResultsSection({
627 title,
628 linkText,
661
662// Main search page component
663export function SearchPage({
664 fileResults,
665 projectResults,
1225 <a href="?q=database" className="example-link">database</a>
1226 <a href="?q=image" className="example-link">image</a>
1227 <a href="?q=function" className="example-link">function</a>
1228 <a href="?q=discord" className="example-link">discord</a>
1229 <a href="?q=openai" className="example-link">openai</a>
1379 <a href="?q=database" className="example-link">database</a>
1380 <a href="?q=image" className="example-link">image</a>
1381 <a href="?q=function" className="example-link">function</a>
1382 <a href="?q=discord" className="example-link">discord</a>
1383 <a href="?q=openai" className="example-link">openai</a>
1397
1398// Newsletter curation components
1399export function EditedValCard({ val }: {
1400 val: EditedValResult;
1401}) {
1448}
1449
1450export function NewsletterProjectCard({ project }: {
1451 project: NewsletterProjectResult;
1452}) {
1500}
1501
1502export function NewsletterCurationPage({
1503 activeProjects,
1504 daysBack,
2096 const SELECTED_PROJECTS_KEY = 'newsletter_selected_projects';
2097
2098 function getSelectedProjects() {
2099 try {
2100 return JSON.parse(localStorage.getItem(SELECTED_PROJECTS_KEY) || '[]');
2104 }
2105
2106 function setSelectedProjects(projects) {
2107 localStorage.setItem(SELECTED_PROJECTS_KEY, JSON.stringify(projects));
2108 }
2109
2110 function toggleSelectedProject(id) {
2111 const selected = getSelectedProjects();
2112 const index = selected.indexOf(id);
2122 }
2123
2124 function selectAllOnPage() {
2125 const projectButtons = document.querySelectorAll('.corner-select');
2126 const selected = getSelectedProjects();
2137 }
2138
2139 function clearSelection() {
2140 setSelectedProjects([]);
2141 updateSelectedUI();
2142 }
2143
2144 function exportSelectedToMarkdown() {
2145 const selected = getSelectedProjects();
2146 if (selected.length === 0) return;
2201 }
2202
2203 function updateSelectedUI() {
2204 const selectedProjects = getSelectedProjects();
2205
2234
2235 // Initialize on page load
2236 document.addEventListener('DOMContentLoaded', function() {
2237 // Add click handlers to select buttons
2238 document.querySelectorAll('.corner-select').forEach(button => {

charmaineValSearchclient.tsx12 matches

@charmaine•Updated 6 hours 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');

charmaineValSearchapi.tsx3 matches

@charmaine•Updated 6 hours ago
15
16// Handle typeahead API requests
17export function handleTypeahead(req: Request): Response {
18 const url = new URL(req.url);
19 const searchTerm = url.searchParams.get("q") || "";
47
48// Newsletter curation route
49export async function handleNewsletterCuration(req: Request): Promise<Response> {
50 const url = new URL(req.url);
51 const daysParam = url.searchParams.get("days") || "30";
115
116// Main request handler
117export async function handler(req: Request): Promise<Response> {
118 const url = new URL(req.url);
119

LoopsNewsletterFormform.ts1 match

@valdottown•Updated 6 hours ago
1import { serveFile } from "https://esm.town/v/std/utils@85-main/index.ts";
2
3export default async function(req: Request): Promise<Response> {
4 // serve public files at the root
5 const url = new URL(req.url);

getFileEmail4 file matches

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

tuna8 file matches

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