web: URL routes, deep links and history navigation (L6)

This commit is contained in:
2026-10-19 14:45:57 +01:00
parent bcc3835fba
commit 895ed9d8b7
8 changed files with 1669 additions and 60 deletions
+70 -3
View File
@@ -33,6 +33,24 @@ const MIME = {
".map": "application/json; charset=utf-8",
};
// A path is asset-looking when its last segment ends in a known file type, and a
// page route when its first segment names one of the client's destinations. A
// stage key may itself end in an extension (`plan.js`): under a page prefix the
// route still serves the shell, while an asset-looking path elsewhere (`/nope.js`)
// stays an honest 404 and a real file (`/src/app.js`) is still served.
const ASSET_EXTENSIONS = new Set([...Object.keys(MIME), ".woff", ".woff2", ".txt"]);
const PAGE_PREFIXES = new Set(["pipelines", "runs", "chat", "settings", "templates"]);
/** The decoded first path segment, or "" for the root. */
function firstSegment(pathname) {
const raw = pathname.split("/").filter(Boolean)[0] ?? "";
try {
return decodeURIComponent(raw);
} catch {
return raw;
}
}
function flag(argv, name, fallback) {
const i = argv.indexOf(name);
if (i !== -1 && argv[i + 1]) return argv[i + 1];
@@ -43,22 +61,65 @@ function parsePort(argv) {
return Number(flag(argv, "--port", process.env.PORT ?? 8090));
}
/** Resolve a request path to a file inside ROOT, or null if it escapes. */
/**
* Resolve a request path to a file inside ROOT. Returns null when the percent
* escapes are malformed (a guarded decode, so a bad `%` cannot throw out of the
* request handler) and false when the path escapes ROOT; the caller treats the
* first as an unknown page route and the second as forbidden.
*/
function resolvePath(urlPath) {
const decoded = decodeURIComponent(urlPath.split("?")[0]);
let decoded;
try {
decoded = decodeURIComponent(urlPath.split("?")[0]);
} catch {
return null;
}
const rel = normalize(decoded).replace(/^([/\\])+/, "");
const target = resolve(join(ROOT, rel || "index.html"));
if (target !== ROOT && !target.startsWith(ROOT + sep)) return null;
if (target !== ROOT && !target.startsWith(ROOT + sep)) return false;
return target;
}
/** Send index.html (the page shell). The router reads the real URL in the browser. */
async function serveIndex(res) {
const html = await readFile(join(ROOT, "index.html"), "utf8");
// A deep URL such as /runs/440 would otherwise resolve the shell's relative
// `./src/app.js` against /runs/. A root <base> keeps the shell's own asset URLs
// absolute without changing the address bar (and without editing index.html).
const body = html.replace(/<head>/i, '<head>\n <base href="/" />');
res.writeHead(200, {
"Content-Type": MIME[".html"],
"Cache-Control": "no-store",
});
res.end(body);
}
const server = createServer(async (req, res) => {
const pathname = (req.url ?? "/").split("?")[0];
if (pathname === "/favicon.ico") {
res.writeHead(204).end(); // no icon; keeps the console free of a 404
return;
}
// SPA fallback: a page route (`/runs/440`, `/pipelines/24/5/stage/plan.js`) or a
// non-asset GET serves the shell, so a hard navigation deep-links and the client
// router opens the destination. A path that looks like an asset outside a page
// prefix (`.js`, `.css`, `.png`, …) stays an honest 404, and a malformed escape
// is handled like any other unknown path rather than rejecting the handler.
const assetLike = ASSET_EXTENSIONS.has(extname(pathname).toLowerCase());
const pageLike = PAGE_PREFIXES.has(firstSegment(pathname));
const serveShell = pageLike || !assetLike;
const target = resolvePath(req.url ?? "/");
if (target === null) {
// A malformed percent escape is an unknown page route, not a handler throw.
if (serveShell) {
await serveIndex(res).catch(() => {
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
});
return;
}
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
return;
}
if (!target) {
res.writeHead(403).end("Forbidden");
return;
@@ -74,6 +135,12 @@ const server = createServer(async (req, res) => {
});
res.end(body);
} catch {
if (serveShell) {
await serveIndex(res).catch(() => {
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
});
return;
}
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
}
});