Open History to see the last commit
1export interface ValidationResult {
2 valid: boolean
3 error?: string
4 strippedCode?: string
5}
6
7export async function validateHandler(
8 handlerCode: string,
9 _bindingTypeDefinitions: string,
10 allowedBindings: Set<string>,
11): Promise<ValidationResult> {
12 const validationError = validateBindingUsage(handlerCode, allowedBindings)
13 if (validationError) {
14 return { valid: false, error: validationError }
15 }
16
17 // Basic syntax validation - check for common issues
18 // Full TypeScript validation would require esbuild, but it has issues
19 // in Vite's SSR environment. The code will be validated again at runtime
20 // in the isolate which will catch any actual errors.
21 const syntaxChecks = [
22 { pattern: /^\s*$/, error: 'Handler code cannot be empty' },
23 {
24 pattern: /import\s+/,
25 error: 'import statements are not allowed in handlers',
26 },
27 {
28 pattern: /export\s+/,
29 error: 'export statements are not allowed in handlers',
30 },
31 ]
32
33 for (const check of syntaxChecks) {
34 if (check.pattern.test(handlerCode)) {
35 return { valid: false, error: check.error }
36 }
37 }
38
39 // Return the handler code as-is (no TypeScript stripping needed for runtime)
40 return { valid: true, strippedCode: handlerCode }
41}
42
43function validateBindingUsage(
44 handlerCode: string,
45 allowedBindings: Set<string>,
46): string | null {
47 const matches = handlerCode.match(/\bexternal_[A-Za-z0-9_]+\b/g) || []
48 const unknown = matches.filter((name) => !allowedBindings.has(name))
49 if (unknown.length === 0) return null
50
51 const unique = Array.from(new Set(unknown))
52 return `Unknown bindings used: ${unique.join(', ')}`
53}