// Маленький роутер и помощники ответа. Маршрут: { method, path: "/api/items/:id", handler(ctx) }. // ctx = { req, res, params, query, body() }. export function match(pattern, pathname) { const a = pattern.split("/").filter(Boolean); const b = pathname.split("/").filter(Boolean); if (a.length !== b.length) return null; const params = {}; for (let i = 0; i < a.length; i++) { if (a[i].startsWith(":")) params[a[i].slice(1)] = decodeURIComponent(b[i]); else if (a[i] !== b[i]) return null; } return params; } export async function handle(routes, req, res) { const url = new URL(req.url ?? "/", "http://local"); for (const r of routes) { if (r.method !== req.method) continue; const params = match(r.path, url.pathname); if (!params) continue; await r.handler({ req, res, params, query: Object.fromEntries(url.searchParams), body: () => readBody(req) }); return; } html(res, page("Страница не найдена", "

Страница не найдена

"), 404); } export async function readBody(req) { const chunks = []; for await (const c of req) chunks.push(c); const raw = Buffer.concat(chunks).toString("utf8"); if (!raw) return {}; const type = String(req.headers["content-type"] ?? ""); if (type.includes("application/x-www-form-urlencoded")) return Object.fromEntries(new URLSearchParams(raw)); try { return JSON.parse(raw); } catch { return {}; } } export function json(res, status, body) { res.writeHead(status, { "content-type": "application/json; charset=utf-8" }); res.end(JSON.stringify(body)); } export function html(res, body, status = 200) { res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }); res.end(body); } export function esc(s) { return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); } export function page(title, body) { return ` ${esc(title)} ${body} `; }