fix(runtime): stabilize navigation and custom errors
This commit is contained in:
@@ -66,6 +66,14 @@ interface RunningServer {
|
||||
|
||||
In development, `startServer` also connects `app/db/migrations` (and `app/db/<name>/migrations`) and auto-applies migrations, then starts an in-process file watcher. CSS edits hot-swap live. Page, component, layout, API, middleware, realtime, schema, locale, and public-asset edits invalidate only their cached modules, rescan routes where necessary, and morph fresh HTML through the existing HMR WebSocket. The server process and active gateway stay running.
|
||||
|
||||
### Custom not-found handlers
|
||||
|
||||
Add `app/pages/404.wrn` to customize unmatched frontend routes. The rendered
|
||||
page keeps the requested response's HTTP `404` status. Add `app/api/404.ts`
|
||||
with normal HTTP method exports to customize unmatched backend/API responses;
|
||||
its response body and headers are preserved and its status is normalized to
|
||||
`404`.
|
||||
|
||||
`getWrnCompileMetrics()` exposes cumulative content-addressed compiler cache
|
||||
`hits`, `misses`, successful `compilations`, `errors`, `totalDurationMs`, and
|
||||
`lastDurationMs` for the DevToolbar or custom diagnostics. Tests and embedded
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@wrnexus/dev-server",
|
||||
"version": "0.8.29",
|
||||
"version": "0.8.30",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"exports": {
|
||||
|
||||
@@ -672,6 +672,25 @@ export const HMR_CLIENT_JS = `
|
||||
pendingSync = false;
|
||||
var doc = new DOMParser().parseFromString(html, "text/html");
|
||||
|
||||
var i18nScript = Array.prototype.find.call(
|
||||
doc.querySelectorAll("script:not([src])"),
|
||||
function (node) { return /^window\.__wrnI18n=/.test(String(node.textContent || "").trim()); },
|
||||
);
|
||||
if (i18nScript) {
|
||||
var i18nMatch = /^window\.__wrnI18n=([\s\S]*);\s*$/.exec(String(i18nScript.textContent || "").trim());
|
||||
if (i18nMatch) {
|
||||
try {
|
||||
var incomingI18n = JSON.parse(i18nMatch[1]);
|
||||
var existingI18n = window.__wrnI18n || {};
|
||||
incomingI18n.t = existingI18n.t;
|
||||
incomingI18n.set = existingI18n.set;
|
||||
window.__wrnI18n = incomingI18n;
|
||||
} catch (error) {
|
||||
console.error("[wrnexus] failed to synchronize i18n HMR data", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (doc.title) {
|
||||
document.title = doc.title;
|
||||
}
|
||||
@@ -704,6 +723,10 @@ export const HMR_CLIENT_JS = `
|
||||
window.__wrnexusHydrateCsrFetches(document);
|
||||
}
|
||||
|
||||
if (window.__wrnLang && typeof window.__wrnLang.bind === "function") {
|
||||
window.__wrnLang.bind(document);
|
||||
}
|
||||
|
||||
if (
|
||||
window.wrnTheme &&
|
||||
typeof window.wrnTheme.bind === "function"
|
||||
@@ -1449,7 +1472,23 @@ export function createHandlers(deps: RuntimeDeps): Handlers {
|
||||
|
||||
async function handleApi(ctx: Context): Promise<Response> {
|
||||
const matched = router.matchApi(ctx.url.pathname);
|
||||
if (!matched) return Response.json({ error: "Not Found" }, { status: 404 });
|
||||
if (!matched) {
|
||||
const fallback = router.matchApi("/api/404");
|
||||
if (fallback && ctx.url.pathname !== "/api/404") {
|
||||
const originalPath = ctx.url.pathname;
|
||||
ctx.url.pathname = "/api/404";
|
||||
try {
|
||||
const response = await handleApi(ctx);
|
||||
return new Response(response.body, {
|
||||
status: 404,
|
||||
headers: response.headers,
|
||||
});
|
||||
} finally {
|
||||
ctx.url.pathname = originalPath;
|
||||
}
|
||||
}
|
||||
return Response.json({ error: "Not Found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Expose the canonical matched route to package dispatchers. A package may
|
||||
// contribute several URL paths from one module, and request URLs can be
|
||||
@@ -1606,7 +1645,23 @@ export function createHandlers(deps: RuntimeDeps): Handlers {
|
||||
}),
|
||||
);
|
||||
}
|
||||
const response = renderNotFound();
|
||||
let response: Response;
|
||||
const fallback = router.matchPage("/404");
|
||||
if (fallback && ctx.url.pathname !== "/404") {
|
||||
const originalPath = ctx.url.pathname;
|
||||
ctx.url.pathname = "/404";
|
||||
try {
|
||||
const rendered = await handlePage(ctx);
|
||||
response = new Response(rendered.body, {
|
||||
status: 404,
|
||||
headers: rendered.headers,
|
||||
});
|
||||
} finally {
|
||||
ctx.url.pathname = originalPath;
|
||||
}
|
||||
} else {
|
||||
response = renderNotFound();
|
||||
}
|
||||
if (!isMobileRequest) return response;
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("x-wrnexus-original-status", "404");
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { buildRouter } from "@wrnexus/router";
|
||||
import { createHandlers, type RuntimeDeps } from "../src/runtime.ts";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })));
|
||||
|
||||
function customNotFoundRuntime() {
|
||||
const root = mkdtempSync(join(tmpdir(), "wrnexus-not-found-"));
|
||||
roots.push(root);
|
||||
const app = join(root, "app");
|
||||
mkdirSync(join(app, "pages"), { recursive: true });
|
||||
mkdirSync(join(app, "api"), { recursive: true });
|
||||
writeFileSync(join(app, "pages/404.ts"), "export default () => '';");
|
||||
writeFileSync(join(app, "api/404.ts"), "export const GET = () => null;");
|
||||
return createHandlers({
|
||||
mode: "production",
|
||||
hmr: false,
|
||||
router: buildRouter(app),
|
||||
loadModule: async (file) =>
|
||||
file.includes(`${join("api", "404")}.ts`)
|
||||
? { GET: () => Response.json({ code: "CUSTOM_NOT_FOUND" }, { headers: { "x-custom": "yes" } }) }
|
||||
: { default: () => "<main><h1>That page is gone</h1></main>" },
|
||||
getMiddleware: async () => [],
|
||||
assets: { serve: async () => null },
|
||||
} satisfies RuntimeDeps);
|
||||
}
|
||||
|
||||
const server = { upgrade: () => false };
|
||||
|
||||
test("renders app/pages/404 with an HTTP 404 status", async () => {
|
||||
const response = await customNotFoundRuntime().fetch(
|
||||
new Request("https://example.test/missing"),
|
||||
server,
|
||||
);
|
||||
expect(response?.status).toBe(404);
|
||||
expect(await response?.text()).toContain("That page is gone");
|
||||
});
|
||||
|
||||
test("uses app/api/404 for unmatched API routes and preserves headers", async () => {
|
||||
const response = await customNotFoundRuntime().fetch(
|
||||
new Request("https://example.test/api/missing"),
|
||||
server,
|
||||
);
|
||||
expect(response?.status).toBe(404);
|
||||
expect(response?.headers.get("x-custom")).toBe("yes");
|
||||
expect(await response?.json()).toEqual({ code: "CUSTOM_NOT_FOUND" });
|
||||
});
|
||||
Reference in New Issue
Block a user