// src/views.ts — HTML views: built-in templating, content-type map, and boot-time builders. // fs/path are lazy-required inside functions so the barrel stays edge-loadable (workerd has no filesystem). /** Escape the five HTML-significant characters so interpolated data can't inject markup. */ export function escapeHtml(s: string): string { const map: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; return s.replace(/[&<>"']/g, (c) => map[c]); } function stringify(v: unknown): string { return v === null || v === undefined ? '' : String(v); } /** * Minimal built-in template engine: `{{ key }}` interpolates HTML-escaped, `{{{ key }}}` raw, * `{{ a.b }}` walks nested keys, a missing key renders empty. No loops/conditionals/partials. */ export function render(source: string, data: unknown): string { const lookup = (key: string): unknown => key.split('.').reduce((obj, k) => (obj === null || obj === undefined ? undefined : obj[k]), data); return source .replace(/\{\{\{\s*([\w.]+)\s*\}\}\}/g, (_, key) => stringify(lookup(key))) .replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => escapeHtml(stringify(lookup(key)))); } const CONTENT_TYPES: Record = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', }; /** Content-type for a file extension (case-insensitive, leading dot); unknown → `application/octet-stream`. */ export function contentTypeFor(ext: string): string { return CONTENT_TYPES[ext.toLowerCase()] ?? 'application/octet-stream'; }