import { createServer } from "node:http"; import { readFile } from "node:fs/promises"; import { join } from "node:path"; import { renderLanding } from "./landing.js"; import { legalPage } from "./legal.js"; import { renderCatalog } from "./templates/page.js"; import { findTemplate, fileName } from "./templates/catalog.js"; const TYPES = { xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", }; const send = (res, code, type, body) => { res.writeHead(code, { "content-type": `${type}; charset=utf-8` }); res.end(body); }; export function createApp(config) { return createServer(async (req, res) => { const url = new URL(req.url, "http://x"); const path = url.pathname; try { if (path === "/healthz") return send(res, 200, "text/plain", "ok"); if (path === "/") return send(res, 200, "text/html", renderLanding(config, "ru")); if (path === "/en") return send(res, 200, "text/html", renderLanding(config, "en")); if (path === "/templates") return send(res, 200, "text/html", renderCatalog(Object.fromEntries(url.searchParams))); const tpl = /^\/templates\/([a-z0-9-]+)\.(xlsx|docx)$/.exec(path); const t = tpl && findTemplate(tpl[1]); if (t && t.format === tpl[2]) { const body = await readFile(join(config.productDir, "templates", fileName(t))); res.writeHead(200, { "content-type": TYPES[t.format], "content-disposition": `attachment; filename="${fileName(t)}"` }); return res.end(body); } const img = /^\/img\/([\w-]+\.svg)$/.exec(path); if (img) return send(res, 200, "image/svg+xml", await readFile(join(config.publicDir, "img", img[1]))); const doc = /^\/(offer|refund)$/.exec(path); if (doc) { const html = await legalPage(config, doc[1]); if (html) return send(res, 200, "text/html", html); } } catch (e) { if (e.code !== "ENOENT") console.error(e); } send(res, 404, "text/plain", "Не найдено"); }); }