@westacks/vortex
Version:
Server-based routing for SPAs
48 lines (47 loc) • 1.68 kB
JavaScript
import { createServer as p } from "node:http";
import { argv as c, stdout as u, exit as l } from "node:process";
import { p as s } from "./page-DkBioJVC.js";
function y(e, t = 13714) {
return c.length >= 3 ? d(e) : m(e, t);
}
const w = (e) => new Promise((t, o) => {
let n = "";
e.on("data", (r) => n += r), e.on("end", () => t(n + `
`)), e.on("error", o);
});
async function d(e) {
try {
const t = JSON.parse(c[2] ?? "null");
t && s.set(t), u.write(JSON.stringify(await e(s.get())) + `
`);
} catch (t) {
const o = new Error("Unable to parse page data", { cause: t });
console.error(o), l(1);
}
}
async function m(e, t = 13714) {
const o = {
"/up": () => ({ status: "OK", timestamp: Date.now() }),
"/down": () => l(),
"/render": async (n) => {
const r = performance.now(), i = JSON.parse(await w(n) ?? "null");
s.set(i);
const a = await e(s.get());
return console.log(`[VORTEX] Rendered page '${i?.url}' in ${performance.now() - r} ms`), a;
},
"*": () => ({ status: "NOT_FOUND", timestamp: Date.now() })
};
return console.log(`[VORTEX] Starting server on port ${t}...`), p(async (n, r) => {
const i = o[n.url ?? ""] || o["*"];
try {
const a = await i(n);
r.writeHead(200, { "Content-Type": "application/json", Server: "Vortex" }), r.write(JSON.stringify(a));
} catch (a) {
r.writeHead(500, { "Content-Type": "application/json", Server: "Vortex" }), r.end(JSON.stringify({ status: "ERROR", timestamp: Date.now(), error: a })), console.error(a);
}
r.end();
}).listen(t, () => console.log(`[VORTEX] Listening on port ${t}`));
}
export {
y as createVortexServer
};