/** Largest request body we accept (a settings patch is tiny). */ export const MAX_BODY_BYTES = 64 * 1024; /** Optional diagnostics hook for failed route responses (set by the kernel). */ let routeErrorHook; export function setRouteErrorHook(hook) { routeErrorHook = hook; } /** Collect a request body as UTF-8 text. */ export async function readBody(req, maxBytes = MAX_BODY_BYTES) { const chunks = []; let bytes = 0; for await (const chunk of req) { const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); bytes += buffer.byteLength; if (bytes > maxBytes) throw new Error('request-too-large'); chunks.push(buffer); } return Buffer.concat(chunks).toString('utf8'); } /** Reject cross-origin browser writes. */ export function sameOrigin(req) { const origin = req.headers.origin; const host = req.headers.host; if (origin === undefined || host === undefined) return true; return origin === `http://${host}` || origin === `https://${host}`; } /** Emit one JSON response with no caching. */ export function json(res, status, body) { const text = JSON.stringify(body); res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'content-length': Buffer.byteLength(text), }); res.end(text); } /** Emit a plain-text error (page route) or JSON error (API routes). */ export function fail(res, status, message, asHtml = false) { try { routeErrorHook?.('route.error', { status, error: message, html: asHtml }); } catch { /* diagnostics must never change the response */ } const text = asHtml ? `