@warlock.js/web 5.2.3 → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/build/contribution.mjs.map +1 -1
- package/esm/build/discover-pages.mjs +5 -7
- package/esm/build/discover-pages.mjs.map +1 -1
- package/esm/build/generate-client-registry.mjs.map +1 -1
- package/esm/build/generate-pages-barrel.mjs.map +1 -1
- package/esm/build/page-default-export.mjs.map +1 -1
- package/esm/build/page-routes-manifest.mjs.map +1 -1
- package/esm/build/public-files.mjs.map +1 -1
- package/esm/build/read-route-exports.mjs.map +1 -1
- package/esm/client/build-hydrated-tree.mjs.map +1 -1
- package/esm/client/hydrate-page.mjs +4 -3
- package/esm/client/hydrate-page.mjs.map +1 -1
- package/esm/client/navigation/fetch-page-data.mjs +2 -2
- package/esm/client/navigation/fetch-page-data.mjs.map +1 -1
- package/esm/client/navigation/navigation-root.mjs +5 -1
- package/esm/client/navigation/navigation-root.mjs.map +1 -1
- package/esm/client/navigation/prefetch.mjs.map +1 -1
- package/esm/client/runtime/manifest.mjs.map +1 -1
- package/esm/client/runtime/matcher.mjs.map +1 -1
- package/esm/components/document-context.mjs.map +1 -1
- package/esm/components/link.mjs.map +1 -1
- package/esm/hydration-payload.mjs +6 -2
- package/esm/hydration-payload.mjs.map +1 -1
- package/esm/index.d.mts +4 -2
- package/esm/index.mjs +2 -1
- package/esm/localization.d.mts +21 -0
- package/esm/localization.mjs +28 -0
- package/esm/localization.mjs.map +1 -0
- package/esm/routing/data-request.mjs +5 -3
- package/esm/routing/data-request.mjs.map +1 -1
- package/esm/routing/filesystem-route.mjs +36 -7
- package/esm/routing/filesystem-route.mjs.map +1 -1
- package/esm/routing/layout-policy.mjs.map +1 -1
- package/esm/routing/page-file-segment.mjs +66 -0
- package/esm/routing/page-file-segment.mjs.map +1 -0
- package/esm/routing/page-route-grammar.mjs +79 -0
- package/esm/routing/page-route-grammar.mjs.map +1 -0
- package/esm/routing/query-string.mjs.map +1 -1
- package/esm/routing/route-identity.d.mts +69 -0
- package/esm/routing/route-identity.mjs +100 -44
- package/esm/routing/route-identity.mjs.map +1 -1
- package/esm/routing/route-table.mjs.map +1 -1
- package/esm/server/build-hydration-payload.mjs +3 -2
- package/esm/server/build-hydration-payload.mjs.map +1 -1
- package/esm/server/create-page-route-handler.d.mts +34 -1
- package/esm/server/create-page-route-handler.mjs +35 -4
- package/esm/server/create-page-route-handler.mjs.map +1 -1
- package/esm/server/execute-page-request.mjs.map +1 -1
- package/esm/server/framework-default-not-found-stylesheet.mjs +102 -0
- package/esm/server/framework-default-not-found-stylesheet.mjs.map +1 -0
- package/esm/server/install-page-routes-from-manifest.mjs +13 -16
- package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
- package/esm/server/install-page-routes.d.mts +3 -1
- package/esm/server/install-page-routes.mjs +11 -11
- package/esm/server/install-page-routes.mjs.map +1 -1
- package/esm/server/match-page-route.mjs.map +1 -1
- package/esm/server/not-found-page.d.mts +1 -13
- package/esm/server/not-found-page.mjs +50 -5
- package/esm/server/not-found-page.mjs.map +1 -1
- package/esm/server/page-file-change.mjs.map +1 -1
- package/esm/server/page-route-reload.mjs.map +1 -1
- package/esm/server/register-production-public-files.mjs +16 -1
- package/esm/server/register-production-public-files.mjs.map +1 -1
- package/esm/server/render-page.d.mts +1 -8
- package/esm/server/render-page.mjs +24 -21
- package/esm/server/render-page.mjs.map +1 -1
- package/esm/server/response-cache-floor.mjs +79 -0
- package/esm/server/response-cache-floor.mjs.map +1 -0
- package/esm/server/set-cookie-cache-floor-hook.mjs +41 -0
- package/esm/server/set-cookie-cache-floor-hook.mjs.map +1 -0
- package/esm/server/settle-page-response.mjs.map +1 -1
- package/esm/server/stylesheet-urls.mjs.map +1 -1
- package/esm/server/unregistered-pages.mjs.map +1 -1
- package/esm/server/web-connector-factory.mjs.map +1 -1
- package/esm/server/web-connector.d.mts +1 -1
- package/esm/server/web-connector.mjs +23 -4
- package/esm/server/web-connector.mjs.map +1 -1
- package/esm/shared.mjs.map +1 -1
- package/esm/vite/build-client.mjs.map +1 -1
- package/esm/vite/gate-a-resolve.mjs.map +1 -1
- package/esm/vite/gate-b-secrets.mjs.map +1 -1
- package/esm/vite/gate-c-verify.mjs.map +1 -1
- package/esm/vite/hydration-entries.mjs.map +1 -1
- package/esm/vite/index.mjs.map +1 -1
- package/esm/vite/page-registry-plugin.mjs.map +1 -1
- package/esm/vite/projection.mjs.map +1 -1
- package/llms-full.txt +62 -33
- package/llms.txt +1 -1
- package/package.json +4 -3
- package/skills/create-a-page/SKILL.md +59 -28
- package/skills/navigate-on-the-client/SKILL.md +16 -11
- package/skills/serve-styles/SKILL.md +2 -1
- package/skills/use-layouts/SKILL.md +3 -6
- package/skills/write-the-root/SKILL.md +0 -2
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
//#region ../web/src/routing/page-route-grammar.ts
|
|
2
|
+
const allowed = { type: "allowed" };
|
|
3
|
+
function rejected(reason) {
|
|
4
|
+
return {
|
|
5
|
+
type: "rejected",
|
|
6
|
+
reason
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
/** Whole-segment `:param` — the entire segment is `:` followed by a plain name. */
|
|
10
|
+
const wholeSegmentParamPattern = /^:[A-Za-z0-9_]+$/;
|
|
11
|
+
/**
|
|
12
|
+
* Classifies one segment of a slash-led path. `isFinal` matters because `*`
|
|
13
|
+
* is allowed only as the whole final segment, and an empty segment at the
|
|
14
|
+
* end means a trailing slash rather than a doubled one.
|
|
15
|
+
*/
|
|
16
|
+
function classifySegment(segment, path, isFinal) {
|
|
17
|
+
if (segment === "") {
|
|
18
|
+
if (isFinal) return rejected(`Path "${path}" ends with a trailing slash, which page routes do not support — declare "${path.slice(0, -1)}" without the trailing slash instead.`);
|
|
19
|
+
return rejected(`Path "${path}" contains an empty segment from a doubled slash, which page routes do not support — remove the extra slash.`);
|
|
20
|
+
}
|
|
21
|
+
if (segment === "*") {
|
|
22
|
+
if (isFinal) return allowed;
|
|
23
|
+
return rejected(`Path "${path}" uses "*" before its final segment, and page routes support "*" only as a terminal catch-all — move the "*" to the end of the path, as in "/a/b/*".`);
|
|
24
|
+
}
|
|
25
|
+
if (segment.includes("*")) {
|
|
26
|
+
if (isFinal) return rejected(`Segment "${segment}" of "${path}" attaches "*" to other text, and page routes support "*" only as a whole final segment — declare it as its own segment, as in "/prefix/*".`);
|
|
27
|
+
return rejected(`Segment "${segment}" of "${path}" uses "*" before the final segment, and page routes support "*" only as a whole terminal segment — move the "*" to the end of the path, as in "/a/b/*".`);
|
|
28
|
+
}
|
|
29
|
+
if (segment.includes("\\:")) return rejected(`Segment "${segment}" of "${path}" escapes a colon with a backslash, which page routes do not support — page routes treat ":" only as a whole-segment param marker, so a literal colon cannot be declared; rename the segment to avoid the colon.`);
|
|
30
|
+
if (!segment.includes(":")) return allowed;
|
|
31
|
+
if (wholeSegmentParamPattern.test(segment)) return allowed;
|
|
32
|
+
if (segment.includes("(")) return rejected(`Segment "${segment}" of "${path}" constrains its param with a regex, which page routes do not support — use a plain whole-segment param such as ":id" and validate the value in the page instead.`);
|
|
33
|
+
if (segment.endsWith("?")) return rejected(`Segment "${segment}" of "${path}" marks its param optional with "?", which page routes do not support — declare two pages instead, one with the param segment and one without it.`);
|
|
34
|
+
if (segment.split(":").length - 1 > 1) return rejected(`Segment "${segment}" of "${path}" declares more than one param, and page routes require a param to occupy its whole segment — split the params into separate segments, as in ":lat/:lng".`);
|
|
35
|
+
return rejected(`Segment "${segment}" of "${path}" mixes a ":" param with other text, and page routes require a param to occupy its whole segment — use a plain whole-segment param such as ":id" instead.`);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Decides whether a declared page `route.path` is inside the page-route
|
|
39
|
+
* grammar. Pure and total: every input yields a verdict and nothing throws.
|
|
40
|
+
* `path` must already be canonical (no normalization is performed here — as
|
|
41
|
+
* with the rest of this directory, this module asserts, it never repairs).
|
|
42
|
+
*/
|
|
43
|
+
function classifyPageRoutePath(path) {
|
|
44
|
+
if (path === "*") return allowed;
|
|
45
|
+
if (path === "") return rejected(`The page route path is empty — declare "/" for the site root instead.`);
|
|
46
|
+
if (!path.startsWith("/")) return rejected(`Path "${path}" does not start with "/", and the only page route allowed without a leading slash is the exact root wildcard "*" — declare "/${path}" instead.`);
|
|
47
|
+
if (path === "/") return allowed;
|
|
48
|
+
const segments = path.slice(1).split("/");
|
|
49
|
+
const lastIndex = segments.length - 1;
|
|
50
|
+
for (const [index, segment] of segments.entries()) {
|
|
51
|
+
const verdict = classifySegment(segment, path, index === lastIndex);
|
|
52
|
+
if (verdict.type === "rejected") return verdict;
|
|
53
|
+
}
|
|
54
|
+
return allowed;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The single error contract for a rejected page route path — the one class
|
|
58
|
+
* and one message every caller of {@link classifyPageRoutePath} raises when
|
|
59
|
+
* it refuses a page whose declared path was rejected. `pageFile` is the
|
|
60
|
+
* caller's context (its audience-appropriate identifier for the page — an
|
|
61
|
+
* app-root-relative POSIX path, in practice); `routePath` and `reason` come
|
|
62
|
+
* from the verdict; the category and wording are this module's.
|
|
63
|
+
*/
|
|
64
|
+
var PageRoutePathNotSupportedError = class extends Error {
|
|
65
|
+
pageFile;
|
|
66
|
+
routePath;
|
|
67
|
+
reason;
|
|
68
|
+
constructor(pageFile, routePath, reason) {
|
|
69
|
+
super(`"${pageFile}" declares the page route path "${routePath}", which is not supported: ${reason} Page routes support a narrower grammar than API routes — a page path may be "/", static segments, whole-segment ":param" segments, the exact root wildcard "*", or a path whose final segment is exactly "*" (such as "/prefix/*").`);
|
|
70
|
+
this.pageFile = pageFile;
|
|
71
|
+
this.routePath = routePath;
|
|
72
|
+
this.reason = reason;
|
|
73
|
+
this.name = "PageRoutePathNotSupportedError";
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
//#endregion
|
|
78
|
+
export { PageRoutePathNotSupportedError, classifyPageRoutePath };
|
|
79
|
+
//# sourceMappingURL=page-route-grammar.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"page-route-grammar.mjs","names":[],"sources":["../../../../../../../web/src/routing/page-route-grammar.ts"],"sourcesContent":["/**\r\n * Page-route grammar — the single, pure predicate that decides whether a\r\n * page's DECLARED, colon-form `route.path` (`/users/:id`) is inside the PAGE\r\n * route grammar. Page routes deliberately support a NARROWER grammar than\r\n * API routes. A page's FILESYSTEM segment grammar — the shape of a directory\r\n * name or basename on disk, such as `[id]` — is a separate concern owned by\r\n * the sibling module `page-file-segment.ts`; this predicate does not cover it.\r\n *\r\n * DIRECTORY CONTRACT — applies to everything in `web/src/routing/`: nothing\r\n * here may import `node:fs`, `node:path`, `vite`, or `fastify`. This module\r\n * receives a canonical route path string and trusts nothing about it beyond\r\n * what it checks — it asserts rather than trusts, but it never repairs a\r\n * malformed path into a valid one.\r\n *\r\n * ALLOWED — and ONLY these shapes; anything else is rejected by default:\r\n * the root path `/`; static segments (`/users/settings`); whole-segment\r\n * `:param` segments where the param occupies its entire segment\r\n * (`/users/:id`); the exact root wildcard `*` (the one path allowed without\r\n * a leading slash — distinct from `/*`); and slash-led paths whose FINAL\r\n * segment is exactly `*` (`/*`, `/prefix/*`, `/a/b/*`).\r\n *\r\n * REJECTED — each with a reason naming the offending construct and, where\r\n * one exists, the supported alternative: regex-constrained params\r\n * (`/users/:id(\\d+)`), optional params (`/users/:id?`), multiple params in\r\n * one segment (`/near/:lat-:lng`), params mixed with static text\r\n * (`/file/:name.png`, `/pre:id`), backslash-escaped colons\r\n * (`/path/\\:literal`), a `*` that does not occupy a whole terminal segment\r\n * (`/a/prefix*`, or a wildcard before the final segment), paths missing\r\n * their leading slash, empty\r\n * segments from doubled slashes (`/a//b`), and trailing slashes (`/users/`).\r\n *\r\n * REJECTION IS DATA, NOT A THROW: {@link classifyPageRoutePath} is total and\r\n * never raises. What a rejection MEANS to the user is nonetheless fixed\r\n * here: {@link PageRoutePathNotSupportedError} is the single error contract\r\n * every caller raises when it refuses a rejected path — one class, one\r\n * message shape, built from the rejection reason plus caller-supplied page\r\n * identity. Callers decide only WHEN to raise it and supply that context;\r\n * none of them wraps the rejection in a category or wording of its own.\r\n */\r\n\r\n/**\r\n * The predicate's verdict for one declared page route path:\r\n *\r\n * - `\"allowed\"` — the path is one of the grammar's allowed shapes.\r\n * - `\"rejected\"` — the path is outside the grammar; `reason` is a complete,\r\n * user-readable sentence naming the offending construct (the segment, when\r\n * one segment is at fault) and the supported alternative if one exists.\r\n */\r\nexport type PageRoutePathVerdict = { type: \"allowed\" } | { type: \"rejected\"; reason: string };\r\n\r\nconst allowed: PageRoutePathVerdict = { type: \"allowed\" };\r\n\r\nfunction rejected(reason: string): PageRoutePathVerdict {\r\n return { type: \"rejected\", reason };\r\n}\r\n\r\n/** Whole-segment `:param` — the entire segment is `:` followed by a plain name. */\r\nconst wholeSegmentParamPattern = /^:[A-Za-z0-9_]+$/;\r\n\r\n/**\r\n * Classifies one segment of a slash-led path. `isFinal` matters because `*`\r\n * is allowed only as the whole final segment, and an empty segment at the\r\n * end means a trailing slash rather than a doubled one.\r\n */\r\nfunction classifySegment(segment: string, path: string, isFinal: boolean): PageRoutePathVerdict {\r\n if (segment === \"\") {\r\n if (isFinal) {\r\n return rejected(\r\n `Path \"${path}\" ends with a trailing slash, which page routes do not support — ` +\r\n `declare \"${path.slice(0, -1)}\" without the trailing slash instead.`,\r\n );\r\n }\r\n\r\n return rejected(\r\n `Path \"${path}\" contains an empty segment from a doubled slash, which page routes do not ` +\r\n `support — remove the extra slash.`,\r\n );\r\n }\r\n\r\n if (segment === \"*\") {\r\n if (isFinal) {\r\n return allowed;\r\n }\r\n\r\n return rejected(\r\n `Path \"${path}\" uses \"*\" before its final segment, and page routes support \"*\" only as a ` +\r\n `terminal catch-all — move the \"*\" to the end of the path, as in \"/a/b/*\".`,\r\n );\r\n }\r\n\r\n if (segment.includes(\"*\")) {\r\n if (isFinal) {\r\n return rejected(\r\n `Segment \"${segment}\" of \"${path}\" attaches \"*\" to other text, and page routes support ` +\r\n `\"*\" only as a whole final segment — declare it as its own segment, as in \"/prefix/*\".`,\r\n );\r\n }\r\n\r\n return rejected(\r\n `Segment \"${segment}\" of \"${path}\" uses \"*\" before the final segment, and page routes ` +\r\n `support \"*\" only as a whole terminal segment — move the \"*\" to the end of the path, as ` +\r\n `in \"/a/b/*\".`,\r\n );\r\n }\r\n\r\n if (segment.includes(\"\\\\:\")) {\r\n return rejected(\r\n `Segment \"${segment}\" of \"${path}\" escapes a colon with a backslash, which page routes do ` +\r\n `not support — page routes treat \":\" only as a whole-segment param marker, so a literal ` +\r\n `colon cannot be declared; rename the segment to avoid the colon.`,\r\n );\r\n }\r\n\r\n if (!segment.includes(\":\")) {\r\n return allowed;\r\n }\r\n\r\n if (wholeSegmentParamPattern.test(segment)) {\r\n return allowed;\r\n }\r\n\r\n if (segment.includes(\"(\")) {\r\n return rejected(\r\n `Segment \"${segment}\" of \"${path}\" constrains its param with a regex, which page routes do ` +\r\n `not support — use a plain whole-segment param such as \":id\" and validate the value in ` +\r\n `the page instead.`,\r\n );\r\n }\r\n\r\n if (segment.endsWith(\"?\")) {\r\n return rejected(\r\n `Segment \"${segment}\" of \"${path}\" marks its param optional with \"?\", which page routes do ` +\r\n `not support — declare two pages instead, one with the param segment and one without it.`,\r\n );\r\n }\r\n\r\n if (segment.split(\":\").length - 1 > 1) {\r\n return rejected(\r\n `Segment \"${segment}\" of \"${path}\" declares more than one param, and page routes require a ` +\r\n `param to occupy its whole segment — split the params into separate segments, as in ` +\r\n `\":lat/:lng\".`,\r\n );\r\n }\r\n\r\n return rejected(\r\n `Segment \"${segment}\" of \"${path}\" mixes a \":\" param with other text, and page routes ` +\r\n `require a param to occupy its whole segment — use a plain whole-segment param such as ` +\r\n `\":id\" instead.`,\r\n );\r\n}\r\n\r\n/**\r\n * Decides whether a declared page `route.path` is inside the page-route\r\n * grammar. Pure and total: every input yields a verdict and nothing throws.\r\n * `path` must already be canonical (no normalization is performed here — as\r\n * with the rest of this directory, this module asserts, it never repairs).\r\n */\r\nexport function classifyPageRoutePath(path: string): PageRoutePathVerdict {\r\n if (path === \"*\") {\r\n return allowed;\r\n }\r\n\r\n if (path === \"\") {\r\n return rejected(`The page route path is empty — declare \"/\" for the site root instead.`);\r\n }\r\n\r\n if (!path.startsWith(\"/\")) {\r\n return rejected(\r\n `Path \"${path}\" does not start with \"/\", and the only page route allowed without a leading ` +\r\n `slash is the exact root wildcard \"*\" — declare \"/${path}\" instead.`,\r\n );\r\n }\r\n\r\n if (path === \"/\") {\r\n return allowed;\r\n }\r\n\r\n const segments = path.slice(1).split(\"/\");\r\n const lastIndex = segments.length - 1;\r\n\r\n for (const [index, segment] of segments.entries()) {\r\n const verdict = classifySegment(segment, path, index === lastIndex);\r\n\r\n if (verdict.type === \"rejected\") {\r\n return verdict;\r\n }\r\n }\r\n\r\n return allowed;\r\n}\r\n\r\n/**\r\n * The single error contract for a rejected page route path — the one class\r\n * and one message every caller of {@link classifyPageRoutePath} raises when\r\n * it refuses a page whose declared path was rejected. `pageFile` is the\r\n * caller's context (its audience-appropriate identifier for the page — an\r\n * app-root-relative POSIX path, in practice); `routePath` and `reason` come\r\n * from the verdict; the category and wording are this module's.\r\n */\r\nexport class PageRoutePathNotSupportedError extends Error {\r\n public constructor(\r\n public readonly pageFile: string,\r\n public readonly routePath: string,\r\n public readonly reason: string,\r\n ) {\r\n super(\r\n `\"${pageFile}\" declares the page route path \"${routePath}\", which is not supported: ` +\r\n `${reason} Page routes support a narrower grammar than API routes — a page path may be ` +\r\n `\"/\", static segments, whole-segment \":param\" segments, the exact root wildcard \"*\", or ` +\r\n `a path whose final segment is exactly \"*\" (such as \"/prefix/*\").`,\r\n );\r\n this.name = \"PageRoutePathNotSupportedError\";\r\n }\r\n}\r\n"],"mappings":";AAkDA,MAAM,UAAgC,EAAE,MAAM,UAAU;AAExD,SAAS,SAAS,QAAsC;CACtD,OAAO;EAAE,MAAM;EAAY;CAAO;AACpC;;AAGA,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AAC,MAAM,GAAG;CACxC,MAAM,YAAY,SAAS,SAAS;CAEpC,KAAK,MAAM,CAAC,OAAO,YAAY,SAAS,QAAQ,GAAG;EACjD,MAAM,UAAU,gBAAgB,SAAS,MAAM,UAAU,SAAS;EAElE,IAAI,QAAQ,SAAS,YACnB,OAAO;CAEX;CAEA,OAAO;AACT;;;;;;;;;AAUA,IAAa,iCAAb,cAAoD,MAAM;CAEtC;CACA;CACA;CAHlB,AAAO,YACL,AAAgB,UAChB,AAAgB,WAChB,AAAgB,QAChB;EACA,MACE,IAAI,SAAS,kCAAkC,UAAU,6BACpD,OAAO,qOAGd;EATgB;EACA;EACA;EAQhB,KAAK,OAAO;CACd;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-string.mjs","names":[],"sources":["../../../../../../../web/src/routing/query-string.ts"],"sourcesContent":["/**\n * The query string: BOTH directions, one grammar, one file.\n *\n * ── The rule this module exists to obey ──────────────────────────────────────\n *\n * `queryStringOf` is what `href(name, params, query)` appends, and therefore\n * what every `<Link>` puts in the document; `queryString.parse` is what reads it\n * back. They live together because a second, independently-written\n * query-string implementation would mean one thing writes URLs and a different\n * thing reads them. Query-string libraries genuinely disagree about arrays,\n * nested objects and space escaping, so the moment the two drift the round trip\n * loses data SILENTLY — the wrong value renders and no error is raised\n * anywhere. That is the two-route-matchers failure class (canon 9c8f878b) one\n * layer down.\n *\n * Escaping is not two rules that agree today. Both directions stand on\n * `URLSearchParams`: the encoder builds one and calls `.toString()`, the decoder\n * hands the string back to `new URLSearchParams(...)`. `+`-for-space and every\n * percent-encoding rule are therefore ONE rule and cannot drift.\n *\n * ── The grammar, and why it is not ours to choose ────────────────────────────\n *\n * Structure — arrays and nested objects — is the part `URLSearchParams` has no\n * opinion about, so it was read off the SERVER rather than invented. Warlock is\n * a backend framework and core already parses query strings for list endpoints\n * and filters; a client that emitted anything else would not have fixed this\n * module's bug, it would have moved it across the wire where it is harder to\n * see. Measured, with file:line, in\n * `reports/query-grammar-findings-2026-08-24.md`:\n *\n * - `core/src/http/server.ts:14-36` configures Fastify with NO\n * `querystringParser`, so find-my-way's `fast-querystring` default applies:\n * flat keys, `+` is a space, a repeated key collapses to an array.\n * - `core/src/http/request.ts:491` then runs `request.query` through\n * `parseBody` — the SAME bracket-aware parser as the request body.\n * - `core/src/http/request.ts:516-520` reads `key[]` as an array marker, and\n * `:568-575` wraps a single `key[]=a` into the one-element array `[\"a\"]`.\n * - `core/src/http/request.ts:557-561` turns `key[sub]=v` into\n * `{key: {sub: v}}`, one level deep.\n *\n * So: `tags[]=a&tags[]=b` for arrays, `filter[status]=active` for objects,\n * `filter[tags][]=a` for an array inside an object. Bare repeated keys\n * (`tags=a&tags=b`) would also reach core as an array, but only at cardinality\n * two or more — `tags=a` comes back as the scalar `\"a\"`, and a shape that\n * changes with the number of matches is a `TypeError` waiting for the day a\n * filter matches one item. `[]` is the form core wrote a branch for.\n *\n * ── What is REFUSED, and why refusing is the safe answer ─────────────────────\n *\n * Two levels of nesting is not a gap in core, it is measured data loss:\n * `a[b][c]=x` takes the `][` branch at `core/src/http/request.ts:528-551`,\n * computes `Number(\"b\")` as `NaN`, and the value lands on a `NaN` index and\n * vanishes — core answers `{a: []}`. So the encoder throws\n * {@link UnserializableQueryValueError} rather than write it. `href()` already\n * throws on a missing route parameter rather than emit a link that renders\n * correctly and 404s; this is the same call.\n *\n * ── What the encoder still normalises, and what that costs ───────────────────\n *\n * Leaf values are serialised with `String(value)`, so every value arrives back\n * as a `string`: `href(\"p\", {}, { page: 2 })` writes `?page=2`, and `2` and\n * `\"2\"` are the same URL. The round-trip law that can actually hold is\n * `parse(encode(query)) === query with String() applied to its leaves and\n * undefined dropped`, and that is what the spec asserts. Asserting anything\n * stronger would be asserting a decoder that guesses types, which is how\n * `?zip=01234` becomes the number `1234`.\n *\n * The decoder does NOT split values on `,`: that would turn the legitimate\n * string `\"Doe, John\"` into `[\"Doe\", \" John\"]`, trading a visible limitation for\n * a silent corruption of ordinary data. Arrays are carried by `[]`, which is\n * unambiguous, so there is nothing left to guess at.\n *\n * ── Universal by requirement, not by accident ────────────────────────────────\n *\n * `web` renders on the server first, so every export here is safe to import and\n * to CALL with no DOM. `@mongez/react-router`'s equivalent reads\n * `window.location.search` unguarded (query-string.ts:22) and throws under SSR.\n * Here the browser-only readers return their empty answer instead — see\n * `queryString.all` for the hydration caveat that comes with that.\n *\n * ── Still NOT here: `toQueryString` and `update` ─────────────────────────────\n *\n * MRR exposes `toQueryString(params)` and `update(params)`, which SERIALISE.\n * The serialiser they need is no longer module-private — `queryStringOf` is\n * exported from here — so the old blocker is gone. What remains is that\n * `web/src/index.ts` does not re-export it yet, and the barrel is owned\n * elsewhere. That is a one-line follow-up, not a redesign.\n */\n\n/** A decoded leaf. Always a `string` — see the header on `String(value)`. */\nexport type QueryStringLeaf = string;\n\n/**\n * The inside of a `key[sub]` bag: one level deep, exactly as far as core parses.\n *\n * There is no deeper case to model. `key[sub][deeper]` is refused by the encoder\n * and carried verbatim as a literal key by the decoder, so a nested bag only\n * ever holds a leaf or an array of leaves.\n */\nexport type QueryStringNested = Record<string, QueryStringLeaf | QueryStringLeaf[]>;\n\n/** A decoded value: a leaf, a `key[]` array, or a `key[sub]` bag. */\nexport type QueryStringValue = QueryStringLeaf | QueryStringLeaf[] | QueryStringNested;\n\n/** A decoded query string. */\nexport type QueryStringObject = Record<string, QueryStringValue>;\n\n/** What {@link queryStringOf} accepts. Values are validated, not trusted. */\nexport type QueryStringInput = Readonly<Record<string, unknown>>;\n\n/**\n * Thrown when a query value has a shape the wire format cannot carry.\n *\n * Deliberately LOUD. The alternative is emitting something core silently\n * mangles — `a[b][c]=x` arrives as `{a: []}` — which is this defect all over\n * again, one layer further from where anyone would look for it.\n */\nexport class UnserializableQueryValueError extends Error {\n public constructor(\n public readonly queryKey: string,\n public readonly shape: string,\n ) {\n super(\n `Warlock cannot put ${shape} in a query string at \"${queryKey}\". The wire format is the ` +\n \"one @warlock.js/core parses (core/src/http/request.ts:503-591): a value may be a \" +\n \"scalar, an array of scalars (`key[]=a&key[]=b`), or an object one level deep whose \" +\n \"values are scalars or arrays of scalars (`key[sub]=a`, `key[sub][]=a`). Anything \" +\n \"deeper is refused rather than written, because core reads `a[b][c]=x` back as \" +\n \"`{a: []}` — the value is destroyed on arrival with no error. Flatten the value, or \" +\n \"JSON.stringify it into a single scalar and parse it on the server.\",\n );\n this.name = \"UnserializableQueryValueError\";\n }\n}\n\n/**\n * Is this a BAG of query keys, as opposed to a value with its own string form?\n *\n * A `Date`, a `URL` or anything else carrying its own `toString` is a scalar\n * here — `String(value)` is meaningful for it, and turning it into\n * `since[getTime]=...` would be absurd. A plain object, or a class instance that\n * would otherwise stringify to the useless `\"[object Object]\"`, is a bag and\n * gets enumerated.\n *\n * The `typeof` check matters for null-prototype objects: they have no\n * `toString` at all, and `String()` on one THROWS.\n */\nfunction isKeyBag(value: object): boolean {\n const stringForm = (value as { toString?: unknown }).toString;\n\n return typeof stringForm !== \"function\" || stringForm === Object.prototype.toString;\n}\n\n/** Refuse anything that is not a leaf. Used everywhere a leaf is the only legal shape. */\nfunction requireLeaf(key: string, value: unknown): void {\n if (Array.isArray(value)) {\n throw new UnserializableQueryValueError(key, \"a nested array\");\n }\n\n if (typeof value === \"object\" && value !== null && isKeyBag(value)) {\n throw new UnserializableQueryValueError(key, \"a nested object\");\n }\n}\n\n/**\n * Append `key[]=element` per element.\n *\n * An `undefined` element is skipped, matching the top-level rule. Because the\n * `[]` form carries no indices, skipping shortens the array rather than leaving\n * a hole — there is no hole to leave.\n *\n * An EMPTY array appends nothing, so the key is absent from the URL. The format\n * has no way to say \"an array with no elements\": `key[]=` means the one-element\n * array `[\"\"]`, which is a different value. A visible limitation beats a guess.\n */\nfunction appendArray(search: URLSearchParams, key: string, value: readonly unknown[]): void {\n const arrayKey = `${key}[]`;\n\n for (const element of value) {\n if (element === undefined) continue;\n\n requireLeaf(arrayKey, element);\n\n search.append(arrayKey, String(element));\n }\n}\n\n/** Append `key[sub]=value`, or `key[sub][]=value` when the member is an array. */\nfunction appendBag(search: URLSearchParams, key: string, value: object): void {\n for (const [subKey, subValue] of Object.entries(value)) {\n if (subValue === undefined) continue;\n\n const nestedKey = `${key}[${subKey}]`;\n\n if (Array.isArray(subValue)) {\n appendArray(search, nestedKey, subValue);\n continue;\n }\n\n requireLeaf(nestedKey, subValue);\n\n search.append(nestedKey, String(subValue));\n }\n}\n\n/**\n * Serialise a query object to a search string, INCLUDING the leading `?`.\n *\n * Returns `\"\"` — not `\"?\"` — when there is nothing to write, so the result can\n * always be concatenated onto a path. `href()` is the primary caller; the\n * grammar it emits is the one core parses, and the whole justification is in the\n * module header.\n *\n * @throws {UnserializableQueryValueError} when a value nests deeper than the\n * wire format can carry.\n */\nexport function queryStringOf(query: QueryStringInput | undefined): string {\n if (query === undefined) return \"\";\n\n const search = new URLSearchParams();\n\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n\n if (Array.isArray(value)) {\n appendArray(search, key, value);\n continue;\n }\n\n if (typeof value === \"object\" && value !== null && isKeyBag(value)) {\n appendBag(search, key, value);\n continue;\n }\n\n search.append(key, String(value));\n }\n\n const serialized = search.toString();\n\n return serialized === \"\" ? \"\" : `?${serialized}`;\n}\n\n/**\n * What to do when the same PLAIN key appears more than once, e.g. `?tag=a&tag=b`.\n *\n * - `\"last\"` — keep the final occurrence. Matches `URLSearchParams.get()`, the\n * read side of the primitive the encoder writes with, and keeps every value a\n * `string`.\n * - `\"first\"` — keep the earliest occurrence.\n * - `\"array\"` — collect every occurrence. Under this strategy a key that occurs\n * ONCE is still an array of one, because a shape that changes with the number\n * of values is a `TypeError` waiting for the day a filter matches a single\n * item.\n *\n * It does NOT govern `key[]` or `key[sub]`; those are shapes the encoder writes\n * deliberately, and their meaning is fixed. See {@link QueryStringOptions}.\n */\nexport type RepeatedKeyStrategy = \"last\" | \"first\" | \"array\";\n\n/**\n * The whole option surface.\n *\n * ── Why this is one flag and not MRR's pluggable parsers ─────────────────────\n *\n * MRR's `setQueryStringOptions` swaps `objectParser` and `stringParser`\n * (query-string.ts:10-15). Neither survives contact with a fixed, shared\n * encoder:\n *\n * - A pluggable `objectParser` is a licence to install a READER that disagrees\n * with the writer. It is precisely the silent round-trip break this module\n * was written to prevent, offered as a supported API.\n * - A pluggable `stringParser` would be worse: it cannot reach `href()`, which\n * calls `queryStringOf` directly with no hook. Setting it would change what\n * this module emits while every `<Link>` on the page kept emitting the old\n * format — two writers, disagreeing, by configuration.\n *\n * `repeatedKeys` is safe for one specific reason, and the reason survived the\n * move to bracket notation: `queryStringOf` iterates `Object.entries`, so it can\n * never emit a duplicate PLAIN key. It now does emit duplicate `key[]` pairs —\n * that is how an array is written — but those go down the array branch of the\n * decoder, which this flag does not touch. Were the flag to govern the bracket\n * forms as well, `repeatedKeys: \"array\"` would decode `filter[x]=1` as\n * `{filter: {x: [\"1\"]}}` and break the round trip BY CONFIGURATION.\n *\n * So the flag still decides only something the encoder has no opinion about: a\n * repeated plain key, which can only arrive from a URL this package did not\n * write — hand-typed, external links, `GET` forms.\n *\n * Set it at BOOT, not per request: this is process-global config, and a\n * request-scoped write would be read by whatever request happens to be\n * rendering (the defect catalogued at route-table.ts:10-25).\n */\nexport type QueryStringOptions = {\n readonly repeatedKeys?: RepeatedKeyStrategy;\n};\n\ntype ResolvedQueryStringOptions = Required<QueryStringOptions>;\n\nconst DEFAULT_OPTIONS: ResolvedQueryStringOptions = {\n repeatedKeys: \"last\",\n};\n\n/**\n * Held on `globalThis`, not in a module binding, for the reason measured and\n * written up at route-table.ts:43-65: in dev the process runs two module graphs\n * over these files (tsx/Node and Vite's SSR runner), so a `let` written by boot\n * code is not the `let` a component reads. A split here would be quiet — the\n * second graph would silently fall back to the defaults and decode a repeated\n * key the other way.\n */\nconst OPTIONS_SLOT = Symbol.for(\"warlock.web.queryStringOptions\");\n\ntype OptionsHost = typeof globalThis & {\n [OPTIONS_SLOT]?: ResolvedQueryStringOptions;\n};\n\nfunction currentOptions(): ResolvedQueryStringOptions {\n return (globalThis as OptionsHost)[OPTIONS_SLOT] ?? DEFAULT_OPTIONS;\n}\n\n/**\n * Merge query-string options over the current ones.\n *\n * Named for `@mongez/react-router`'s function so migrating call sites keep\n * compiling; the OPTIONS are deliberately narrower, and `QueryStringOptions`\n * explains exactly which ones were refused and why.\n */\nexport function setQueryStringOptions(options: QueryStringOptions): void {\n (globalThis as OptionsHost)[OPTIONS_SLOT] = { ...currentOptions(), ...options };\n}\n\n/**\n * Drop back to the defaults.\n *\n * Exists because the options are process-global: a test that set one would\n * otherwise leak it into every later test in the same worker, passing in file\n * order and failing under `--shuffle`. Same reasoning as `resetRouteTable`.\n */\nexport function resetQueryStringOptions(): void {\n delete (globalThis as OptionsHost)[OPTIONS_SLOT];\n}\n\n/**\n * The search string of the current document, or `\"\"` when there is no document.\n *\n * The `typeof` guard is the SSR contract: no export in this module may touch a\n * DOM global without one.\n */\nfunction browserSearch(): string {\n if (typeof window === \"undefined\") return \"\";\n\n return window.location?.search ?? \"\";\n}\n\n/**\n * Reduce anything search-shaped to the pairs themselves.\n *\n * Accepts `\"?a=1\"`, `\"a=1\"`, `\"/path?a=1\"` and a full URL, because\n * `location.href`, `location.search` and a hand-written literal all turn up at\n * this door and `new URLSearchParams(\"/path?a=1\")` would answer with the key\n * `\"/path?a\"` — a wrong answer with no error. Cutting at the first `?` and the\n * first `#` is safe rather than heuristic: `queryStringOf` percent-encodes both\n * characters inside values (`%3F`, `%23`), so a literal one is always a\n * delimiter.\n */\nfunction searchPairsOf(source: string): string {\n const withoutHash = source.split(\"#\", 1)[0];\n const questionMark = withoutHash.indexOf(\"?\");\n\n return questionMark === -1 ? withoutHash : withoutHash.slice(questionMark + 1);\n}\n\n/**\n * The three key shapes the encoder writes. Everything else is a literal key.\n *\n * The character classes exclude brackets, so each pattern matches exactly one\n * shape: `tags[]` cannot satisfy `NESTED`, and `a[b][c]` satisfies none of them.\n */\nconst ARRAY_KEY = /^([^[\\]]+)\\[\\]$/;\nconst NESTED_KEY = /^([^[\\]]+)\\[([^[\\]]+)\\]$/;\nconst NESTED_ARRAY_KEY = /^([^[\\]]+)\\[([^[\\]]+)\\]\\[\\]$/;\n\ntype ParsedKey =\n | { kind: \"plain\"; name: string }\n | { kind: \"array\"; name: string }\n | { kind: \"nested\"; name: string; subKey: string }\n | { kind: \"nestedArray\"; name: string; subKey: string };\n\n/**\n * Classify a decoded key.\n *\n * A shape neither side produces — `a[b][c]`, `items[0][name]`, an unbalanced\n * `a[` — falls through to `\"plain\"` and is carried VERBATIM. Those can only come\n * from a URL warlock did not write, and guessing at them is exactly how a\n * decoder drifts from its writer. Carrying the key as text loses nothing.\n */\nfunction parseKey(key: string): ParsedKey {\n const nestedArray = NESTED_ARRAY_KEY.exec(key);\n\n if (nestedArray) {\n return { kind: \"nestedArray\", name: nestedArray[1], subKey: nestedArray[2] };\n }\n\n const array = ARRAY_KEY.exec(key);\n\n if (array) return { kind: \"array\", name: array[1] };\n\n const nested = NESTED_KEY.exec(key);\n\n if (nested) return { kind: \"nested\", name: nested[1], subKey: nested[2] };\n\n return { kind: \"plain\", name: key };\n}\n\n/** A fresh bag with NO prototype. See {@link decode} for why that is not optional. */\nfunction emptyBag<T extends object>(): T {\n return Object.create(null) as T;\n}\n\nfunction isBag(value: unknown): value is QueryStringNested {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The array living at `container[name]`, created if it is not there yet.\n *\n * A conflicting earlier shape is REPLACED rather than written into. `?a=1&a[]=2`\n * is not something the encoder can emit, so it is a foreign URL contradicting\n * itself; appending to a string would be a silent no-op, and last-shape-wins at\n * least matches how `repeatedKeys: \"last\"` resolves the scalar version.\n */\nfunction arrayAt(container: Record<string, unknown>, name: string): string[] {\n const existing = container[name];\n\n if (Array.isArray(existing)) return existing;\n\n const created: string[] = [];\n\n container[name] = created;\n\n return created;\n}\n\n/** The bag living at `result[name]`, created if absent. Same last-shape-wins rule. */\nfunction bagAt(result: QueryStringObject, name: string): QueryStringNested {\n const existing = result[name];\n\n if (isBag(existing)) return existing;\n\n const created = emptyBag<QueryStringNested>();\n\n result[name] = created;\n\n return created;\n}\n\n/**\n * The single decode path. Every reader below goes through here.\n *\n * Every container has a NULL PROTOTYPE — the result and each `key[sub]` bag.\n * Query keys are attacker-controlled, and assigning `?__proto__=x` onto a `{}`\n * literal hits the inherited setter, which DISCARDS the key: data loss with no\n * error. Bracket parsing makes this sharper than it was when this decoder was\n * flat, because `?filter[__proto__]=x` now reaches a nested container too —\n * which is why `bagAt` builds with `Object.create(null)` rather than `{}`.\n * MRR's parser walks `key.split(\"[\")` onto plain objects and needs the blocklist\n * at query-string-parsers.ts:7 as a result; with no prototype there is no setter\n * to hit and the key is stored as the ordinary data it is.\n */\nfunction decode(source: string): QueryStringObject {\n const pairs = searchPairsOf(source);\n const result = emptyBag<QueryStringObject>();\n\n if (pairs === \"\") return result;\n\n const { repeatedKeys } = currentOptions();\n\n for (const [key, value] of new URLSearchParams(pairs)) {\n const parsed = parseKey(key);\n\n if (parsed.kind === \"array\") {\n arrayAt(result, parsed.name).push(value);\n continue;\n }\n\n if (parsed.kind === \"nestedArray\") {\n arrayAt(bagAt(result, parsed.name), parsed.subKey).push(value);\n continue;\n }\n\n if (parsed.kind === \"nested\") {\n // Last wins. The encoder cannot repeat a `key[sub]` pair — `Object.entries`\n // yields each sub-key once — so this only arises from a foreign URL, and\n // `repeatedKeys` deliberately does not reach here (QueryStringOptions).\n bagAt(result, parsed.name)[parsed.subKey] = value;\n continue;\n }\n\n if (!(parsed.name in result)) {\n result[parsed.name] = repeatedKeys === \"array\" ? [value] : value;\n continue;\n }\n\n if (repeatedKeys === \"first\") continue;\n\n if (repeatedKeys === \"last\") {\n result[parsed.name] = value;\n continue;\n }\n\n arrayAt(result, parsed.name).push(value);\n }\n\n return result;\n}\n\n/**\n * Reading the current query string, and any query string.\n *\n * Named for `@mongez/react-router`'s object so the familiar calls keep working;\n * the implementation is not ported — see the module header for what changed and\n * why.\n */\nexport const queryString = {\n /**\n * The current document's query string, decoded.\n *\n * On the server this is `{}`, because the browser location is the only source\n * this module has and a per-request one would be module state two concurrent\n * requests could race over (route-table.ts:10-25).\n *\n * That makes it a HYDRATION HAZARD in a component: the server renders `{}`\n * and the browser renders the real values, so the two trees differ. In a\n * component, take the query from the page's own props and hand it to\n * {@link queryString.parse}, which is universal. `all()` is for browser-only\n * code — an event handler, an effect, a client-side helper.\n */\n all(): QueryStringObject {\n return decode(browserSearch());\n },\n\n /**\n * Decode a query string that was handed to you.\n *\n * Universal: it reads no globals, so this is the entry point that is safe on\n * the server. Accepts a bare pair list, a leading `?`, a path, or a full URL.\n */\n parse(search: string): QueryStringObject {\n return decode(search);\n },\n\n /**\n * One key from the current query string.\n *\n * PRESENCE, not truthiness. MRR returns `all[key] || defaultValue`\n * (query-string.ts:43), which hands back the default for `?a=` — so a\n * deliberately-cleared filter reads as though it was never set, and the page\n * shows the default instead of the empty state. Here `?a=` returns `\"\"`, and\n * only an absent key returns the default.\n *\n * @param defaultValue returned only when the key is absent. Defaults to\n * `null`, as MRR's does.\n */\n get<T = null>(key: string, defaultValue: T = null as T): QueryStringValue | T {\n const all = decode(browserSearch());\n\n return key in all ? all[key] : defaultValue;\n },\n\n /**\n * The current query string verbatim, without the leading `?`.\n *\n * `\"\"` on the server, and `\"\"` when there is no query — the same two cases\n * `queryStringOf` collapses when it writes.\n */\n toString(): string {\n return searchPairsOf(browserSearch());\n },\n};\n"],"mappings":";;;;;;;;AAqHA,IAAa,gCAAb,cAAmD,MAAM;CAErC;CACA;CAFlB,AAAO,YACL,AAAgB,UAChB,AAAgB,OAChB;EACA,MACE,sBAAsB,MAAM,yBAAyB,SAAS,6fAOhE;EAXgB;EACA;EAWhB,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;AAcA,SAAS,SAAS,OAAwB;CACxC,MAAM,aAAc,MAAiC;CAErD,OAAO,OAAO,eAAe,cAAc,eAAe,OAAO,UAAU;AAC7E;;AAGA,SAAS,YAA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;;CAczB,MAAyB;EACvB,OAAO,OAAO,cAAc,CAAC;CAC/B;;;;;;;CAQA,MAAM,QAAmC;EACvC,OAAO,OAAO,MAAM;CACtB;;;;;;;;;;;;;CAcA,IAAc,KAAa,eAAkB,MAAiC;EAC5E,MAAM,MAAM,OAAO,cAAc,CAAC;EAElC,OAAO,OAAO,MAAM,IAAI,OAAO;CACjC;;;;;;;CAQA,WAAmB;EACjB,OAAO,cAAc,cAAc,CAAC;CACtC;AACF"}
|
|
1
|
+
{"version":3,"file":"query-string.mjs","names":[],"sources":["../../../../../../../web/src/routing/query-string.ts"],"sourcesContent":["/**\n * The query string: BOTH directions, one grammar, one file.\n *\n * ── The rule this module exists to obey ──────────────────────────────────────\n *\n * `queryStringOf` is what `href(name, params, query)` appends, and therefore\n * what every `<Link>` puts in the document; `queryString.parse` is what reads it\n * back. They live together because a second, independently-written\n * query-string implementation would mean one thing writes URLs and a different\n * thing reads them. Query-string libraries genuinely disagree about arrays,\n * nested objects and space escaping, so the moment the two drift the round trip\n * loses data SILENTLY — the wrong value renders and no error is raised\n * anywhere. That is the two-route-matchers failure class (canon 9c8f878b) one\n * layer down.\n *\n * Escaping is not two rules that agree today. Both directions stand on\n * `URLSearchParams`: the encoder builds one and calls `.toString()`, the decoder\n * hands the string back to `new URLSearchParams(...)`. `+`-for-space and every\n * percent-encoding rule are therefore ONE rule and cannot drift.\n *\n * ── The grammar, and why it is not ours to choose ────────────────────────────\n *\n * Structure — arrays and nested objects — is the part `URLSearchParams` has no\n * opinion about, so it was read off the SERVER rather than invented. Warlock is\n * a backend framework and core already parses query strings for list endpoints\n * and filters; a client that emitted anything else would not have fixed this\n * module's bug, it would have moved it across the wire where it is harder to\n * see. Measured, with file:line, in\n * `reports/query-grammar-findings-2026-08-24.md`:\n *\n * - `core/src/http/server.ts:14-36` configures Fastify with NO\n * `querystringParser`, so find-my-way's `fast-querystring` default applies:\n * flat keys, `+` is a space, a repeated key collapses to an array.\n * - `core/src/http/request.ts:491` then runs `request.query` through\n * `parseBody` — the SAME bracket-aware parser as the request body.\n * - `core/src/http/request.ts:516-520` reads `key[]` as an array marker, and\n * `:568-575` wraps a single `key[]=a` into the one-element array `[\"a\"]`.\n * - `core/src/http/request.ts:557-561` turns `key[sub]=v` into\n * `{key: {sub: v}}`, one level deep.\n *\n * So: `tags[]=a&tags[]=b` for arrays, `filter[status]=active` for objects,\n * `filter[tags][]=a` for an array inside an object. Bare repeated keys\n * (`tags=a&tags=b`) would also reach core as an array, but only at cardinality\n * two or more — `tags=a` comes back as the scalar `\"a\"`, and a shape that\n * changes with the number of matches is a `TypeError` waiting for the day a\n * filter matches one item. `[]` is the form core wrote a branch for.\n *\n * ── What is REFUSED, and why refusing is the safe answer ─────────────────────\n *\n * Two levels of nesting is not a gap in core, it is measured data loss:\n * `a[b][c]=x` takes the `][` branch at `core/src/http/request.ts:528-551`,\n * computes `Number(\"b\")` as `NaN`, and the value lands on a `NaN` index and\n * vanishes — core answers `{a: []}`. So the encoder throws\n * {@link UnserializableQueryValueError} rather than write it. `href()` already\n * throws on a missing route parameter rather than emit a link that renders\n * correctly and 404s; this is the same call.\n *\n * ── What the encoder still normalises, and what that costs ───────────────────\n *\n * Leaf values are serialised with `String(value)`, so every value arrives back\n * as a `string`: `href(\"p\", {}, { page: 2 })` writes `?page=2`, and `2` and\n * `\"2\"` are the same URL. The round-trip law that can actually hold is\n * `parse(encode(query)) === query with String() applied to its leaves and\n * undefined dropped`, and that is what the spec asserts. Asserting anything\n * stronger would be asserting a decoder that guesses types, which is how\n * `?zip=01234` becomes the number `1234`.\n *\n * The decoder does NOT split values on `,`: that would turn the legitimate\n * string `\"Doe, John\"` into `[\"Doe\", \" John\"]`, trading a visible limitation for\n * a silent corruption of ordinary data. Arrays are carried by `[]`, which is\n * unambiguous, so there is nothing left to guess at.\n *\n * ── Universal by requirement, not by accident ────────────────────────────────\n *\n * `web` renders on the server first, so every export here is safe to import and\n * to CALL with no DOM. `@mongez/react-router`'s equivalent reads\n * `window.location.search` unguarded (query-string.ts:22) and throws under SSR.\n * Here the browser-only readers return their empty answer instead — see\n * `queryString.all` for the hydration caveat that comes with that.\n *\n * ── Still NOT here: `toQueryString` and `update` ─────────────────────────────\n *\n * MRR exposes `toQueryString(params)` and `update(params)`, which SERIALISE.\n * The serialiser they need is no longer module-private — `queryStringOf` is\n * exported from here — so the old blocker is gone. What remains is that\n * `web/src/index.ts` does not re-export it yet, and the barrel is owned\n * elsewhere. That is a one-line follow-up, not a redesign.\n */\n\n/** A decoded leaf. Always a `string` — see the header on `String(value)`. */\nexport type QueryStringLeaf = string;\n\n/**\n * The inside of a `key[sub]` bag: one level deep, exactly as far as core parses.\n *\n * There is no deeper case to model. `key[sub][deeper]` is refused by the encoder\n * and carried verbatim as a literal key by the decoder, so a nested bag only\n * ever holds a leaf or an array of leaves.\n */\nexport type QueryStringNested = Record<string, QueryStringLeaf | QueryStringLeaf[]>;\n\n/** A decoded value: a leaf, a `key[]` array, or a `key[sub]` bag. */\nexport type QueryStringValue = QueryStringLeaf | QueryStringLeaf[] | QueryStringNested;\n\n/** A decoded query string. */\nexport type QueryStringObject = Record<string, QueryStringValue>;\n\n/** What {@link queryStringOf} accepts. Values are validated, not trusted. */\nexport type QueryStringInput = Readonly<Record<string, unknown>>;\n\n/**\n * Thrown when a query value has a shape the wire format cannot carry.\n *\n * Deliberately LOUD. The alternative is emitting something core silently\n * mangles — `a[b][c]=x` arrives as `{a: []}` — which is this defect all over\n * again, one layer further from where anyone would look for it.\n */\nexport class UnserializableQueryValueError extends Error {\n public constructor(\n public readonly queryKey: string,\n public readonly shape: string,\n ) {\n super(\n `Warlock cannot put ${shape} in a query string at \"${queryKey}\". The wire format is the ` +\n \"one @warlock.js/core parses (core/src/http/request.ts:503-591): a value may be a \" +\n \"scalar, an array of scalars (`key[]=a&key[]=b`), or an object one level deep whose \" +\n \"values are scalars or arrays of scalars (`key[sub]=a`, `key[sub][]=a`). Anything \" +\n \"deeper is refused rather than written, because core reads `a[b][c]=x` back as \" +\n \"`{a: []}` — the value is destroyed on arrival with no error. Flatten the value, or \" +\n \"JSON.stringify it into a single scalar and parse it on the server.\",\n );\n this.name = \"UnserializableQueryValueError\";\n }\n}\n\n/**\n * Is this a BAG of query keys, as opposed to a value with its own string form?\n *\n * A `Date`, a `URL` or anything else carrying its own `toString` is a scalar\n * here — `String(value)` is meaningful for it, and turning it into\n * `since[getTime]=...` would be absurd. A plain object, or a class instance that\n * would otherwise stringify to the useless `\"[object Object]\"`, is a bag and\n * gets enumerated.\n *\n * The `typeof` check matters for null-prototype objects: they have no\n * `toString` at all, and `String()` on one THROWS.\n */\nfunction isKeyBag(value: object): boolean {\n const stringForm = (value as { toString?: unknown }).toString;\n\n return typeof stringForm !== \"function\" || stringForm === Object.prototype.toString;\n}\n\n/** Refuse anything that is not a leaf. Used everywhere a leaf is the only legal shape. */\nfunction requireLeaf(key: string, value: unknown): void {\n if (Array.isArray(value)) {\n throw new UnserializableQueryValueError(key, \"a nested array\");\n }\n\n if (typeof value === \"object\" && value !== null && isKeyBag(value)) {\n throw new UnserializableQueryValueError(key, \"a nested object\");\n }\n}\n\n/**\n * Append `key[]=element` per element.\n *\n * An `undefined` element is skipped, matching the top-level rule. Because the\n * `[]` form carries no indices, skipping shortens the array rather than leaving\n * a hole — there is no hole to leave.\n *\n * An EMPTY array appends nothing, so the key is absent from the URL. The format\n * has no way to say \"an array with no elements\": `key[]=` means the one-element\n * array `[\"\"]`, which is a different value. A visible limitation beats a guess.\n */\nfunction appendArray(search: URLSearchParams, key: string, value: readonly unknown[]): void {\n const arrayKey = `${key}[]`;\n\n for (const element of value) {\n if (element === undefined) continue;\n\n requireLeaf(arrayKey, element);\n\n search.append(arrayKey, String(element));\n }\n}\n\n/** Append `key[sub]=value`, or `key[sub][]=value` when the member is an array. */\nfunction appendBag(search: URLSearchParams, key: string, value: object): void {\n for (const [subKey, subValue] of Object.entries(value)) {\n if (subValue === undefined) continue;\n\n const nestedKey = `${key}[${subKey}]`;\n\n if (Array.isArray(subValue)) {\n appendArray(search, nestedKey, subValue);\n continue;\n }\n\n requireLeaf(nestedKey, subValue);\n\n search.append(nestedKey, String(subValue));\n }\n}\n\n/**\n * Serialise a query object to a search string, INCLUDING the leading `?`.\n *\n * Returns `\"\"` — not `\"?\"` — when there is nothing to write, so the result can\n * always be concatenated onto a path. `href()` is the primary caller; the\n * grammar it emits is the one core parses, and the whole justification is in the\n * module header.\n *\n * @throws {UnserializableQueryValueError} when a value nests deeper than the\n * wire format can carry.\n */\nexport function queryStringOf(query: QueryStringInput | undefined): string {\n if (query === undefined) return \"\";\n\n const search = new URLSearchParams();\n\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n\n if (Array.isArray(value)) {\n appendArray(search, key, value);\n continue;\n }\n\n if (typeof value === \"object\" && value !== null && isKeyBag(value)) {\n appendBag(search, key, value);\n continue;\n }\n\n search.append(key, String(value));\n }\n\n const serialized = search.toString();\n\n return serialized === \"\" ? \"\" : `?${serialized}`;\n}\n\n/**\n * What to do when the same PLAIN key appears more than once, e.g. `?tag=a&tag=b`.\n *\n * - `\"last\"` — keep the final occurrence. Matches `URLSearchParams.get()`, the\n * read side of the primitive the encoder writes with, and keeps every value a\n * `string`.\n * - `\"first\"` — keep the earliest occurrence.\n * - `\"array\"` — collect every occurrence. Under this strategy a key that occurs\n * ONCE is still an array of one, because a shape that changes with the number\n * of values is a `TypeError` waiting for the day a filter matches a single\n * item.\n *\n * It does NOT govern `key[]` or `key[sub]`; those are shapes the encoder writes\n * deliberately, and their meaning is fixed. See {@link QueryStringOptions}.\n */\nexport type RepeatedKeyStrategy = \"last\" | \"first\" | \"array\";\n\n/**\n * The whole option surface.\n *\n * ── Why this is one flag and not MRR's pluggable parsers ─────────────────────\n *\n * MRR's `setQueryStringOptions` swaps `objectParser` and `stringParser`\n * (query-string.ts:10-15). Neither survives contact with a fixed, shared\n * encoder:\n *\n * - A pluggable `objectParser` is a licence to install a READER that disagrees\n * with the writer. It is precisely the silent round-trip break this module\n * was written to prevent, offered as a supported API.\n * - A pluggable `stringParser` would be worse: it cannot reach `href()`, which\n * calls `queryStringOf` directly with no hook. Setting it would change what\n * this module emits while every `<Link>` on the page kept emitting the old\n * format — two writers, disagreeing, by configuration.\n *\n * `repeatedKeys` is safe for one specific reason, and the reason survived the\n * move to bracket notation: `queryStringOf` iterates `Object.entries`, so it can\n * never emit a duplicate PLAIN key. It now does emit duplicate `key[]` pairs —\n * that is how an array is written — but those go down the array branch of the\n * decoder, which this flag does not touch. Were the flag to govern the bracket\n * forms as well, `repeatedKeys: \"array\"` would decode `filter[x]=1` as\n * `{filter: {x: [\"1\"]}}` and break the round trip BY CONFIGURATION.\n *\n * So the flag still decides only something the encoder has no opinion about: a\n * repeated plain key, which can only arrive from a URL this package did not\n * write — hand-typed, external links, `GET` forms.\n *\n * Set it at BOOT, not per request: this is process-global config, and a\n * request-scoped write would be read by whatever request happens to be\n * rendering (the defect catalogued at route-table.ts:10-25).\n */\nexport type QueryStringOptions = {\n readonly repeatedKeys?: RepeatedKeyStrategy;\n};\n\ntype ResolvedQueryStringOptions = Required<QueryStringOptions>;\n\nconst DEFAULT_OPTIONS: ResolvedQueryStringOptions = {\n repeatedKeys: \"last\",\n};\n\n/**\n * Held on `globalThis`, not in a module binding, for the reason measured and\n * written up at route-table.ts:43-65: in dev the process runs two module graphs\n * over these files (tsx/Node and Vite's SSR runner), so a `let` written by boot\n * code is not the `let` a component reads. A split here would be quiet — the\n * second graph would silently fall back to the defaults and decode a repeated\n * key the other way.\n */\nconst OPTIONS_SLOT = Symbol.for(\"warlock.web.queryStringOptions\");\n\ntype OptionsHost = typeof globalThis & {\n [OPTIONS_SLOT]?: ResolvedQueryStringOptions;\n};\n\nfunction currentOptions(): ResolvedQueryStringOptions {\n return (globalThis as OptionsHost)[OPTIONS_SLOT] ?? DEFAULT_OPTIONS;\n}\n\n/**\n * Merge query-string options over the current ones.\n *\n * Named for `@mongez/react-router`'s function so migrating call sites keep\n * compiling; the OPTIONS are deliberately narrower, and `QueryStringOptions`\n * explains exactly which ones were refused and why.\n */\nexport function setQueryStringOptions(options: QueryStringOptions): void {\n (globalThis as OptionsHost)[OPTIONS_SLOT] = { ...currentOptions(), ...options };\n}\n\n/**\n * Drop back to the defaults.\n *\n * Exists because the options are process-global: a test that set one would\n * otherwise leak it into every later test in the same worker, passing in file\n * order and failing under `--shuffle`. Same reasoning as `resetRouteTable`.\n */\nexport function resetQueryStringOptions(): void {\n delete (globalThis as OptionsHost)[OPTIONS_SLOT];\n}\n\n/**\n * The search string of the current document, or `\"\"` when there is no document.\n *\n * The `typeof` guard is the SSR contract: no export in this module may touch a\n * DOM global without one.\n */\nfunction browserSearch(): string {\n if (typeof window === \"undefined\") return \"\";\n\n return window.location?.search ?? \"\";\n}\n\n/**\n * Reduce anything search-shaped to the pairs themselves.\n *\n * Accepts `\"?a=1\"`, `\"a=1\"`, `\"/path?a=1\"` and a full URL, because\n * `location.href`, `location.search` and a hand-written literal all turn up at\n * this door and `new URLSearchParams(\"/path?a=1\")` would answer with the key\n * `\"/path?a\"` — a wrong answer with no error. Cutting at the first `?` and the\n * first `#` is safe rather than heuristic: `queryStringOf` percent-encodes both\n * characters inside values (`%3F`, `%23`), so a literal one is always a\n * delimiter.\n */\nfunction searchPairsOf(source: string): string {\n const withoutHash = source.split(\"#\", 1)[0];\n const questionMark = withoutHash.indexOf(\"?\");\n\n return questionMark === -1 ? withoutHash : withoutHash.slice(questionMark + 1);\n}\n\n/**\n * The three key shapes the encoder writes. Everything else is a literal key.\n *\n * The character classes exclude brackets, so each pattern matches exactly one\n * shape: `tags[]` cannot satisfy `NESTED`, and `a[b][c]` satisfies none of them.\n */\nconst ARRAY_KEY = /^([^[\\]]+)\\[\\]$/;\nconst NESTED_KEY = /^([^[\\]]+)\\[([^[\\]]+)\\]$/;\nconst NESTED_ARRAY_KEY = /^([^[\\]]+)\\[([^[\\]]+)\\]\\[\\]$/;\n\ntype ParsedKey =\n | { kind: \"plain\"; name: string }\n | { kind: \"array\"; name: string }\n | { kind: \"nested\"; name: string; subKey: string }\n | { kind: \"nestedArray\"; name: string; subKey: string };\n\n/**\n * Classify a decoded key.\n *\n * A shape neither side produces — `a[b][c]`, `items[0][name]`, an unbalanced\n * `a[` — falls through to `\"plain\"` and is carried VERBATIM. Those can only come\n * from a URL warlock did not write, and guessing at them is exactly how a\n * decoder drifts from its writer. Carrying the key as text loses nothing.\n */\nfunction parseKey(key: string): ParsedKey {\n const nestedArray = NESTED_ARRAY_KEY.exec(key);\n\n if (nestedArray) {\n return { kind: \"nestedArray\", name: nestedArray[1], subKey: nestedArray[2] };\n }\n\n const array = ARRAY_KEY.exec(key);\n\n if (array) return { kind: \"array\", name: array[1] };\n\n const nested = NESTED_KEY.exec(key);\n\n if (nested) return { kind: \"nested\", name: nested[1], subKey: nested[2] };\n\n return { kind: \"plain\", name: key };\n}\n\n/** A fresh bag with NO prototype. See {@link decode} for why that is not optional. */\nfunction emptyBag<T extends object>(): T {\n return Object.create(null) as T;\n}\n\nfunction isBag(value: unknown): value is QueryStringNested {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The array living at `container[name]`, created if it is not there yet.\n *\n * A conflicting earlier shape is REPLACED rather than written into. `?a=1&a[]=2`\n * is not something the encoder can emit, so it is a foreign URL contradicting\n * itself; appending to a string would be a silent no-op, and last-shape-wins at\n * least matches how `repeatedKeys: \"last\"` resolves the scalar version.\n */\nfunction arrayAt(container: Record<string, unknown>, name: string): string[] {\n const existing = container[name];\n\n if (Array.isArray(existing)) return existing;\n\n const created: string[] = [];\n\n container[name] = created;\n\n return created;\n}\n\n/** The bag living at `result[name]`, created if absent. Same last-shape-wins rule. */\nfunction bagAt(result: QueryStringObject, name: string): QueryStringNested {\n const existing = result[name];\n\n if (isBag(existing)) return existing;\n\n const created = emptyBag<QueryStringNested>();\n\n result[name] = created;\n\n return created;\n}\n\n/**\n * The single decode path. Every reader below goes through here.\n *\n * Every container has a NULL PROTOTYPE — the result and each `key[sub]` bag.\n * Query keys are attacker-controlled, and assigning `?__proto__=x` onto a `{}`\n * literal hits the inherited setter, which DISCARDS the key: data loss with no\n * error. Bracket parsing makes this sharper than it was when this decoder was\n * flat, because `?filter[__proto__]=x` now reaches a nested container too —\n * which is why `bagAt` builds with `Object.create(null)` rather than `{}`.\n * MRR's parser walks `key.split(\"[\")` onto plain objects and needs the blocklist\n * at query-string-parsers.ts:7 as a result; with no prototype there is no setter\n * to hit and the key is stored as the ordinary data it is.\n */\nfunction decode(source: string): QueryStringObject {\n const pairs = searchPairsOf(source);\n const result = emptyBag<QueryStringObject>();\n\n if (pairs === \"\") return result;\n\n const { repeatedKeys } = currentOptions();\n\n for (const [key, value] of new URLSearchParams(pairs)) {\n const parsed = parseKey(key);\n\n if (parsed.kind === \"array\") {\n arrayAt(result, parsed.name).push(value);\n continue;\n }\n\n if (parsed.kind === \"nestedArray\") {\n arrayAt(bagAt(result, parsed.name), parsed.subKey).push(value);\n continue;\n }\n\n if (parsed.kind === \"nested\") {\n // Last wins. The encoder cannot repeat a `key[sub]` pair — `Object.entries`\n // yields each sub-key once — so this only arises from a foreign URL, and\n // `repeatedKeys` deliberately does not reach here (QueryStringOptions).\n bagAt(result, parsed.name)[parsed.subKey] = value;\n continue;\n }\n\n if (!(parsed.name in result)) {\n result[parsed.name] = repeatedKeys === \"array\" ? [value] : value;\n continue;\n }\n\n if (repeatedKeys === \"first\") continue;\n\n if (repeatedKeys === \"last\") {\n result[parsed.name] = value;\n continue;\n }\n\n arrayAt(result, parsed.name).push(value);\n }\n\n return result;\n}\n\n/**\n * Reading the current query string, and any query string.\n *\n * Named for `@mongez/react-router`'s object so the familiar calls keep working;\n * the implementation is not ported — see the module header for what changed and\n * why.\n */\nexport const queryString = {\n /**\n * The current document's query string, decoded.\n *\n * On the server this is `{}`, because the browser location is the only source\n * this module has and a per-request one would be module state two concurrent\n * requests could race over (route-table.ts:10-25).\n *\n * That makes it a HYDRATION HAZARD in a component: the server renders `{}`\n * and the browser renders the real values, so the two trees differ. In a\n * component, take the query from the page's own props and hand it to\n * {@link queryString.parse}, which is universal. `all()` is for browser-only\n * code — an event handler, an effect, a client-side helper.\n */\n all(): QueryStringObject {\n return decode(browserSearch());\n },\n\n /**\n * Decode a query string that was handed to you.\n *\n * Universal: it reads no globals, so this is the entry point that is safe on\n * the server. Accepts a bare pair list, a leading `?`, a path, or a full URL.\n */\n parse(search: string): QueryStringObject {\n return decode(search);\n },\n\n /**\n * One key from the current query string.\n *\n * PRESENCE, not truthiness. MRR returns `all[key] || defaultValue`\n * (query-string.ts:43), which hands back the default for `?a=` — so a\n * deliberately-cleared filter reads as though it was never set, and the page\n * shows the default instead of the empty state. Here `?a=` returns `\"\"`, and\n * only an absent key returns the default.\n *\n * @param defaultValue returned only when the key is absent. Defaults to\n * `null`, as MRR's does.\n */\n get<T = null>(key: string, defaultValue: T = null as T): QueryStringValue | T {\n const all = decode(browserSearch());\n\n return key in all ? all[key] : defaultValue;\n },\n\n /**\n * The current query string verbatim, without the leading `?`.\n *\n * `\"\"` on the server, and `\"\"` when there is no query — the same two cases\n * `queryStringOf` collapses when it writes.\n */\n toString(): string {\n return searchPairsOf(browserSearch());\n },\n};\n"],"mappings":";;;;;;;;AAqHA,IAAa,gCAAb,cAAmD,MAAM;CAErC;CACA;CAFlB,AAAO,YACL,AAAgB,UAChB,AAAgB,OAChB;EACA,MACE,sBAAsB,MAAM,yBAAyB,SAAS,6fAOhE;EAXgB;EACA;EAWhB,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;AAcA,SAAS,SAAS,OAAwB;CACxC,MAAM,aAAc,MAAiC;CAErD,OAAO,OAAO,eAAe,cAAc,eAAe,OAAO,UAAU;AAC7E;;AAGA,SAAS,YAAY,KAAa,OAAsB;CACtD,IAAI,MAAM,QAAQ,KAAK,GACrB,MAAM,IAAI,8BAA8B,KAAK,gBAAgB;CAG/D,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,SAAS,KAAK,GAC/D,MAAM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cA,IAAc,KAAa,eAAkB,MAAiC;EAC5E,MAAM,MAAM,OAAO,cAAc,CAAC;EAElC,OAAO,OAAO,MAAM,IAAI,OAAO;CACjC;;;;;;;CAQA,WAAmB;EACjB,OAAO,cAAc,cAAc,CAAC;CACtC;AACF"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
//#region ../web/src/routing/route-identity.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Route identity — the single, pure implementation of "what is this page's
|
|
4
|
+
* route path and name". The dev installer
|
|
5
|
+
* (`web/src/server/install-page-routes.ts`), the production manifest
|
|
6
|
+
* installer (`web/src/server/install-page-routes-from-manifest.ts`) and
|
|
7
|
+
* discovery (`web/src/build/discover-pages.ts`) each hand-derived this on
|
|
8
|
+
* their own until all three were made to delegate here.
|
|
9
|
+
*
|
|
10
|
+
* {@link resolvePageRouteName} is the ONE answer to "what is this page's
|
|
11
|
+
* route name": an explicit `name` on the declared `route` export wins,
|
|
12
|
+
* otherwise the name comes from the page's own FILE PATH
|
|
13
|
+
* (`deriveFilesystemRouteName`) — never from `route.path`. The route name is
|
|
14
|
+
* an identity key (`routing/route-table.ts`'s lookup key, `components/link.ts`,
|
|
15
|
+
* `server/render-page.ts`, the generated client registry and the hydration
|
|
16
|
+
* payload all address a page by it), and an identity key must be stable under
|
|
17
|
+
* the change most likely to happen to a page — its URL, renamed for SEO,
|
|
18
|
+
* localization or restructuring. A file path is also unique by construction,
|
|
19
|
+
* while a declared `path: "/"` yields no usable name at all.
|
|
20
|
+
*
|
|
21
|
+
* Pure string logic only: no `fs`, no `path`, no Node built-ins. Every input
|
|
22
|
+
* this module accepts is already CANONICAL — a POSIX, app-root-relative
|
|
23
|
+
* source path (e.g. `"src/web/index.page.tsx"`).
|
|
24
|
+
*
|
|
25
|
+
* {@link canonicalizeRouteExport} is also the ONE seam every declared
|
|
26
|
+
* `route.path` passes through on its way into either installer
|
|
27
|
+
* (`install-page-routes.ts`, `install-page-routes-from-manifest.ts`), so it is
|
|
28
|
+
* where `../routing/page-route-grammar.ts`'s `classifyPageRoutePath` is
|
|
29
|
+
* applied: a rejected path raises {@link PageRoutePathNotSupportedError}
|
|
30
|
+
* naming the offending page file, rather than being published literally.
|
|
31
|
+
*
|
|
32
|
+
* Well-formedness of the declared `route` export itself (is it a string or an
|
|
33
|
+
* object, does the object have a `path`) is the extractor's problem — already
|
|
34
|
+
* rejected at build before either derivation function here is called.
|
|
35
|
+
*
|
|
36
|
+
* DIRECTORY CONTRACT — applies to everything in `web/src/routing/`: nothing
|
|
37
|
+
* here may import `node:fs`, `node:path`, `vite`, or `fastify`. Modules in
|
|
38
|
+
* this directory receive canonical values and trust nothing — they assert
|
|
39
|
+
* rather than trust, but they never repair. A module that needs the
|
|
40
|
+
* filesystem does not belong here. The purity is deliberate: it keeps these
|
|
41
|
+
* modules consumable from the dev server, the build, the production runtime,
|
|
42
|
+
* and — if ever needed — the browser client, without dragging any of those
|
|
43
|
+
* environments along.
|
|
44
|
+
*/
|
|
45
|
+
/**
|
|
46
|
+
* A page's opt-in into shared-cache storage for its document AND its data
|
|
47
|
+
* representation (`x-warlock-data`) — the two must never diverge, because a
|
|
48
|
+
* cacheable data payload leaks exactly what an uncacheable document was
|
|
49
|
+
* protecting (`../server/create-page-route-handler.ts`).
|
|
50
|
+
*
|
|
51
|
+
* `public: true` is not a flag with a `false` counterpart: the framework is
|
|
52
|
+
* closed by default (`../server/response-cache-floor.ts`), so the only
|
|
53
|
+
* meaningful state this object can express is "yes, cache me" — a page that
|
|
54
|
+
* wants the default simply omits `cache` entirely. `maxAge` has no framework
|
|
55
|
+
* default and never will: a route's freshness window is a decision only the
|
|
56
|
+
* route's author can make safely, and guessing one would be exactly the kind
|
|
57
|
+
* of silent, environment-dependent behaviour this feature exists to remove.
|
|
58
|
+
* Both keys are required — see {@link InvalidPageCacheOptInError}.
|
|
59
|
+
*
|
|
60
|
+
* Shaped as an object, not a boolean or a bare number, so a later addition
|
|
61
|
+
* (e.g. CDN surrogate keys) extends it without a breaking change.
|
|
62
|
+
*/
|
|
63
|
+
type PageCacheOptIn = {
|
|
64
|
+
public: true; /** Freshness window in seconds, emitted as `Cache-Control: public, max-age=<maxAge>`. */
|
|
65
|
+
maxAge: number;
|
|
66
|
+
};
|
|
67
|
+
//#endregion
|
|
68
|
+
export { PageCacheOptIn };
|
|
69
|
+
//# sourceMappingURL=route-identity.d.mts.map
|
|
@@ -1,68 +1,124 @@
|
|
|
1
|
+
import { deriveFilesystemRouteName } from "./filesystem-route.mjs";
|
|
2
|
+
import { PageRoutePathNotSupportedError, classifyPageRoutePath } from "./page-route-grammar.mjs";
|
|
3
|
+
|
|
1
4
|
//#region ../web/src/routing/route-identity.ts
|
|
2
5
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
+
* Route identity — the single, pure implementation of "what is this page's
|
|
7
|
+
* route path and name". The dev installer
|
|
8
|
+
* (`web/src/server/install-page-routes.ts`), the production manifest
|
|
9
|
+
* installer (`web/src/server/install-page-routes-from-manifest.ts`) and
|
|
10
|
+
* discovery (`web/src/build/discover-pages.ts`) each hand-derived this on
|
|
11
|
+
* their own until all three were made to delegate here.
|
|
12
|
+
*
|
|
13
|
+
* {@link resolvePageRouteName} is the ONE answer to "what is this page's
|
|
14
|
+
* route name": an explicit `name` on the declared `route` export wins,
|
|
15
|
+
* otherwise the name comes from the page's own FILE PATH
|
|
16
|
+
* (`deriveFilesystemRouteName`) — never from `route.path`. The route name is
|
|
17
|
+
* an identity key (`routing/route-table.ts`'s lookup key, `components/link.ts`,
|
|
18
|
+
* `server/render-page.ts`, the generated client registry and the hydration
|
|
19
|
+
* payload all address a page by it), and an identity key must be stable under
|
|
20
|
+
* the change most likely to happen to a page — its URL, renamed for SEO,
|
|
21
|
+
* localization or restructuring. A file path is also unique by construction,
|
|
22
|
+
* while a declared `path: "/"` yields no usable name at all.
|
|
23
|
+
*
|
|
24
|
+
* Pure string logic only: no `fs`, no `path`, no Node built-ins. Every input
|
|
25
|
+
* this module accepts is already CANONICAL — a POSIX, app-root-relative
|
|
26
|
+
* source path (e.g. `"src/web/index.page.tsx"`).
|
|
27
|
+
*
|
|
28
|
+
* {@link canonicalizeRouteExport} is also the ONE seam every declared
|
|
29
|
+
* `route.path` passes through on its way into either installer
|
|
30
|
+
* (`install-page-routes.ts`, `install-page-routes-from-manifest.ts`), so it is
|
|
31
|
+
* where `../routing/page-route-grammar.ts`'s `classifyPageRoutePath` is
|
|
32
|
+
* applied: a rejected path raises {@link PageRoutePathNotSupportedError}
|
|
33
|
+
* naming the offending page file, rather than being published literally.
|
|
34
|
+
*
|
|
35
|
+
* Well-formedness of the declared `route` export itself (is it a string or an
|
|
36
|
+
* object, does the object have a `path`) is the extractor's problem — already
|
|
37
|
+
* rejected at build before either derivation function here is called.
|
|
38
|
+
*
|
|
39
|
+
* DIRECTORY CONTRACT — applies to everything in `web/src/routing/`: nothing
|
|
40
|
+
* here may import `node:fs`, `node:path`, `vite`, or `fastify`. Modules in
|
|
41
|
+
* this directory receive canonical values and trust nothing — they assert
|
|
42
|
+
* rather than trust, but they never repair. A module that needs the
|
|
43
|
+
* filesystem does not belong here. The purity is deliberate: it keeps these
|
|
44
|
+
* modules consumable from the dev server, the build, the production runtime,
|
|
45
|
+
* and — if ever needed — the browser client, without dragging any of those
|
|
46
|
+
* environments along.
|
|
47
|
+
*/
|
|
48
|
+
/**
|
|
49
|
+
* Raised when a page's `route.cache` is present but malformed — most notably
|
|
50
|
+
* `public: true` with no `maxAge`. The framework refuses to invent a
|
|
51
|
+
* freshness window (see {@link PageCacheOptIn}), so this is a BOOT-TIME
|
|
52
|
+
* failure rather than a silent fallback to `no-store`: a developer who wrote
|
|
53
|
+
* `cache: { public: true }` meant for the route to be cacheable, and serving
|
|
54
|
+
* it `no-store` without a word would be the exact silent-failure class this
|
|
55
|
+
* release exists to kill.
|
|
6
56
|
*/
|
|
7
|
-
var
|
|
8
|
-
|
|
9
|
-
constructor(
|
|
10
|
-
super(`
|
|
11
|
-
this.
|
|
12
|
-
this.name = "
|
|
57
|
+
var InvalidPageCacheOptInError = class extends Error {
|
|
58
|
+
pageFile;
|
|
59
|
+
constructor(pageFile) {
|
|
60
|
+
super(`"${pageFile}" declares \`route.cache\` without a valid opt-in. Both keys are required: write \`cache: { public: true, maxAge: <seconds> }\` — for example \`cache: { public: true, maxAge: 60 }\`. Remove \`cache\` entirely to keep the route \`no-store\` (the default) instead.`);
|
|
61
|
+
this.pageFile = pageFile;
|
|
62
|
+
this.name = "InvalidPageCacheOptInError";
|
|
13
63
|
}
|
|
14
64
|
};
|
|
15
65
|
/**
|
|
66
|
+
* Resolves and validates a declared `route` export's `cache` opt-in.
|
|
67
|
+
*
|
|
68
|
+
* `undefined` — the common case — means "no opt-in", which the caller (the
|
|
69
|
+
* response-cache-floor seam) treats as `no-store`, not as "cacheable with no
|
|
70
|
+
* limit". A malformed opt-in throws {@link InvalidPageCacheOptInError} rather
|
|
71
|
+
* than being coerced or ignored, so a typo in a route's `cache` field fails
|
|
72
|
+
* the build/boot instead of quietly shipping an unintended cache policy.
|
|
73
|
+
*/
|
|
74
|
+
function resolvePageRouteCache(route, pageFile) {
|
|
75
|
+
if (route === void 0 || typeof route === "string") return void 0;
|
|
76
|
+
const { cache } = route;
|
|
77
|
+
if (cache === void 0) return void 0;
|
|
78
|
+
if (cache.public !== true || typeof cache.maxAge !== "number") throw new InvalidPageCacheOptInError(pageFile);
|
|
79
|
+
return cache;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
16
82
|
* Canonicalizes a declared `route` export — string or `{ path, name? }` —
|
|
17
83
|
* into `{ path, name? }`. Requires well-formed input; an export that is
|
|
18
84
|
* neither a string nor an object with a `path` is the extractor's problem,
|
|
19
85
|
* already rejected before this function is ever called.
|
|
86
|
+
*
|
|
87
|
+
* This is also where the declared `path` is validated: `pageFile` names the
|
|
88
|
+
* page whose `route` export is being canonicalized, and a `path` that
|
|
89
|
+
* {@link classifyPageRoutePath} rejects raises
|
|
90
|
+
* {@link PageRoutePathNotSupportedError} naming it — rather than being
|
|
91
|
+
* published literally. Both installers reach every declared path through
|
|
92
|
+
* here, so this is the one place that check has to live.
|
|
20
93
|
*/
|
|
21
|
-
function canonicalizeRouteExport(route) {
|
|
94
|
+
function canonicalizeRouteExport(route, pageFile) {
|
|
95
|
+
const path = typeof route === "string" ? route : route.path;
|
|
96
|
+
const verdict = classifyPageRoutePath(path);
|
|
97
|
+
if (verdict.type === "rejected") throw new PageRoutePathNotSupportedError(pageFile, path, verdict.reason);
|
|
22
98
|
if (typeof route === "string") return { path: route };
|
|
23
99
|
return route.name === void 0 ? { path: route.path } : {
|
|
24
100
|
path: route.path,
|
|
25
101
|
name: route.name
|
|
26
102
|
};
|
|
27
103
|
}
|
|
28
|
-
/** Strips leading and trailing "." characters — mirrors `trim(value, ".")` as used by the installer's `deriveRouteName`. */
|
|
29
|
-
function trimDots(value) {
|
|
30
|
-
return value.replace(/^\.+|\.+$/g, "");
|
|
31
|
-
}
|
|
32
104
|
/**
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
|
|
38
|
-
function moduleSegmentFor(sourceFile) {
|
|
39
|
-
const segments = sourceFile.split("/");
|
|
40
|
-
return segments[1] === "app" ? segments[2] : void 0;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Derives the fallback route name for a page whose declared route carries no
|
|
44
|
-
* `name` — the same derivation the dev installer's `deriveRouteName` applies
|
|
45
|
-
* today (`web/src/server/install-page-routes.ts`), expressed against
|
|
46
|
-
* canonical inputs instead of an absolute file path plus an `appSrcRoot`.
|
|
47
|
-
*
|
|
48
|
-
* The installer only ever calls its derivation for a page under
|
|
49
|
-
* `<appSrcRoot>/app/**`, so a global (`src/web/**`) page has no installer
|
|
50
|
-
* behaviour to mirror; for that case this function instead follows
|
|
51
|
-
* discovery's own convention (`routeNameFor` in `discover-pages.ts`) — no
|
|
52
|
-
* module prefix, and `"index"` when there is nothing left to say at all.
|
|
105
|
+
* Resolves a page's route NAME — the single derivation `install-page-routes.ts`,
|
|
106
|
+
* `install-page-routes-from-manifest.ts` and `discover-pages.ts` all delegate
|
|
107
|
+
* to, so dev, the production manifest installer and build discovery cannot
|
|
108
|
+
* derive three different names for the same page (see the module doc comment
|
|
109
|
+
* for why the file path, not `route.path`, is the source of truth).
|
|
53
110
|
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
111
|
+
* An explicit `name` on `route` always wins. Otherwise the name is derived
|
|
112
|
+
* from `pageFile` via {@link deriveFilesystemRouteName} — `pageFile` must
|
|
113
|
+
* already be canonical: a POSIX path relative to the page's web root (e.g.
|
|
114
|
+
* `"blog/archive.page.tsx"`), the same value each caller already computes as
|
|
115
|
+
* `filesystemPageFileFor`/`webRelativeSourceFile`/`relativePageFile`.
|
|
56
116
|
*/
|
|
57
|
-
function
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
const moduleName = moduleSegmentFor(sourceFile);
|
|
61
|
-
const suffix = trimDots(routePath.replace(/\//g, "."));
|
|
62
|
-
if (moduleName !== void 0) return suffix ? `${moduleName}.${suffix}` : moduleName;
|
|
63
|
-
return suffix || "index";
|
|
117
|
+
function resolvePageRouteName(route, pageFile) {
|
|
118
|
+
if (route === void 0) return deriveFilesystemRouteName(pageFile);
|
|
119
|
+
return canonicalizeRouteExport(route, pageFile).name ?? deriveFilesystemRouteName(pageFile);
|
|
64
120
|
}
|
|
65
121
|
|
|
66
122
|
//#endregion
|
|
67
|
-
export { canonicalizeRouteExport,
|
|
123
|
+
export { canonicalizeRouteExport, resolvePageRouteCache, resolvePageRouteName };
|
|
68
124
|
//# sourceMappingURL=route-identity.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-identity.mjs","names":[],"sources":["../../../../../../../web/src/routing/route-identity.ts"],"sourcesContent":["/**\n * Route identity — the single, pure implementation of \"what is this page's\n * route path and name\". The dev installer\n * (`web/src/server/install-page-routes.ts`), the production manifest\n * installer (`web/src/server/install-page-routes-from-manifest.ts`) and\n * discovery (`web/src/build/discover-pages.ts`) each hand-derived this on\n * their own until all three were made to delegate here.\n *\n * Pure string logic only: no `fs`, no `path`, no Node built-ins. Every input\n * this module accepts is already CANONICAL — a POSIX, app-root-relative\n * source path (e.g. `\"src/app/users/web/account/settings.page.tsx\"` or\n * `\"src/web/index.page.tsx\"`) and an already-validated declared route export.\n * Turning an absolute, OS-specific file path into that canonical form is the\n * caller's job; this module refuses (see {@link NonPosixSourceFilePathError})\n * rather than guess at a normalization.\n *\n * Well-formedness of the declared `route` export itself (is it a string or an\n * object, does the object have a `path`) is the extractor's problem — already\n * rejected at build before either derivation function here is called.\n *\n * DIRECTORY CONTRACT — applies to everything in `web/src/routing/`: nothing\n * here may import `node:fs`, `node:path`, `vite`, or `fastify`. Modules in\n * this directory receive canonical values and trust nothing — they assert\n * rather than trust, but they never repair. A module that needs the\n * filesystem does not belong here. The purity is deliberate: it keeps these\n * modules consumable from the dev server, the build, the production runtime,\n * and — if ever needed — the browser client, without dragging any of those\n * environments along.\n */\n\n/** The shape a page's `route` export may declare — mirrors `PageRouteExport` in `install-page-routes.ts`. */\nexport type DeclaredRouteExport = string | { path: string; name?: string };\n\n/** The canonical form every declared `route` export resolves to. */\nexport type CanonicalRoute = {\n path: string;\n name?: string;\n};\n\n/** The canonical inputs {@link deriveFallbackRouteName} requires — see the module doc comment for what \"canonical\" means. */\nexport type RouteNameFallbackInput = {\n /** The page's declared route path, e.g. `\"/settings\"` or `\"/\"`. */\n routePath: string;\n /** The page's app-root-relative POSIX source path, e.g. `\"src/app/main/web/contact-us.page.tsx\"`. */\n sourceFile: string;\n};\n\n/**\n * Raised when a caller passes a `sourceFile` containing a backslash.\n * Canonical means canonical: this module does not normalize Windows path\n * separators on the caller's behalf.\n */\nexport class NonPosixSourceFilePathError extends Error {\n public constructor(public readonly sourceFile: string) {\n super(\n `route-identity: sourceFile \"${sourceFile}\" contains a backslash. This module's inputs ` +\n \"must already be canonical app-root-relative POSIX paths (forward slashes only) — \" +\n 'normalize with `value.replace(/\\\\\\\\/g, \"/\")` before calling deriveFallbackRouteName.',\n );\n this.name = \"NonPosixSourceFilePathError\";\n }\n}\n\n/**\n * Canonicalizes a declared `route` export — string or `{ path, name? }` —\n * into `{ path, name? }`. Requires well-formed input; an export that is\n * neither a string nor an object with a `path` is the extractor's problem,\n * already rejected before this function is ever called.\n */\nexport function canonicalizeRouteExport(route: DeclaredRouteExport): CanonicalRoute {\n if (typeof route === \"string\") {\n return { path: route };\n }\n\n return route.name === undefined ? { path: route.path } : { path: route.path, name: route.name };\n}\n\n/** Strips leading and trailing \".\" characters — mirrors `trim(value, \".\")` as used by the installer's `deriveRouteName`. */\nfunction trimDots(value: string): string {\n return value.replace(/^\\.+|\\.+$/g, \"\");\n}\n\n/**\n * The module segment a canonical source path declares, or `undefined` for a\n * global (`src/web/**`) page. `sourceFile` is `<srcDir>/app/<module>/web/...`\n * or `<srcDir>/web/...` — the first segment is the (arbitrarily named) src\n * dir, so the module test looks at the SECOND segment.\n */\nfunction moduleSegmentFor(sourceFile: string): string | undefined {\n const segments = sourceFile.split(\"/\");\n\n return segments[1] === \"app\" ? segments[2] : undefined;\n}\n\n/**\n * Derives the fallback route name for a page whose declared route carries no\n * `name` — the same derivation the dev installer's `deriveRouteName` applies\n * today (`web/src/server/install-page-routes.ts`), expressed against\n * canonical inputs instead of an absolute file path plus an `appSrcRoot`.\n *\n * The installer only ever calls its derivation for a page under\n * `<appSrcRoot>/app/**`, so a global (`src/web/**`) page has no installer\n * behaviour to mirror; for that case this function instead follows\n * discovery's own convention (`routeNameFor` in `discover-pages.ts`) — no\n * module prefix, and `\"index\"` when there is nothing left to say at all.\n *\n * Throws {@link NonPosixSourceFilePathError} when `sourceFile` contains a\n * backslash.\n */\nexport function deriveFallbackRouteName(input: RouteNameFallbackInput): string {\n const { routePath, sourceFile } = input;\n\n if (sourceFile.includes(\"\\\\\")) {\n throw new NonPosixSourceFilePathError(sourceFile);\n }\n\n const moduleName = moduleSegmentFor(sourceFile);\n const suffix = trimDots(routePath.replace(/\\//g, \".\"));\n\n if (moduleName !== undefined) {\n return suffix ? `${moduleName}.${suffix}` : moduleName;\n }\n\n return suffix || \"index\";\n}\n"],"mappings":";;;;;;AAoDA,IAAa,8BAAb,cAAiD,MAAM;CAClB;CAAnC,AAAO,YAAY,AAAgB,YAAoB;EACrD,MACE,+BAA+B,WAAW,qNAG5C;EALiC;EAMjC,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,SAAgB,wBAAwB,OAA4C;CAClF,IAAI,OAAO,UAAU,UACnB,OAAO,EAAE,MAAM,MAAM;CAGvB,OAAO,MAAM,SAAS,SAAY,EAAE,MAAM,MAAM,KAAK,IAAI;EAAE,MAAM,MAAM;EAAM,MAAM,MAAM;CAAK;AAChG;;AAGA,SAAS,SAAS,OAAuB;CACvC,OAAO,MAAM,QAAQ,cAAc,EAAE;AACvC;;;;;;;AAQA,SAAS,iBAAiB,YAAwC;CAChE,MAAM,WAAW,WAAW,MAAM,GAAG;CAErC,OAAO,SAAS,OAAO,QAAQ,SAAS,KAAK;AAC/C;;;;;;;;;;;;;;;;AAiBA,SAAgB,wBAAwB,OAAuC;CAC7E,MAAM,EAAE,WAAW,eAAe;CAElC,IAAI,WAAW,SAAS,IAAI,GAC1B,MAAM,IAAI,4BAA4B,UAAU;CAGlD,MAAM,aAAa,iBAAiB,UAAU;CAC9C,MAAM,SAAS,SAAS,UAAU,QAAQ,OAAO,GAAG,CAAC;CAErD,IAAI,eAAe,QACjB,OAAO,SAAS,GAAG,WAAW,GAAG,WAAW;CAG9C,OAAO,UAAU;AACnB"}
|
|
1
|
+
{"version":3,"file":"route-identity.mjs","names":[],"sources":["../../../../../../../web/src/routing/route-identity.ts"],"sourcesContent":["/**\r\n * Route identity — the single, pure implementation of \"what is this page's\r\n * route path and name\". The dev installer\r\n * (`web/src/server/install-page-routes.ts`), the production manifest\r\n * installer (`web/src/server/install-page-routes-from-manifest.ts`) and\r\n * discovery (`web/src/build/discover-pages.ts`) each hand-derived this on\r\n * their own until all three were made to delegate here.\r\n *\r\n * {@link resolvePageRouteName} is the ONE answer to \"what is this page's\r\n * route name\": an explicit `name` on the declared `route` export wins,\r\n * otherwise the name comes from the page's own FILE PATH\r\n * (`deriveFilesystemRouteName`) — never from `route.path`. The route name is\r\n * an identity key (`routing/route-table.ts`'s lookup key, `components/link.ts`,\r\n * `server/render-page.ts`, the generated client registry and the hydration\r\n * payload all address a page by it), and an identity key must be stable under\r\n * the change most likely to happen to a page — its URL, renamed for SEO,\r\n * localization or restructuring. A file path is also unique by construction,\r\n * while a declared `path: \"/\"` yields no usable name at all.\r\n *\r\n * Pure string logic only: no `fs`, no `path`, no Node built-ins. Every input\r\n * this module accepts is already CANONICAL — a POSIX, app-root-relative\r\n * source path (e.g. `\"src/web/index.page.tsx\"`).\r\n *\r\n * {@link canonicalizeRouteExport} is also the ONE seam every declared\r\n * `route.path` passes through on its way into either installer\r\n * (`install-page-routes.ts`, `install-page-routes-from-manifest.ts`), so it is\r\n * where `../routing/page-route-grammar.ts`'s `classifyPageRoutePath` is\r\n * applied: a rejected path raises {@link PageRoutePathNotSupportedError}\r\n * naming the offending page file, rather than being published literally.\r\n *\r\n * Well-formedness of the declared `route` export itself (is it a string or an\r\n * object, does the object have a `path`) is the extractor's problem — already\r\n * rejected at build before either derivation function here is called.\r\n *\r\n * DIRECTORY CONTRACT — applies to everything in `web/src/routing/`: nothing\r\n * here may import `node:fs`, `node:path`, `vite`, or `fastify`. Modules in\r\n * this directory receive canonical values and trust nothing — they assert\r\n * rather than trust, but they never repair. A module that needs the\r\n * filesystem does not belong here. The purity is deliberate: it keeps these\r\n * modules consumable from the dev server, the build, the production runtime,\r\n * and — if ever needed — the browser client, without dragging any of those\r\n * environments along.\r\n */\r\n\r\nimport { deriveFilesystemRouteName } from \"./filesystem-route\";\r\nimport { classifyPageRoutePath, PageRoutePathNotSupportedError } from \"./page-route-grammar\";\r\n\r\n/**\r\n * A page's opt-in into shared-cache storage for its document AND its data\r\n * representation (`x-warlock-data`) — the two must never diverge, because a\r\n * cacheable data payload leaks exactly what an uncacheable document was\r\n * protecting (`../server/create-page-route-handler.ts`).\r\n *\r\n * `public: true` is not a flag with a `false` counterpart: the framework is\r\n * closed by default (`../server/response-cache-floor.ts`), so the only\r\n * meaningful state this object can express is \"yes, cache me\" — a page that\r\n * wants the default simply omits `cache` entirely. `maxAge` has no framework\r\n * default and never will: a route's freshness window is a decision only the\r\n * route's author can make safely, and guessing one would be exactly the kind\r\n * of silent, environment-dependent behaviour this feature exists to remove.\r\n * Both keys are required — see {@link InvalidPageCacheOptInError}.\r\n *\r\n * Shaped as an object, not a boolean or a bare number, so a later addition\r\n * (e.g. CDN surrogate keys) extends it without a breaking change.\r\n */\r\nexport type PageCacheOptIn = {\r\n public: true;\r\n /** Freshness window in seconds, emitted as `Cache-Control: public, max-age=<maxAge>`. */\r\n maxAge: number;\r\n};\r\n\r\n/** The shape a page's `route` export may declare — mirrors `PageRouteExport` in `install-page-routes.ts`. */\r\nexport type DeclaredRouteExport = string | { path: string; name?: string; cache?: PageCacheOptIn };\r\n\r\n/** The canonical form every declared `route` export resolves to. */\r\nexport type CanonicalRoute = {\r\n path: string;\r\n name?: string;\r\n};\r\n\r\n/**\r\n * Raised when a page's `route.cache` is present but malformed — most notably\r\n * `public: true` with no `maxAge`. The framework refuses to invent a\r\n * freshness window (see {@link PageCacheOptIn}), so this is a BOOT-TIME\r\n * failure rather than a silent fallback to `no-store`: a developer who wrote\r\n * `cache: { public: true }` meant for the route to be cacheable, and serving\r\n * it `no-store` without a word would be the exact silent-failure class this\r\n * release exists to kill.\r\n */\r\nexport class InvalidPageCacheOptInError extends Error {\r\n public constructor(public readonly pageFile: string) {\r\n super(\r\n `\"${pageFile}\" declares \\`route.cache\\` without a valid opt-in. Both keys are required: ` +\r\n \"write `cache: { public: true, maxAge: <seconds> }` — for example `cache: { public: \" +\r\n \"true, maxAge: 60 }`. Remove `cache` entirely to keep the route `no-store` (the default) \" +\r\n \"instead.\",\r\n );\r\n this.name = \"InvalidPageCacheOptInError\";\r\n }\r\n}\r\n\r\n/**\r\n * Resolves and validates a declared `route` export's `cache` opt-in.\r\n *\r\n * `undefined` — the common case — means \"no opt-in\", which the caller (the\r\n * response-cache-floor seam) treats as `no-store`, not as \"cacheable with no\r\n * limit\". A malformed opt-in throws {@link InvalidPageCacheOptInError} rather\r\n * than being coerced or ignored, so a typo in a route's `cache` field fails\r\n * the build/boot instead of quietly shipping an unintended cache policy.\r\n */\r\nexport function resolvePageRouteCache(\r\n route: DeclaredRouteExport | undefined,\r\n pageFile: string,\r\n): PageCacheOptIn | undefined {\r\n if (route === undefined || typeof route === \"string\") return undefined;\r\n\r\n const { cache } = route;\r\n\r\n if (cache === undefined) return undefined;\r\n\r\n if (cache.public !== true || typeof cache.maxAge !== \"number\") {\r\n throw new InvalidPageCacheOptInError(pageFile);\r\n }\r\n\r\n return cache;\r\n}\r\n\r\n/**\r\n * Canonicalizes a declared `route` export — string or `{ path, name? }` —\r\n * into `{ path, name? }`. Requires well-formed input; an export that is\r\n * neither a string nor an object with a `path` is the extractor's problem,\r\n * already rejected before this function is ever called.\r\n *\r\n * This is also where the declared `path` is validated: `pageFile` names the\r\n * page whose `route` export is being canonicalized, and a `path` that\r\n * {@link classifyPageRoutePath} rejects raises\r\n * {@link PageRoutePathNotSupportedError} naming it — rather than being\r\n * published literally. Both installers reach every declared path through\r\n * here, so this is the one place that check has to live.\r\n */\r\nexport function canonicalizeRouteExport(\r\n route: DeclaredRouteExport,\r\n pageFile: string,\r\n): CanonicalRoute {\r\n const path = typeof route === \"string\" ? route : route.path;\r\n const verdict = classifyPageRoutePath(path);\r\n\r\n if (verdict.type === \"rejected\") {\r\n throw new PageRoutePathNotSupportedError(pageFile, path, verdict.reason);\r\n }\r\n\r\n if (typeof route === \"string\") {\r\n return { path: route };\r\n }\r\n\r\n return route.name === undefined ? { path: route.path } : { path: route.path, name: route.name };\r\n}\r\n\r\n/**\r\n * Resolves a page's route NAME — the single derivation `install-page-routes.ts`,\r\n * `install-page-routes-from-manifest.ts` and `discover-pages.ts` all delegate\r\n * to, so dev, the production manifest installer and build discovery cannot\r\n * derive three different names for the same page (see the module doc comment\r\n * for why the file path, not `route.path`, is the source of truth).\r\n *\r\n * An explicit `name` on `route` always wins. Otherwise the name is derived\r\n * from `pageFile` via {@link deriveFilesystemRouteName} — `pageFile` must\r\n * already be canonical: a POSIX path relative to the page's web root (e.g.\r\n * `\"blog/archive.page.tsx\"`), the same value each caller already computes as\r\n * `filesystemPageFileFor`/`webRelativeSourceFile`/`relativePageFile`.\r\n */\r\nexport function resolvePageRouteName(\r\n route: DeclaredRouteExport | undefined,\r\n pageFile: string,\r\n): string {\r\n if (route === undefined) {\r\n return deriveFilesystemRouteName(pageFile);\r\n }\r\n\r\n return canonicalizeRouteExport(route, pageFile).name ?? deriveFilesystemRouteName(pageFile);\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,IAAa,6BAAb,cAAgD,MAAM;CACjB;CAAnC,AAAO,YAAY,AAAgB,UAAkB;EACnD,MACE,IAAI,SAAS,uQAIf;EANiC;EAOjC,KAAK,OAAO;CACd;AACF;;;;;;;;;;AAWA,SAAgB,sBACd,OACA,UAC4B;CAC5B,IAAI,UAAU,UAAa,OAAO,UAAU,UAAU,OAAO;CAE7D,MAAM,EAAE,UAAU;CAElB,IAAI,UAAU,QAAW,OAAO;CAEhC,IAAI,MAAM,WAAW,QAAQ,OAAO,MAAM,WAAW,UACnD,MAAM,IAAI,2BAA2B,QAAQ;CAG/C,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,wBACd,OACA,UACgB;CAChB,MAAM,OAAO,OAAO,UAAU,WAAW,QAAQ,MAAM;CACvD,MAAM,UAAU,sBAAsB,IAAI;CAE1C,IAAI,QAAQ,SAAS,YACnB,MAAM,IAAI,+BAA+B,UAAU,MAAM,QAAQ,MAAM;CAGzE,IAAI,OAAO,UAAU,UACnB,OAAO,EAAE,MAAM,MAAM;CAGvB,OAAO,MAAM,SAAS,SAAY,EAAE,MAAM,MAAM,KAAK,IAAI;EAAE,MAAM,MAAM;EAAM,MAAM,MAAM;CAAK;AAChG;;;;;;;;;;;;;;AAeA,SAAgB,qBACd,OACA,UACQ;CACR,IAAI,UAAU,QACZ,OAAO,0BAA0B,QAAQ;CAG3C,OAAO,wBAAwB,OAAO,QAAQ,CAAC,CAAC,QAAQ,0BAA0B,QAAQ;AAC5F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-table.mjs","names":[],"sources":["../../../../../../../web/src/routing/route-table.ts"],"sourcesContent":["/**\n * The name→URL primitive, and the one route table both sides read.\n *\n * `href(name, params, query)` is the DURABLE primitive; `<Link>` is sugar over\n * it. That ordering is deliberate and ratified: a function serves emails,\n * redirects, `Location` headers and non-React callers, none of which can render\n * a component — and it keeps client-side navigation, when it lands, a behaviour\n * change rather than an API change.\n *\n * ── Why a process-global table is correct HERE ───────────────────────────────\n * Module-level mutable state is normally a defect in a server that handles\n * concurrent requests, and this codebase has a real example of that defect to\n * point at: `@mongez/react-router`'s `RouterWrapper` keeps the RENDERED PAGE\n * CONTENT in a module-level binding, so request B overwrites the tree request A\n * is about to serialize. That is why it is not on the SSR path.\n *\n * A route table is the opposite kind of value. It is derived from the file\n * system at boot, identical for every request in the process, and never written\n * during a request — the same category as the compiled route table the server's\n * own router holds. Nothing here is per-request, so there is nothing for two\n * requests to race over.\n *\n * The rule that keeps it that way: `publishRouteTable` is called at INSTALL\n * time (server) or at hydration entry (browser), and never from a loader, a\n * middleware, or a component.\n */\n\nimport { queryStringOf, type QueryStringInput } from \"./query-string\";\n\n/** The two fields `href` needs. Callers may pass richer entries; the rest is ignored. */\nexport type RouteTableEntry = {\n readonly name: string;\n readonly path: string;\n};\n\n/** What `href` accepts for a `:param` segment. Rendered with `String(value)`. */\nexport type RouteParameters = Readonly<Record<string, unknown>>;\n\n/**\n * Query values; an `undefined` value is omitted rather than serialized.\n *\n * A value may be a scalar, an array of scalars, or an object one level deep —\n * the shapes `@warlock.js/core` parses back out of the URL. Anything deeper\n * throws `UnserializableQueryValueError`; the grammar and the measurements\n * behind it are documented in query-string.ts.\n */\nexport type RouteQuery = QueryStringInput;\n\nconst PARAMETER_PATTERN = /:([A-Za-z0-9_]+)|\\*/g;\n\n/**\n * ── WHY THIS LIVES ON `globalThis` AND NOT IN A MODULE BINDING ───────────────\n *\n * A plain `let` here does not work in development, and the failure is silent\n * enough to be worth spelling out.\n *\n * In dev the process runs TWO module graphs over the same files. Route\n * installation is loaded by tsx/Node (it is CLI bootstrap and imports core\n * directly), while page and layout modules are evaluated by Vite's SSR module\n * runner — which keeps its own registry and its own instance of every module it\n * transforms, `@warlock.js/web` included. So a module-level binding written by\n * the installer is not the binding `<Link>` reads during render: the installer\n * publishes into one instance and the component finds the other one empty.\n *\n * That was measured, not theorised. With a module-level `let`, every anchor on\n * a server-rendered page threw `RouteTableNotPublishedError` with an empty\n * known-names list while installation had demonstrably run.\n *\n * `Symbol.for` resolves through the per-ISOLATE symbol registry, which both\n * graphs share because they are the same isolate. So the table is one value no\n * matter which graph reaches it first, and the module keeps its module-shaped\n * API. `publishedBy` is carried for diagnosis only.\n */\nconst ROUTE_TABLE_SLOT = Symbol.for(\"warlock.web.routeTable\");\n\ntype RouteTableSlot = {\n table: Map<string, string>;\n publishedBy: string;\n};\n\ntype RouteTableHost = typeof globalThis & {\n [ROUTE_TABLE_SLOT]?: RouteTableSlot;\n};\n\n/**\n * `undefined` means \"nobody has published yet\", which is a DIFFERENT fault from\n * \"the table is published and this name is not in it\" — an empty Map would\n * conflate them and send the reader hunting a route that was never missing.\n */\nfunction readSlot(): RouteTableSlot | undefined {\n return (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT];\n}\n\nexport class RouteTableNotPublishedError extends Error {\n public constructor(public readonly routeName: string) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) was called before the route table was ` +\n \"published, so no route name resolves yet. The table is published once at boot — by \" +\n \"the server when it installs page routes, and by the hydration entry before it mounts. \" +\n \"Seeing this means href() ran outside both: typically a module evaluating at import \" +\n \"time, or a unit test that renders a component without publishing a table first.\",\n );\n this.name = \"RouteTableNotPublishedError\";\n }\n}\n\nexport class UnknownRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly knownRouteNames: readonly string[],\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) does not name a known route. ` +\n (knownRouteNames.length === 0\n ? \"The route table is published but empty, so no page declared a `route` discovery could see.\"\n : `The table knows: ${knownRouteNames.map(name => JSON.stringify(name)).join(\", \")}.`),\n );\n this.name = \"UnknownRouteNameError\";\n }\n}\n\nexport class MissingRouteParameterError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly parameterName: string,\n public readonly routePath: string,\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) is missing the parameter ` +\n `${JSON.stringify(parameterName)}, required by the route path \"${routePath}\". ` +\n \"It is not defaulted: a missing parameter would otherwise be interpolated as the \" +\n \"literal text `undefined`, producing a link that renders correctly and 404s for a \" +\n \"visitor.\",\n );\n this.name = \"MissingRouteParameterError\";\n }\n}\n\nexport class UnknownRouteParameterError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly parameterNames: readonly string[],\n public readonly routePath: string,\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) was given ` +\n `${parameterNames.map(name => JSON.stringify(name)).join(\", \")}, which the route path ` +\n `\"${routePath}\" does not declare. Passing an undeclared parameter is a typo often ` +\n \"enough that it is refused rather than dropped; values meant for the query string go \" +\n \"in the third argument.\",\n );\n this.name = \"UnknownRouteParameterError\";\n }\n}\n\nexport class DuplicateRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly paths: readonly [string, string],\n ) {\n super(\n `Warlock route table: two routes both claim the name ${JSON.stringify(routeName)} — ` +\n `\"${paths[0]}\" and \"${paths[1]}\". A name resolves to exactly one URL, so one of the ` +\n \"two would silently win and every link to it would be wrong half the time.\",\n );\n this.name = \"DuplicateRouteNameError\";\n }\n}\n\n/**\n * Publish the table. WHOLESALE — the previous one is discarded, not merged\n * into.\n *\n * Merging looks harmless until a page is deleted and the dev server restarts:\n * the dead name would stay resolvable, and `<Link>` would go on rendering a URL\n * the server no longer routes. The table has to be able to shrink.\n */\nexport function publishRouteTable(\n entries: readonly RouteTableEntry[],\n publishedBy = \"unnamed\",\n): void {\n const table = new Map<string, string>();\n\n for (const entry of entries) {\n const existing = table.get(entry.name);\n\n if (existing !== undefined) {\n throw new DuplicateRouteNameError(entry.name, [existing, entry.path]);\n }\n\n table.set(entry.name, entry.path);\n }\n\n (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT] = { table, publishedBy };\n}\n\n/**\n * Drop the table, returning the module to its pre-boot state.\n *\n * Exists for tests: the table is process-global, so a suite that published one\n * would otherwise leak it into every later test in the same worker and pass in\n * file order while failing under `--shuffle`.\n */\nexport function resetRouteTable(): void {\n delete (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT];\n}\n\n/** The published names, for diagnostics. Empty when nothing is published. */\nexport function knownRouteNames(): readonly string[] {\n const slot = readSlot();\n\n return slot === undefined ? [] : [...slot.table.keys()];\n}\n\n/** Who published the live table, for diagnosis. `undefined` when nothing has. */\nexport function routeTablePublisher(): string | undefined {\n return readSlot()?.publishedBy;\n}\n\nfunction parameterNamesOf(routePath: string): readonly string[] {\n const names: string[] = [];\n\n for (const match of routePath.matchAll(PARAMETER_PATTERN)) {\n names.push(match[1] ?? \"*\");\n }\n\n return names;\n}\n\nfunction interpolate(\n routeName: string,\n routePath: string,\n params: RouteParameters | undefined,\n): string {\n const declared = parameterNamesOf(routePath);\n const supplied = Object.keys(params ?? {}).filter(key => params?.[key] !== undefined);\n const undeclared = supplied.filter(key => !declared.includes(key));\n\n if (undeclared.length > 0) {\n throw new UnknownRouteParameterError(routeName, undeclared, routePath);\n }\n\n return routePath.replace(PARAMETER_PATTERN, match => {\n const name = match === \"*\" ? \"*\" : match.slice(1);\n const value = params?.[name];\n\n if (value === undefined) {\n throw new MissingRouteParameterError(routeName, name, routePath);\n }\n\n return encodeURIComponent(String(value));\n });\n}\n\n/**\n * Resolve a route NAME to a URL.\n *\n * A name, never a path: a moved page changes its URL and keeps its name, so\n * every call site keeps working. That is the property the hardcoded table in\n * the previous `<Link>` could not offer, because it restated six URLs by hand\n * and silently refused every other page in the app.\n *\n * The query half is delegated to `queryStringOf`, which lives next to the\n * DECODER it has to agree with. It used to live here, and being module-private\n * meant the read half could not share it — the one-writer rule held only\n * because nobody had written the second writer yet.\n *\n * @throws {UnserializableQueryValueError} when a query value nests deeper than\n * the wire format core parses can carry.\n */\nexport function href(\n name: string,\n params?: RouteParameters,\n query?: RouteQuery,\n): string {\n const slot = readSlot();\n\n if (slot === undefined) throw new RouteTableNotPublishedError(name);\n\n const routePath = slot.table.get(name);\n\n if (routePath === undefined) {\n throw new UnknownRouteNameError(name, [...slot.table.keys()]);\n }\n\n return `${interpolate(name, routePath, params)}${queryStringOf(query)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;AAyB1B,MAAM,mBAAmB,OAAO,IAAI,wBAAwB;;;;;;AAgB5D,SAAS,WAAuC;CAC9C,OAAQ,WAA8B;AACxC;AAEA,IAAa,8BAAb,cAAiD,MAAM;CAClB;CAAnC,AAAO,YAAY,AAAgB,WAAmB;EACpD,MACE,gBAAgB,KAAK,UAAU,SAAS,EAAE,oXAK5C;EAPiC;EAQjC,KAAK,OAAO;CACd;AACF;AAEA,IAAa,wBAAb,cAA2C,MAAM;CAE7B;CACA;CAFlB,AAAO,YACL,AAAgB,WAChB,AAAgB,iBAChB;EACA,MACE,gBAAgB,KAAK,UAAU,SAAS,EAAE,oCACvC,gBAAgB,WAAW,IACxB,+FACA,o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BAAqC;CACnD,MAAM,OAAO,SAAS;CAEtB,OAAO,SAAS,SAAY,CAAC,IAAI,CAAC,GAAG,KAAK,MAAM,KAAK,CAAC;AACxD;AAOA,SAAS,iBAAiB,WAAsC;CAC9D,MAAM,QAAkB,CAAC;CAEzB,KAAK,MAAM,SAAS,UAAU,SAAS,iBAAiB,GACtD,MAAM,KAAK,MAAM,MAAM,GAAG;CAG5B,OAAO;AACT;AAEA,SAAS,YACP,WACA,WACA,QACQ;CACR,MAAM,WAAW,iBAAiB,SAAS;CAE3C,MAAM,aADW,OAAO,KAAK,UAAU,CAAC,CAAC,EAAE,QAAO,QAAO,SAAS,SAAS,MACjD,EAAE,QAAO,QAAO,CAAC,SAAS,SAAS,GAAG,CAAC;CAEjE,IAAI,WAAW,SAAS,GACtB,MAAM,IAAI,2BAA2B,WAAW,YAAY,SAAS;CAGvE,OAAO,UAAU,QAAQ,oBAAmB,UAAS;EACnD,MAAM,OAAO,UAAU,MAAM,MAAM,MAAM,MAAM,CAAC;EAChD,MAAM,QAAQ,SAAS;EAEvB,IAAI,UAAU,QACZ,MAAM,IAAI,2BAA2B,WAAW,MAAM,SAAS;EAGjE,OAAO,mBAAmB,OAAO,KAAK,CAAC;CACzC,CAAC;AACH;;;;;;;;;;;;;;;;;AAkBA,SAAgB,KACd,MACA,QACA,OACQ;CACR,MAAM,OAAO,SAAS;CAEtB,IAAI,SAAS,QAAW,MAAM,IAAI,4BAA4B,IAAI;CAElE,MAAM,YAAY,KAAK,MAAM,IAAI,IAAI;CAErC,IAAI,cAAc,QAChB,MAAM,IAAI,sBAAsB,MAAM,CAAC,GAAG,KAAK,MAAM,KAAK,CAAC,CAAC;CAG9D,OAAO,GAAG,YAAY,MAAM,WAAW,MAAM,IAAI,cAAc,KAAK;AACtE"}
|
|
1
|
+
{"version":3,"file":"route-table.mjs","names":[],"sources":["../../../../../../../web/src/routing/route-table.ts"],"sourcesContent":["/**\n * The name→URL primitive, and the one route table both sides read.\n *\n * `href(name, params, query)` is the DURABLE primitive; `<Link>` is sugar over\n * it. That ordering is deliberate and ratified: a function serves emails,\n * redirects, `Location` headers and non-React callers, none of which can render\n * a component — and it keeps client-side navigation, when it lands, a behaviour\n * change rather than an API change.\n *\n * ── Why a process-global table is correct HERE ───────────────────────────────\n * Module-level mutable state is normally a defect in a server that handles\n * concurrent requests, and this codebase has a real example of that defect to\n * point at: `@mongez/react-router`'s `RouterWrapper` keeps the RENDERED PAGE\n * CONTENT in a module-level binding, so request B overwrites the tree request A\n * is about to serialize. That is why it is not on the SSR path.\n *\n * A route table is the opposite kind of value. It is derived from the file\n * system at boot, identical for every request in the process, and never written\n * during a request — the same category as the compiled route table the server's\n * own router holds. Nothing here is per-request, so there is nothing for two\n * requests to race over.\n *\n * The rule that keeps it that way: `publishRouteTable` is called at INSTALL\n * time (server) or at hydration entry (browser), and never from a loader, a\n * middleware, or a component.\n */\n\nimport { queryStringOf, type QueryStringInput } from \"./query-string\";\n\n/** The two fields `href` needs. Callers may pass richer entries; the rest is ignored. */\nexport type RouteTableEntry = {\n readonly name: string;\n readonly path: string;\n};\n\n/** What `href` accepts for a `:param` segment. Rendered with `String(value)`. */\nexport type RouteParameters = Readonly<Record<string, unknown>>;\n\n/**\n * Query values; an `undefined` value is omitted rather than serialized.\n *\n * A value may be a scalar, an array of scalars, or an object one level deep —\n * the shapes `@warlock.js/core` parses back out of the URL. Anything deeper\n * throws `UnserializableQueryValueError`; the grammar and the measurements\n * behind it are documented in query-string.ts.\n */\nexport type RouteQuery = QueryStringInput;\n\nconst PARAMETER_PATTERN = /:([A-Za-z0-9_]+)|\\*/g;\n\n/**\n * ── WHY THIS LIVES ON `globalThis` AND NOT IN A MODULE BINDING ───────────────\n *\n * A plain `let` here does not work in development, and the failure is silent\n * enough to be worth spelling out.\n *\n * In dev the process runs TWO module graphs over the same files. Route\n * installation is loaded by tsx/Node (it is CLI bootstrap and imports core\n * directly), while page and layout modules are evaluated by Vite's SSR module\n * runner — which keeps its own registry and its own instance of every module it\n * transforms, `@warlock.js/web` included. So a module-level binding written by\n * the installer is not the binding `<Link>` reads during render: the installer\n * publishes into one instance and the component finds the other one empty.\n *\n * That was measured, not theorised. With a module-level `let`, every anchor on\n * a server-rendered page threw `RouteTableNotPublishedError` with an empty\n * known-names list while installation had demonstrably run.\n *\n * `Symbol.for` resolves through the per-ISOLATE symbol registry, which both\n * graphs share because they are the same isolate. So the table is one value no\n * matter which graph reaches it first, and the module keeps its module-shaped\n * API. `publishedBy` is carried for diagnosis only.\n */\nconst ROUTE_TABLE_SLOT = Symbol.for(\"warlock.web.routeTable\");\n\ntype RouteTableSlot = {\n table: Map<string, string>;\n publishedBy: string;\n};\n\ntype RouteTableHost = typeof globalThis & {\n [ROUTE_TABLE_SLOT]?: RouteTableSlot;\n};\n\n/**\n * `undefined` means \"nobody has published yet\", which is a DIFFERENT fault from\n * \"the table is published and this name is not in it\" — an empty Map would\n * conflate them and send the reader hunting a route that was never missing.\n */\nfunction readSlot(): RouteTableSlot | undefined {\n return (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT];\n}\n\nexport class RouteTableNotPublishedError extends Error {\n public constructor(public readonly routeName: string) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) was called before the route table was ` +\n \"published, so no route name resolves yet. The table is published once at boot — by \" +\n \"the server when it installs page routes, and by the hydration entry before it mounts. \" +\n \"Seeing this means href() ran outside both: typically a module evaluating at import \" +\n \"time, or a unit test that renders a component without publishing a table first.\",\n );\n this.name = \"RouteTableNotPublishedError\";\n }\n}\n\nexport class UnknownRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly knownRouteNames: readonly string[],\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) does not name a known route. ` +\n (knownRouteNames.length === 0\n ? \"The route table is published but empty, so no page declared a `route` discovery could see.\"\n : `The table knows: ${knownRouteNames.map(name => JSON.stringify(name)).join(\", \")}.`),\n );\n this.name = \"UnknownRouteNameError\";\n }\n}\n\nexport class MissingRouteParameterError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly parameterName: string,\n public readonly routePath: string,\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) is missing the parameter ` +\n `${JSON.stringify(parameterName)}, required by the route path \"${routePath}\". ` +\n \"It is not defaulted: a missing parameter would otherwise be interpolated as the \" +\n \"literal text `undefined`, producing a link that renders correctly and 404s for a \" +\n \"visitor.\",\n );\n this.name = \"MissingRouteParameterError\";\n }\n}\n\nexport class UnknownRouteParameterError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly parameterNames: readonly string[],\n public readonly routePath: string,\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) was given ` +\n `${parameterNames.map(name => JSON.stringify(name)).join(\", \")}, which the route path ` +\n `\"${routePath}\" does not declare. Passing an undeclared parameter is a typo often ` +\n \"enough that it is refused rather than dropped; values meant for the query string go \" +\n \"in the third argument.\",\n );\n this.name = \"UnknownRouteParameterError\";\n }\n}\n\nexport class DuplicateRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly paths: readonly [string, string],\n ) {\n super(\n `Warlock route table: two routes both claim the name ${JSON.stringify(routeName)} — ` +\n `\"${paths[0]}\" and \"${paths[1]}\". A name resolves to exactly one URL, so one of the ` +\n \"two would silently win and every link to it would be wrong half the time.\",\n );\n this.name = \"DuplicateRouteNameError\";\n }\n}\n\n/**\n * Publish the table. WHOLESALE — the previous one is discarded, not merged\n * into.\n *\n * Merging looks harmless until a page is deleted and the dev server restarts:\n * the dead name would stay resolvable, and `<Link>` would go on rendering a URL\n * the server no longer routes. The table has to be able to shrink.\n */\nexport function publishRouteTable(\n entries: readonly RouteTableEntry[],\n publishedBy = \"unnamed\",\n): void {\n const table = new Map<string, string>();\n\n for (const entry of entries) {\n const existing = table.get(entry.name);\n\n if (existing !== undefined) {\n throw new DuplicateRouteNameError(entry.name, [existing, entry.path]);\n }\n\n table.set(entry.name, entry.path);\n }\n\n (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT] = { table, publishedBy };\n}\n\n/**\n * Drop the table, returning the module to its pre-boot state.\n *\n * Exists for tests: the table is process-global, so a suite that published one\n * would otherwise leak it into every later test in the same worker and pass in\n * file order while failing under `--shuffle`.\n */\nexport function resetRouteTable(): void {\n delete (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT];\n}\n\n/** The published names, for diagnostics. Empty when nothing is published. */\nexport function knownRouteNames(): readonly string[] {\n const slot = readSlot();\n\n return slot === undefined ? [] : [...slot.table.keys()];\n}\n\n/** Who published the live table, for diagnosis. `undefined` when nothing has. */\nexport function routeTablePublisher(): string | undefined {\n return readSlot()?.publishedBy;\n}\n\nfunction parameterNamesOf(routePath: string): readonly string[] {\n const names: string[] = [];\n\n for (const match of routePath.matchAll(PARAMETER_PATTERN)) {\n names.push(match[1] ?? \"*\");\n }\n\n return names;\n}\n\nfunction interpolate(\n routeName: string,\n routePath: string,\n params: RouteParameters | undefined,\n): string {\n const declared = parameterNamesOf(routePath);\n const supplied = Object.keys(params ?? {}).filter(key => params?.[key] !== undefined);\n const undeclared = supplied.filter(key => !declared.includes(key));\n\n if (undeclared.length > 0) {\n throw new UnknownRouteParameterError(routeName, undeclared, routePath);\n }\n\n return routePath.replace(PARAMETER_PATTERN, match => {\n const name = match === \"*\" ? \"*\" : match.slice(1);\n const value = params?.[name];\n\n if (value === undefined) {\n throw new MissingRouteParameterError(routeName, name, routePath);\n }\n\n return encodeURIComponent(String(value));\n });\n}\n\n/**\n * Resolve a route NAME to a URL.\n *\n * A name, never a path: a moved page changes its URL and keeps its name, so\n * every call site keeps working. That is the property the hardcoded table in\n * the previous `<Link>` could not offer, because it restated six URLs by hand\n * and silently refused every other page in the app.\n *\n * The query half is delegated to `queryStringOf`, which lives next to the\n * DECODER it has to agree with. It used to live here, and being module-private\n * meant the read half could not share it — the one-writer rule held only\n * because nobody had written the second writer yet.\n *\n * @throws {UnserializableQueryValueError} when a query value nests deeper than\n * the wire format core parses can carry.\n */\nexport function href(\n name: string,\n params?: RouteParameters,\n query?: RouteQuery,\n): string {\n const slot = readSlot();\n\n if (slot === undefined) throw new RouteTableNotPublishedError(name);\n\n const routePath = slot.table.get(name);\n\n if (routePath === undefined) {\n throw new UnknownRouteNameError(name, [...slot.table.keys()]);\n }\n\n return `${interpolate(name, routePath, params)}${queryStringOf(query)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;AAyB1B,MAAM,mBAAmB,OAAO,IAAI,wBAAwB;;;;;;AAgB5D,SAAS,WAAuC;CAC9C,OAAQ,WAA8B;AACxC;AAEA,IAAa,8BAAb,cAAiD,MAAM;CAClB;CAAnC,AAAO,YAAY,AAAgB,WAAmB;EACpD,MACE,gBAAgB,KAAK,UAAU,SAAS,EAAE,oXAK5C;EAPiC;EAQjC,KAAK,OAAO;CACd;AACF;AAEA,IAAa,wBAAb,cAA2C,MAAM;CAE7B;CACA;CAFlB,AAAO,YACL,AAAgB,WAChB,AAAgB,iBAChB;EACA,MACE,gBAAgB,KAAK,UAAU,SAAS,EAAE,oCACvC,gBAAgB,WAAW,IACxB,+FACA,oBAAoB,gBAAgB,KAAI,SAAQ,KAAK,UAAU,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,GACzF;EARgB;EACA;EAQhB,KAAK,OAAO;CACd;AACF;AAEA,IAAa,6BAAb,cAAgD,MAAM;CAElC;CACA;CACA;CAHlB,AAAO,YACL,AAAgB,WAChB,AAAgB,eAChB,AAAgB,WAChB;EACA,MACE,gBAAgB,KAAK,UAAU,SAAS,EAAE,6BACrC,KAAK,UAAU,aAAa,EAAE,gCAAgC,UAAU,+KAI/E;EAVgB;EACA;EACA;EAShB,KAAK,OAAO;CACd;AACF;AAEA,IAAa,6BAAb,cAAgD,MAAM;CAElC;CACA;CACA;CAHlB,AAAO,YACL,AAAgB,WAChB,AAAgB,gBAChB,AAAgB,WAChB;EACA,MACE,gBAAgB,KAAK,UAAU,SAA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