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/$%7BsvgDataUrl%7D?q=function&page=22&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 30747 results for "function"(2335ms)

api_ianmenethil_comauthInternal.ts2 matches

@ianmenethil•Updated 18 hours ago
5import { internalJwtService } from "@/services/internalJWTService.ts"; // Adjust path if necessary
6
7export function createInternalAuthMiddleware() {
8 const internalJwtConfig = AUTH_CONFIG.jwt.INTERNAL;
9 if (!internalJwtConfig.enabled) {
75}
76
77export function requireInternalAuth(requiredScope?: string) {
78 return async (c: Context<{ Variables: HonoVariables }>, next: Next): Promise<Response | void> => {
79 const internalContext = c.get("internalAuth");

api_ianmenethil_comauthentication.ts11 matches

@ianmenethil•Updated 18 hours ago
32 * Apply authentication based on method
33 */
34async function applyAuthMethod(
35 method: AuthMethod,
36 c: Context<{ Variables: HonoVariables }>,
94 * Multi-method authentication middleware
95 */
96export function createAuthMiddleware(options: AuthMiddlewareOptions = {}) {
97 const defaultAuthTypes: AuthMethod[] = [
98 AUTH_CONFIG.jwt.API.enabled && "jwt",
234
235/**
236 * Helper functions
237 */
238export function getAuthContext(c: Context<{ Variables: HonoVariables }>): AuthContext | undefined {
239 return c.get("auth");
240}
241
242export function isAuthenticated(c: Context<{ Variables: HonoVariables }>): boolean {
243 return !!c.get("auth");
244}
245
246export function getCurrentUserId(c: Context<{ Variables: HonoVariables }>): string | undefined {
247 const auth = c.get("auth");
248 return auth?.userId || auth?.user;
249}
250
251export function getCurrentUserEmail(c: Context<{ Variables: HonoVariables }>): string | undefined {
252 const auth = c.get("auth");
253 return auth?.email;
254}
255
256export function hasScope(c: Context<{ Variables: HonoVariables }>, scope: string): boolean {
257 const auth = c.get("auth");
258 return auth?.scopes?.includes(scope) || false;
259}
260
261export function hasPermission(
262 c: Context<{ Variables: HonoVariables }>,
263 permission: string,
267}
268
269export function getAuthMethod(c: Context<{ Variables: HonoVariables }>): AuthMethod | undefined {
270 const auth = c.get("auth");
271 return auth?.type;
273
274/**
275 * Shorthand functions for specific auth requirements
276 */
277export const requireJWT = createAuthMiddleware({ methods: ["jwt"] });

api_ianmenethil_comauthBasic.ts3 matches

@ianmenethil•Updated 18 hours ago
50 * Basic Auth authentication logic for the authentication orchestrator
51 */
52export async function applyBasicAuth(
53 c: Context<{ Variables: HonoVariables }>,
54): Promise<AuthResult> {
171 * Basic Auth authentication middleware for the orchestrator
172 */
173export async function basicAuthMiddleware(
174 c: Context<{ Variables: HonoVariables }>,
175 next: () => Promise<void>,
413
414/**
415 * Utility function to hash passwords using bcrypt
416 */
417export const hashPassword = async (password: string, saltRounds = 12): Promise<string> => {

api_ianmenethil_comauthApiKey.ts6 matches

@ianmenethil•Updated 18 hours ago
15 * Validates API key against configured valid keys
16 */
17export function validateApiKey(apiKey: string): boolean {
18 if (!apiKey) return false;
19
27 * Validates internal API key for server-to-server communication
28 */
29export function validateInternalApiKey(apiKey: string): boolean {
30 return apiKey === AUTH_CONFIG.methods.API_KEY.keys.internal;
31}
34 * Validates webhook secret for webhook authentication
35 */
36export function validateWebhookSecret(secret: string): boolean {
37 return secret === AUTH_CONFIG.methods.API_KEY.keys.webhook;
38}
41 * Validates service-to-service API key
42 */
43export function validateServiceKey(serviceKey: string): boolean {
44 return serviceKey === AUTH_CONFIG.methods.API_KEY.keys.serviceToService;
45}
48 * API Key authentication middleware
49 */
50export async function apiKeyAuthMiddleware(
51 c: Context<{ Variables: Variables }>,
52 next: () => Promise<void>,
80 * API Key authentication logic
81 */
82export function applyApiKeyAuth(request: Request): AuthResult {
83 const apiKeyConfig = AUTH_CONFIG.methods.API_KEY;
84

api_ianmenethil_comauth.jwt.ts9 matches

@ianmenethil•Updated 18 hours ago
1/**
2 * JWT authentication middleware for Hono-based API server.
3 * Provides JWT token creation, verification, and middleware functions.
4 */
5
21 * @returns A string representation of the error message
22 */
23function getErrorMessage(error: unknown): string {
24 if (error instanceof Error) {
25 return error.message;
40 * const token = await createJWT({ sub: 'user123', email: 'user@example.com' });
41 */
42export async function createJWT(payload: AppJwtPayload): Promise<string> {
43 try {
44 const { iat: _iat, exp: _exp, ...restPayload } = payload;
67 * @returns Promise resolving to decoded payload or null if invalid
68 */
69export async function verifyAppJWT(
70 token: string,
71 customSecret?: string,
106 * @returns Promise resolving to authentication result
107 */
108export async function applyJwtAuth(
109 request: Request,
110 customSecret?: string,
199 * JWT Bearer token authentication middleware
200 */
201export async function jwtAuthMiddleware(
202 c: Context<{ Variables: HonoVariables }>,
203 next: Next,
230 * JWT-only middleware for endpoints that strictly require JWT authentication
231 */
232export function jwtOnlyMiddleware(customSecret?: string) {
233 return async (c: Context<{ Variables: HonoVariables }>, next: Next): Promise<Response | void> => {
234 const authResult = await applyJwtAuth(c.req.raw, customSecret);
260 * Creates a refresh token with extended expiry
261 */
262export async function createRefreshToken(payload: AppJwtPayload): Promise<string> {
263 try {
264 const { iat: _iat, exp: _exp, ...restPayload } = payload;
291 * @returns Promise resolving to new token pair or null if invalid
292 */
293export async function refreshAccessToken(
294 refreshTokenValue: string,
295): Promise<{ accessToken: string; refreshToken: string } | null> {

api_ianmenethil_comsqlService.ts40 matches

@ianmenethil•Updated 18 hours ago
290 * ```
291 */
292function validateBearerToken(token: string): void {
293 if (typeof token !== "string" || token.trim().length === 0) {
294 throw new SqlServiceError(
311 * ```
312 */
313function validateSqlStatement(statement: SqlStatement): void {
314 if (typeof statement === "string") {
315 if (statement.trim().length === 0) {
351 * ```
352 */
353function createSqlHeaders(bearerToken: string): Record<string, string> {
354 return {
355 "Authorization": `Bearer ${bearerToken}`,
369 * ```
370 */
371function buildSqlUrl(endpoint: string): string {
372 return `${DEFAULT_SQL_CONFIG.baseUrl}/${DEFAULT_SQL_CONFIG.apiVersion}${endpoint}`;
373}
390 * ```
391 */
392async function makeSqlRequest(url: string, options: RequestInit): Promise<Response> {
393 let lastError: Error | null = null;
394
423 );
424} // ============================================================================
425// CORE SQL EXECUTION FUNCTIONS
426// ============================================================================
427
446 * ```
447 */
448export async function executeSql(
449 statement: SqlStatement,
450 options: SqlOperationOptions,
505 * ```
506 */
507export async function executeBatchSql(
508 statements: SqlStatement[],
509 options: BatchSqlOptions,
558 }
559} // ============================================================================
560// TABLE MANAGEMENT FUNCTIONS
561// ============================================================================
562
583 * ```
584 */
585export async function createTable(
586 schema: TableSchema,
587 options: SqlOperationOptions,
636 * ```
637 */
638export async function dropTable(
639 tableName: string,
640 options: SqlOperationOptions,
661 * ```
662 */
663export async function tableExists(
664 tableName: string,
665 options: SqlOperationOptions,
692 * ```
693 */
694export async function listTables(
695 options: SqlOperationOptions,
696): Promise<SqlOperationResult<string[]>> {
745 * ```
746 */
747export async function insertRecord(
748 tableName: string,
749 data: Record<string, TursoValue>,
790 * ```
791 */
792export async function insertMultipleRecords(
793 tableName: string,
794 records: Record<string, TursoValue>[],
854 * ```
855 */
856export async function selectRecords(
857 tableName: string,
858 options: SqlOperationOptions,
924 * ```
925 */
926export async function findRecordById(
927 tableName: string,
928 id: TursoValue,
956 * ```
957 */
958export async function updateRecords(
959 tableName: string,
960 data: Record<string, TursoValue>,
1018 * ```
1019 */
1020export async function deleteRecords(
1021 tableName: string,
1022 where: Record<string, TursoValue>,
1071 * ```
1072 */
1073export async function deleteRecordById(
1074 tableName: string,
1075 id: TursoValue,
1079 return await deleteRecords(tableName, { [idColumn]: id }, options);
1080} // ============================================================================
1081// INDEX MANAGEMENT FUNCTIONS
1082// ============================================================================
1083
1099 * ```
1100 */
1101export async function createIndex(
1102 indexDef: IndexDefinition,
1103 tableName: string,
1134 * ```
1135 */
1136export async function dropIndex(
1137 indexName: string,
1138 options: SqlOperationOptions,
1144 return await executeSql(sql, options);
1145} // ============================================================================
1146// UTILITY FUNCTIONS
1147// ============================================================================
1148
1164 * ```
1165 */
1166export async function countRecordsWithWhere(
1167 tableName: string,
1168 options: SqlOperationOptions,
1219 * ```
1220 */
1221export async function countRecords(
1222 tableName: string,
1223 options: SqlOperationOptions,
1285 * ```
1286 */
1287export async function executeQuery(
1288 sql: string,
1289 args: TursoValue[] = [],
1317 * ```
1318 */
1319export async function upsertRecord(
1320 tableName: string,
1321 data: Record<string, TursoValue>,
1356 }
1357} // ============================================================================
1358// ORM-STYLE UTILITY FUNCTIONS (From Legacy Version)
1359// ============================================================================
1360
1375 * ```
1376 */
1377export function buildWhereClause(conditions: WhereCondition): {
1378 whereClause: string;
1379 whereArgs: TursoValue[];
1433 * ```
1434 */
1435export function mapRowToObject(row: TursoRow, columns: string[]): Record<string, TursoValue> {
1436 const obj: Record<string, TursoValue> = {};
1437 for (let i = 0; i < columns.length; i++) {
1458 * ```
1459 */
1460export async function selectWithMapping(
1461 tableName: string,
1462 options: SqlOperationOptions,
1541 * ```
1542 */
1543export async function findOne(
1544 tableName: string,
1545 where: WhereCondition,
1581 * ```
1582 */
1583export async function findMany(
1584 tableName: string,
1585 options: SqlOperationOptions,
1612 * ```
1613 */
1614export async function recordExists(
1615 tableName: string,
1616 where: WhereCondition,
1647 * ```
1648 */
1649export async function getTableInfo(
1650 tableName: string,
1651 options: SqlOperationOptions,
1675 * ```
1676 */
1677export async function executeTransaction(
1678 operations: SqlStatement[],
1679 options: SqlOperationOptions,
2144export { ValTownSqlService as SqlService };
2145
2146// Export all functions (already exported individually above)
2147// This section serves as a convenient index of all available functions
2148
2149/**
2150 * Available SQL service functions:
2151 *
2152 * ## Core Execution

api_ianmenethil_comoauthDBService.ts3 matches

@ianmenethil•Updated 18 hours ago
112 updated_at?: number;
113} // ============================================================================
114// HELPER FUNCTIONS
115// ============================================================================
116
118 * Convert database user to SQL-compatible format.
119 */
120function userToSqlRecord(user: DatabaseUser): Record<string, string | number | null> {
121 return {
122 id: user.id,
135 * Convert OAuth account to SQL-compatible format.
136 */
137function oauthAccountToSqlRecord(
138 account: DatabaseOAuthAccount,
139): Record<string, string | number | null> {

api_ianmenethil_comemailService.ts11 matches

@ianmenethil•Updated 18 hours ago
191
192// ============================================================================
193// UTILITY FUNCTIONS
194// ============================================================================
195
198 * @returns ISO date string in Sydney timezone
199 */
200function getCurrentDateInSydney(): string {
201 return new Date().toLocaleString("en-AU", {
202 timeZone: "Australia/Sydney",
214 * @returns Basic configuration object
215 */
216function getConfig<T>(): T {
217 return {} as T;
218} // ============================================================================
219// HTTP UTILITY FUNCTIONS
220// ============================================================================
221
225 * @returns Headers object
226 */
227function createHeaders(bearerToken?: string): Record<string, string> {
228 const token = bearerToken || Deno.env.get("VALTOWN_TOKEN") || Deno.env.get("VALTOWN_API_KEY") ||
229 "";
242 * @returns Complete URL string
243 */
244function buildUrl(endpoint: string, baseUrl?: string): string {
245 const base = baseUrl || DEFAULT_EMAIL_CONFIG.baseUrl;
246 const cleanEndpoint = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
254 * @returns Promise resolving to Response
255 */
256async function makeRequest(url: string, options: RequestInit): Promise<Response> {
257 const controller = new AbortController();
258 const timeoutId = setTimeout(() => controller.abort(), DEFAULT_EMAIL_CONFIG.timeout);
274 }
275} // ============================================================================
276// CORE EMAIL FUNCTIONS
277// ============================================================================
278
294 * ```
295 */
296export async function sendEmail(
297 options: EmailOptions,
298): Promise<EmailOperationResult<{ message: string }>> {
366 */
367
368export function sendSimpleEmail(
369 to: string[],
370 subject: string,
1051// ============================================================================
1052
1053// Export all types and functions
1054export type {
1055 EmailAttachment,

api_ianmenethil_comblobService.ts19 matches

@ianmenethil•Updated 18 hours ago
141 * ```
142 */
143function validateBlobKey(key: string): void {
144 if (typeof key !== "string") {
145 throw new BlobServiceError("Blob key must be a string", STATUS_CODES.BAD_REQUEST);
172 */
173
174function validateBearerToken(token: string): void {
175 if (typeof token !== "string" || token.trim().length === 0) {
176 throw new BlobServiceError(
197 * ```
198 */
199function createHeaders(bearerToken?: string, contentType?: string): Record<string, string> {
200 const headers: Record<string, string> = {};
201
225 * ```
226 */
227function buildUrl(endpoint: string, key?: string, queryParams?: Record<string, string>): string {
228 const baseUrl = `${DEFAULT_BLOB_CONFIG.baseUrl}/${DEFAULT_BLOB_CONFIG.apiVersion}`;
229 let url = `${baseUrl}${endpoint}`;
264 */
265
266async function makeRequest(url: string, options: RequestInit): Promise<Response> {
267 let lastError: Error | null = null;
268
299
300// ============================================================================
301// CORE BLOB SERVICE FUNCTIONS
302// ============================================================================
303
318 * ```
319 */
320export async function listBlobs(
321 options: ListBlobsOptions = {},
322): Promise<BlobOperationResult<BlobListingItem[]>> {
371 */
372
373export async function downloadBlob(key: string): Promise<BlobOperationResult<ArrayBuffer>> {
374 try {
375 validateBlobKey(key);
422 * ```
423 */
424export async function downloadBlobAsText(
425 key: string,
426 encoding: string = "utf-8",
475 */
476
477export async function storeBlob(
478 key: string,
479 data: ArrayBuffer | Uint8Array | string,
543 * ```
544 */
545export async function storeBlobAsJson(
546 key: string,
547 data: unknown,
582 */
583
584export async function deleteBlob(
585 key: string,
586 options: AuthenticatedBlobOptions,
622
623// ============================================================================
624// UTILITY FUNCTIONS
625// ============================================================================
626
639 * ```
640 */
641export async function blobExists(key: string): Promise<boolean> {
642 try {
643 validateBlobKey(key);
668 */
669
670export async function getBlobMetadata(key: string): Promise<BlobListingItem | null> {
671 try {
672 const result = await listBlobs();
695 * ```
696 */
697export async function downloadBlobAsJson<T = unknown>(
698 key: string,
699): Promise<BlobOperationResult<T>> {
740 * ```
741 */
742export async function copyBlob(
743 sourceKey: string,
744 destinationKey: string,
788 */
789
790export async function bulkDeleteBlobsByPrefix(
791 prefix: string,
792 options: AuthenticatedBlobOptions,
1188}
1189
1190// Export all types and functions
1191export type {
1192 AuthenticatedBlobOptions,

api_ianmenethil_comwebhookService.ts7 matches

@ianmenethil•Updated 18 hours ago
23 * @returns Sanitized string
24 */
25function sanitizeInput(input: string): string {
26 return input.replace(/[<>\"'&]/g, "").trim();
27}
33 * @returns Parsed timestamp filter object
34 */
35function parseTimestampFilters(from?: string, to?: string): { from?: Date; to?: Date } {
36 const result: { from?: Date; to?: Date } = {};
37
58 * @returns Headers as key-value object
59 */
60function extractHeaders(request: Request): Record<string, string> {
61 const headers: Record<string, string> = {};
62 request.headers.forEach((value, key) => {
71 * @returns Response with webhook creation result
72 */
73export async function createWebhook(c: Context<{ Variables: Variables }>): Promise<Response> {
74 const requestId = crypto.randomUUID();
75
159 * @returns Response with webhook records list
160 */
161export async function listWebhooks(c: Context<{ Variables: Variables }>): Promise<Response> {
162 const requestId = crypto.randomUUID();
163
249 * @returns Response with webhook record details
250 */
251export async function getWebhook(c: Context<{ Variables: Variables }>): Promise<Response> {
252 const requestId = crypto.randomUUID();
253
316 * @returns Response with deletion confirmation
317 */
318export async function deleteWebhook(c: Context<{ Variables: Variables }>): Promise<Response> {
319 const requestId = crypto.randomUUID();
320
tuna

tuna9 file matches

@jxnblk•Updated 1 week ago
Simple functional CSS library for Val Town

getFileEmail4 file matches

@shouser•Updated 1 month ago
A helper function to build a file's email
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.