/** * pageValidator.ts — Lightweight page validation for LLM-generated HTML. * * Catches common errors (syntax, missing DOM elements, bad synthos.* calls) * before serving pages. No browser binary — static analysis only. * * Layers: * 1. Script extraction + Acorn parse → syntax errors * 2. DOM element ID inventory → missing element references * 3. SynthOS API pattern checks → hallucinated method calls */ import * as acorn from 'acorn'; import * as cheerio from 'cheerio'; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export interface PageValidationError { type: 'syntax-error' | 'missing-element' | 'unknown-api'; message: string; source?: string; // 'inline-script-N' line?: number; col?: number; } export interface PageValidationResult { valid: boolean; errors: PageValidationError[]; durationMs: number; } interface ScriptBlock { index: number; source: string; startLine: number; isModule: boolean; } // --------------------------------------------------------------------------- // Known injected script IDs — skip these during validation // --------------------------------------------------------------------------- const INJECTED_SCRIPT_IDS = new Set([ 'page-bridge', // legacy (replaced by shell-v3) 'page-helpers', // legacy (replaced by v3 modules) 'page-info', 'page-script', // legacy shell script 'synthos-error-capture', // legacy error capture // V3 module scripts 'shell-v3', 'server-v3', 'storage-v3', 'script-v3', 'connector-v3', 'agent-v3', ]); // --------------------------------------------------------------------------- // Known SynthOS API surface (from helpers.v3.js) // --------------------------------------------------------------------------- const KNOWN_SYNTHOS_METHODS = new Set([ // data 'synthos.data', 'synthos.data.list', 'synthos.data.get', 'synthos.data.save', 'synthos.data.remove', // files 'synthos.files', 'synthos.files.list', 'synthos.files.upload', 'synthos.files.url', 'synthos.files.remove', // shared.data 'synthos.shared', 'synthos.shared.data', 'synthos.shared.data.list', 'synthos.shared.data.get', 'synthos.shared.data.save', 'synthos.shared.data.remove', // shared.files 'synthos.shared.files', 'synthos.shared.files.list', 'synthos.shared.files.upload', 'synthos.shared.files.url', 'synthos.shared.files.remove', // generate 'synthos.generate', 'synthos.generate.image', 'synthos.generate.completion', // script 'synthos.script', 'synthos.script.run', // page 'synthos.page', 'synthos.page.list', 'synthos.page.get', 'synthos.page.update', 'synthos.page.remove', 'synthos.page.ask', // search 'synthos.search', 'synthos.search.web', // connector 'synthos.connector', 'synthos.connector.call', 'synthos.connector.list', // agent 'synthos.agent', 'synthos.agent.list', 'synthos.agent.send', 'synthos.agent.sendStream', 'synthos.agent.chat', 'synthos.agent.chat.send', 'synthos.agent.chat.sendStream', 'synthos.agent.chat.history', 'synthos.agent.chat.abort', 'synthos.agent.chat.clear', 'synthos.agent.isEnabled', 'synthos.agent.getCapabilities', // shell 'synthos.shell', 'synthos.shell.navigate', 'synthos.shell.submitChat', 'synthos.shell.setDirty', 'synthos.shell.showLoading', 'synthos.shell.hideLoading', 'synthos.shell.focusChat', 'synthos.shell.openSaveModal', 'synthos.shell.toggleBuilder', 'synthos.shell.openBuilder', 'synthos.shell.closeBuilder', 'synthos.shell.on', ]); // --------------------------------------------------------------------------- // Layer 1: Script Extraction + Acorn Parse // --------------------------------------------------------------------------- function estimateLineOffset(html: string, scriptHtml: string): number { const idx = html.indexOf(scriptHtml); if (idx === -1) return 0; let line = 1; for (let i = 0; i < idx; i++) { if (html[i] === '\n') line++; } return line; } function extractScripts(html: string): ScriptBlock[] { const $ = cheerio.load(html); const scripts: ScriptBlock[] = []; let index = 0; $('script').each((_, el) => { const $el = $(el); // Skip external scripts (have src attribute) if ($el.attr('src')) return; // Skip known injected scripts const id = $el.attr('id'); if (id && INJECTED_SCRIPT_IDS.has(id)) return; const source = $el.text(); if (!source.trim()) return; scripts.push({ index: index++, source, startLine: estimateLineOffset(html, $.html(el)!), isModule: $el.attr('type') === 'module', }); }); return scripts; } function parseSyntax(script: ScriptBlock): PageValidationError | null { try { acorn.parse(script.source, { ecmaVersion: 'latest' as any, sourceType: script.isModule ? 'module' : 'script', allowAwaitOutsideFunction: true, }); return null; } catch (err: unknown) { const e = err as { message?: string; loc?: { line: number; column: number } }; return { type: 'syntax-error', message: e.message ?? 'Unknown syntax error', source: `inline-script-${script.index}`, line: e.loc ? script.startLine + e.loc.line : undefined, col: e.loc?.column, }; } } // --------------------------------------------------------------------------- // Layer 2: DOM Element ID Inventory // --------------------------------------------------------------------------- function buildIdInventory(html: string): Set { const $ = cheerio.load(html); const ids = new Set(); $('[id]').each((_, el) => { const id = $(el).attr('id'); if (id) ids.add(id); }); return ids; } /** * Patterns that CREATE element IDs inside script source text. Scripts that * build DOM via `innerHTML = \`......\`` or assign * `el.id = 'foo'` produce IDs at runtime that `buildIdInventory` misses. * Seeding those IDs as "known" prevents false-positive missing-element * errors for dynamically constructed UI. */ const ID_CREATE_PATTERNS = [ // id="foo" / id='foo' in string literals (innerHTML templates, etc.) /\bid\s*=\s*["']([a-zA-Z_][\w-]*)["']/g, // el.id = 'foo' / obj.id = "foo" /\.id\s*=\s*["']([a-zA-Z_][\w-]*)["']/g, ]; function collectDynamicIds(scripts: ScriptBlock[]): Set { const ids = new Set(); for (const script of scripts) { for (const pattern of ID_CREATE_PATTERNS) { pattern.lastIndex = 0; let match; while ((match = pattern.exec(script.source)) !== null) { ids.add(match[1]); } } } return ids; } /** Patterns that reference element IDs in JS code. */ const ID_REF_PATTERNS = [ /getElementById\(\s*['"]([^'"]+)['"]\s*\)/g, /querySelector(?:All)?\(\s*['"]#([^'"]+)['"]\s*\)/g, /\$\(\s*['"]#([^'"]+)['"]\s*\)/g, ]; function checkIdReferences(scripts: ScriptBlock[], ids: Set): PageValidationError[] { const errors: PageValidationError[] = []; for (const script of scripts) { for (const pattern of ID_REF_PATTERNS) { pattern.lastIndex = 0; let match; while ((match = pattern.exec(script.source)) !== null) { const refId = match[1]; if (!ids.has(refId)) { errors.push({ type: 'missing-element', message: `Script references element '#${refId}' which does not exist in the page`, source: `inline-script-${script.index}`, }); } } } } return errors; } // --------------------------------------------------------------------------- // Layer 3: SynthOS API Pattern Checks // --------------------------------------------------------------------------- const SYNTHOS_CALL_PATTERN = /synthos(?:\.[\w]+)+/g; function checkSynthosApi(scripts: ScriptBlock[]): PageValidationError[] { const errors: PageValidationError[] = []; const seen = new Set(); for (const script of scripts) { SYNTHOS_CALL_PATTERN.lastIndex = 0; let match; while ((match = SYNTHOS_CALL_PATTERN.exec(script.source)) !== null) { const call = match[0]; // Deduplicate within a single validation run if (seen.has(call)) continue; if (!KNOWN_SYNTHOS_METHODS.has(call)) { seen.add(call); errors.push({ type: 'unknown-api', message: `Unknown SynthOS API call: ${call}`, source: `inline-script-${script.index}`, }); } } } return errors; } // --------------------------------------------------------------------------- // Public API // --------------------------------------------------------------------------- export function validatePage(html: string): PageValidationResult { const start = Date.now(); const errors: PageValidationError[] = []; // Layer 1: Extract and parse scripts const scripts = extractScripts(html); for (const script of scripts) { const err = parseSyntax(script); if (err) errors.push(err); } // Layer 2: DOM ID reference checks (only if no syntax errors) if (errors.length === 0) { const ids = buildIdInventory(html); const dynamicIds = collectDynamicIds(scripts); for (const id of dynamicIds) ids.add(id); errors.push(...checkIdReferences(scripts, ids)); } // Layer 3: SynthOS API pattern checks (always runs) errors.push(...checkSynthosApi(scripts)); return { valid: errors.length === 0, errors, durationMs: Date.now() - start, }; }