@warlock.js/web 5.2.4 → 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/discover-pages.mjs +5 -7
- package/esm/build/discover-pages.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/components/document-context.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/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/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/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/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/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/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/web-connector.d.mts +1 -1
- package/esm/server/web-connector.mjs +23 -4
- package/esm/server/web-connector.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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { composeRoutePath } from "../routing/compose-route-path.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { deriveFilesystemRoutePath } from "../routing/filesystem-route.mjs";
|
|
3
3
|
import { NestedLayoutsNotSupportedError, selectPageLayout } from "../routing/layout-policy.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { canonicalizeRouteExport, resolvePageRouteName } from "../routing/route-identity.mjs";
|
|
5
5
|
import { NOT_FOUND_ROUTE_NAME, NOT_FOUND_ROUTE_PATH, NotFoundPageDeclaresRouteError, isNotFoundPageFile } from "../server/not-found-page.mjs";
|
|
6
6
|
import { METADATA_KEYS, OPEN_GRAPH_KEYS, TWITTER_KEYS } from "../metadata.mjs";
|
|
7
7
|
import { assertPageHasDefaultExport } from "./page-default-export.mjs";
|
|
@@ -555,17 +555,15 @@ function discoverPages(options) {
|
|
|
555
555
|
if (prefix === void 0) return [];
|
|
556
556
|
return [[toPosix(path.relative(webRoot, path.dirname(layoutFile))), prefix]];
|
|
557
557
|
}));
|
|
558
|
-
const
|
|
558
|
+
const canonicalRoute = !isNotFoundPage && route ? canonicalizeRouteExport(route, relativePageFile) : void 0;
|
|
559
|
+
const effectiveRoutePath = isNotFoundPage ? "*" : canonicalRoute ? composeRoutePath(layoutPrefix, canonicalRoute.path) : deriveFilesystemRoutePath({
|
|
559
560
|
pageFile: relativePageFile,
|
|
560
561
|
layoutPrefixes
|
|
561
562
|
});
|
|
562
563
|
if (!isNotFoundPage && route !== void 0) explicitRouteFiles.add(relativeToApp(pageFile));
|
|
563
564
|
pages.push({
|
|
564
565
|
type: "page",
|
|
565
|
-
routeName: isNotFoundPage ? NOT_FOUND_ROUTE_NAME :
|
|
566
|
-
routePath: route.path,
|
|
567
|
-
sourceFile: relativeToApp(pageFile)
|
|
568
|
-
}) : deriveFilesystemRouteName(relativePageFile)),
|
|
566
|
+
routeName: isNotFoundPage ? NOT_FOUND_ROUTE_NAME : resolvePageRouteName(route, relativePageFile),
|
|
569
567
|
routePath: effectiveRoutePath,
|
|
570
568
|
pageFile,
|
|
571
569
|
webRoot,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discover-pages.mjs","names":[],"sources":["../../../../../../../web/src/build/discover-pages.ts"],"sourcesContent":["/**\n * Static discovery of the application's page graph — the ONE scan every\n * provider shares.\n *\n * This module has a single responsibility: look at the filesystem and produce\n * the recipe. It writes nothing, knows nothing about the generated barrel, and\n * imports neither Vite nor a single application module. Everything that turns\n * the recipe into an artefact (the production barrel, the dev plugin, the\n * generated client entry) lives with that artefact and consumes\n * {@link discoverPages}.\n *\n * The reason it is one module rather than one function per consumer: two\n * scanners that agree today drift tomorrow, and a page that exists for the\n * server but not the client is the silent failure that costs a day to find.\n * Sharing the scan makes that disagreement impossible by construction instead\n * of catchable by test.\n *\n * \"Static\" means WITHOUT RUNNING THE APPLICATION — this module globs\n * `*.page.tsx`, `layout.tsx` and `root.tsx`, and reads each page's declared\n * `route` and each layout's declared `prefix` by PARSING the source\n * ({@link readRouteExports}). It still imports no application module.\n *\n * An explicit `route` export wins. Otherwise the URL is derived from the page's\n * path beneath `src/web`: directories contribute segments, `(groups)` do not,\n * `index.page.tsx` claims its directory, and `[id]` becomes `:id`. A layout\n * `prefix` replaces its own directory segment. The same recipe is emitted to\n * every provider so build and boot cannot drift.\n *\n * Discovery also CLASSIFIES each layout — does its module have a default\n * export, does it export `middleware` — because the layout policy\n * ({@link \"../routing/layout-policy.ts\"}) owns the rule but may not touch a\n * filesystem to learn the facts the rule needs. That classification is another\n * parse, never an import: a layout is read exactly the way a page's `route` is.\n *\n * And it CHECKS the page's `metadata` keys ({@link UnknownMetadataKeyError}) —\n * see that error and {@link readMetadataKeys} for why a type alone does not\n * close that hole.\n */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { parse } from \"@babel/parser\";\nimport { composeRoutePath } from \"../routing/compose-route-path\";\n// `../server/not-found-page` is imported for its CONSTANTS and its filename\n// predicate only — that module has no runtime imports of its own, precisely so\n// this edge cannot drag the render pipeline into the build. What a not-found\n// page is, and what identity it carries, is decided in one place for discovery\n// and both installers.\nimport {\n isNotFoundPageFile,\n NotFoundPageDeclaresRouteError,\n NOT_FOUND_ROUTE_NAME,\n NOT_FOUND_ROUTE_PATH,\n} from \"../server/not-found-page\";\n// The metadata key set, as VALUES. `../metadata` is a types-plus-constants\n// module with no runtime imports of its own (both its imports are `import\n// type`), so this costs the build nothing and buys the one thing a parse cannot\n// get from a type: the list of keys a page is allowed to write.\nimport { METADATA_KEYS, OPEN_GRAPH_KEYS, TWITTER_KEYS } from \"../metadata\";\nimport { NestedLayoutsNotSupportedError, selectPageLayout } from \"../routing/layout-policy\";\nimport {\n deriveFilesystemRouteName,\n deriveFilesystemRoutePath,\n} from \"../routing/filesystem-route\";\nimport { deriveFallbackRouteName } from \"../routing/route-identity\";\nimport { assertPageHasDefaultExport } from \"./page-default-export\";\nimport type { RouteExportsReadResult } from \"./read-route-exports\";\nimport { NonLiteralRouteExportError, readRouteExports } from \"./read-route-exports\";\n\nexport type DiscoverPagesOptions = {\n /** Absolute path to the application root (where `package.json` lives). */\n appRoot: string;\n /** Source directory name under `appRoot`; defaults to `\"src\"`. */\n srcDir?: string;\n};\n\nexport type DiscoveredRoutablePage = {\n /** A browsable page. Error pages are deliberately a different discovery kind. */\n type: \"page\";\n /**\n * The page's route name: the `name` its `route` export declares, or its\n * filesystem identity as dotted segments, with groups omitted.\n *\n * Unique across the whole graph — {@link discoverPages} refuses to return a\n * result where it is not.\n */\n routeName: string;\n /**\n * The page's effective route path. Explicit routes retain their existing\n * layout-prefix composition. Derived routes use filesystem segments, with\n * each declared layout prefix replacing that layout directory's segment.\n * Always `/`-prefixed.\n */\n routePath: string;\n /** Absolute path to the `*.page.tsx` file. */\n pageFile: string;\n /** The web root this page was found under — the root its layout chain climbs to. */\n webRoot: string;\n /** Absolute paths of every `layout.tsx` from the web root down to the page's own directory, OUTERMOST FIRST. */\n layouts: string[];\n /**\n * The page's middleware chain: the subset of {@link layouts} whose modules\n * export `middleware`, OUTERMOST FIRST — the order they must run in.\n *\n * Source files rather than the middleware values themselves, because\n * discovery never runs application code: this says WHICH layouts contribute a\n * guard, and the consumer that already loads those modules reads the values\n * off them.\n *\n * Empty when no layout on the path declares middleware, which is the common\n * case; a page with no layouts always has an empty chain.\n */\n middlewareLayouts: string[];\n /** Absolute path to the global `root.tsx` every page renders inside, when it exists. */\n appFile?: string;\n};\n\n/** The one application error boundary. It deliberately has no route identity. */\nexport type DiscoveredErrorPage = {\n type: \"error\";\n /** Absolute path to the sole `error.page.tsx` beneath `src/web`. */\n pageFile: string;\n webRoot: string;\n appFile?: string;\n};\n\n/** The complete static web graph: routable leaves plus the optional error boundary. */\nexport type DiscoveredPage = DiscoveredRoutablePage | DiscoveredErrorPage;\n\nexport function isDiscoveredRoutablePage(page: DiscoveredPage): page is DiscoveredRoutablePage {\n return page.type === \"page\";\n}\n\nexport function isErrorPageFile(file: string): boolean {\n return path.basename(file) === \"error.page.tsx\";\n}\n\nexport class DuplicateErrorPageError extends Error {\n public constructor(firstFile: string, secondFile: string) {\n super(\n `Two error pages were found: \"${firstFile}\" and \"${secondFile}\". An application may own exactly one \\`error.page.tsx\\` anywhere beneath src/web.`,\n );\n this.name = \"DuplicateErrorPageError\";\n }\n}\n\nexport class ErrorPageDeclaresRouteError extends Error {\n public constructor(pageFile: string) {\n super(\n `The error page \"${pageFile}\" exports \\`route\\`. error.page.tsx is an error boundary, not a browsable page; remove the route export.`,\n );\n this.name = \"ErrorPageDeclaresRouteError\";\n }\n}\n\n/** Raised when two pages claim one route name. */\nexport class DuplicatePageRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly firstFile: string,\n public readonly secondFile: string,\n ) {\n super(\n `Two pages resolve to the same route name \"${routeName}\": \"${firstFile}\" and ` +\n `\"${secondFile}\". A route name identifies exactly one page, so the second ` +\n \"page would be unreachable. To fix: rename one of the files, or move it so \" +\n \"its directory gives it a different route name.\",\n );\n this.name = \"DuplicatePageRouteNameError\";\n }\n}\n\n/** Raised when two different page files resolve to one effective URL. */\nexport class DuplicatePageRoutePathError extends Error {\n public constructor(\n public readonly routePath: string,\n public readonly firstFile: string,\n public readonly secondFile: string,\n ) {\n super(\n `Two pages resolve to the same route path \"${routePath}\": \"${firstFile}\" and ` +\n `\"${secondFile}\". Each URL may identify exactly one page. Rename or move one file, ` +\n \"or give one page an explicit route with a different path.\",\n );\n this.name = \"DuplicatePageRoutePathError\";\n }\n}\n\nexport function toPosix(value: string): string {\n return value.replace(/\\\\/g, \"/\");\n}\n\nfunction isDirectory(candidate: string): boolean {\n try {\n return fs.statSync(candidate).isDirectory();\n } catch {\n return false;\n }\n}\n\nexport function isFile(candidate: string): boolean {\n try {\n return fs.statSync(candidate).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * The page root. It is optional; a project without it has zero pages, which is\n * a legal empty state.\n */\nexport function discoverWebRoots(srcRoot: string): string[] {\n const webRoot = path.join(srcRoot, \"web\");\n\n return isDirectory(webRoot) ? [webRoot] : [];\n}\n\nfunction byName(left: { name: string }, right: { name: string }): number {\n return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;\n}\n\nexport type DiscoveredPageFile = {\n /** Absolute path to the `*.page.tsx` file. */\n pageFile: string;\n /** The web root ({@link discoverWebRoots}) this page was found under. */\n webRoot: string;\n};\n\n/**\n * The subject list: every `*.page.tsx` under the page root, one call for the\n * whole graph.\n *\n * Unlike {@link discoverPages}, this reads no `route` or `prefix` export and\n * throws on nothing — it answers only \"which page files exist\", so a provider\n * that still resolves a page's route by its own means (dev's\n * `ssrLoadModule`-driven installer, chiefly) can share the walk without\n * inheriting the static-parsing refusals that answering \"what route is this\"\n * requires.\n */\nexport function discoverPageFiles(srcRoot: string): DiscoveredPageFile[] {\n const found: DiscoveredPageFile[] = [];\n\n for (const webRoot of discoverWebRoots(srcRoot)) {\n for (const pageFile of walkFiles(webRoot, (fileName) => fileName.endsWith(\".page.tsx\"))) {\n found.push({ pageFile, webRoot });\n }\n }\n\n return found;\n}\n\n/** Every file under `dir` (recursive) whose name matches `predicate`. */\nexport function walkFiles(dir: string, predicate: (fileName: string) => boolean): string[] {\n const found: string[] = [];\n\n for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort(byName)) {\n const full = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n found.push(...walkFiles(full, predicate));\n } else if (entry.isFile() && predicate(entry.name)) {\n found.push(full);\n }\n }\n\n return found;\n}\n\n/**\n * A page's layout chain: every `layout.tsx` in the directories from its web\n * root down to its own directory, OUTERMOST FIRST.\n *\n * Dev's installer reads only the nearest layout today, because its page module\n * triple holds a single layout; the recipe carries the whole chain so the\n * runtime side can compose\n * nested layouts without a second discovery pass. The nearest layout is always\n * the LAST element, so a consumer that still wants dev's one-layout behaviour\n * reads `layouts.at(-1)`.\n */\nexport function layoutChainFor(pageFile: string, webRoot: string): string[] {\n const chain: string[] = [];\n const relativeDir = path.relative(webRoot, path.dirname(pageFile));\n const segments = relativeDir === \"\" ? [] : relativeDir.split(path.sep);\n\n let current = webRoot;\n\n for (let index = 0; index <= segments.length; index++) {\n if (index > 0) {\n current = path.join(current, segments[index - 1]);\n }\n\n const candidate = path.join(current, \"layout.tsx\");\n\n if (isFile(candidate)) {\n chain.push(candidate);\n }\n }\n\n return chain;\n}\n\nfunction compareStrings(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\n/**\n * The total order every consumer sees, and the reason discovery returns an\n * array rather than a set: the page's SOURCE FILE PATH, lexicographic, POSIX.\n *\n * Serialization order only; matching precedence is a property of the route\n * grammar, not of this array.\n *\n * The file path rather than the route path, now that the route is the declared\n * one: a page's route can be rewritten by editing one line, which would reorder\n * an artefact that has not otherwise changed, while the file it lives in is the\n * stable identity the artefact is built from. It also carries no suggestion of\n * precedence — nobody reads \"sorted by file name\" as \"most specific first\",\n * which is the misreading a route-path order invites.\n *\n * Lexicographic because it is byte-comparable output across every provider,\n * which keeps diffs stable and keeps filesystem enumeration order out of the\n * artefact: two machines that list a directory differently must still produce\n * byte-identical output, or a build is only reproducible by luck.\n */\nfunction comparePages(left: DiscoveredPage, right: DiscoveredPage): number {\n return compareStrings(toPosix(left.pageFile), toPosix(right.pageFile));\n}\n\nfunction assertUniqueRouteNames(pages: readonly DiscoveredRoutablePage[], appRoot: string): void {\n const fileByRouteName = new Map<string, string>();\n\n for (const page of pages) {\n const existing = fileByRouteName.get(page.routeName);\n const relative = toPosix(path.relative(appRoot, page.pageFile));\n\n if (existing !== undefined) {\n throw new DuplicatePageRouteNameError(page.routeName, existing, relative);\n }\n\n fileByRouteName.set(page.routeName, relative);\n }\n}\n\n/**\n * A page's declared `route.path` is a choice its author made deliberately, so\n * two pages that both declare the same path are the author's call, not an\n * accident — {@link assertUniqueRouteNames} is what keeps each of them\n * reachable by name. What this refuses is a COLLISION NOBODY CHOSE: at least\n * one side's path is filesystem-derived, which is exactly the case a rename\n * or a new file can produce without anyone noticing two pages now answer the\n * same URL. The reserved not-found path (`\"*\"`) is never a candidate here\n * either way — it identifies no browsable URL, and {@link assertUniqueRouteNames}\n * already refuses a second `404.page.tsx` by its own reserved name.\n */\nfunction assertUniqueRoutePaths(\n pages: readonly DiscoveredRoutablePage[],\n appRoot: string,\n explicitFiles: ReadonlySet<string>,\n): void {\n const fileByRoutePath = new Map<string, string>();\n\n for (const page of pages) {\n if (page.routePath === NOT_FOUND_ROUTE_PATH) continue;\n\n const existing = fileByRoutePath.get(page.routePath);\n const relative = toPosix(path.relative(appRoot, page.pageFile));\n\n if (existing !== undefined && !(explicitFiles.has(existing) && explicitFiles.has(relative))) {\n throw new DuplicatePageRoutePathError(page.routePath, existing, relative);\n }\n\n if (existing === undefined) fileByRoutePath.set(page.routePath, relative);\n }\n}\n\n/** One key a page's `metadata` declares that nothing reads, and where it is written. */\nexport type UnknownMetadataKey = {\n /** The object it was declared in: `metadata`, `metadata.openGraph`, `metadata.twitter`. */\n container: string;\n /** The key exactly as the page wrote it. */\n key: string;\n /** 1-based line in the page file, so the message points at the character that is wrong. */\n line: number;\n /** The known key it is within two edits of, when there is one. Usually the whole answer. */\n suggestion?: string;\n};\n\n/**\n * Raised when a page's `metadata` export declares a key nothing reads.\n *\n * THE POINT OF THIS ERROR IS THE UNANNOTATED CASE. A page that writes\n * `export const metadata: PageMetadata = { tittle: \"x\" }` is already refused by\n * TypeScript, and if that were the whole story this class would not need to\n * exist. But the annotation is optional, nobody writes it, and\n * `export const metadata = { tittle: \"x\" }` is a perfectly well-typed program:\n * the compiler infers `{ tittle: string }`, has nothing to check it against, and\n * says nothing. The page is then served with no `<title>` — not a wrong title, a\n * missing one — and no error is raised anywhere, at build or at runtime, ever.\n *\n * So the check lives HERE instead, at the gate every page already passes\n * through: a page that silently omits requested metadata is worse than a build\n * that stops and says which line to fix.\n *\n * The alternative considered and rejected was a `defineMetadata({...})` wrapper,\n * which would infer the type for free. It also puts framework ceremony in every\n * page, and a page is meant to be two lines of framework surface (canon\n * `6ea0662f`). The gate gets the same safety without spending that.\n */\nexport class UnknownMetadataKeyError extends Error {\n public constructor(\n public readonly pageFile: string,\n public readonly unknownKeys: readonly UnknownMetadataKey[],\n ) {\n const findings = unknownKeys\n .map(({ container, key, line, suggestion }) => {\n const where = `line ${line}: \\`${container}.${key}\\` — no such key.`;\n\n return suggestion === undefined ? where : `${where} Did you mean \\`${suggestion}\\`?`;\n })\n .join(\"\\n \");\n\n super(\n `The \\`metadata\\` export of \"${pageFile}\" declares a key nothing reads:\\n ${findings}\\n` +\n \"Nothing writes an unknown key to `<head>`, so the tag it was meant to produce would \" +\n \"simply be absent from every response, with no error at build time or at runtime. The \" +\n \"build refuses it here instead.\\n\" +\n ` Known keys: ${METADATA_KEYS.join(\", \")}.\\n` +\n ` Inside \\`openGraph\\`: ${OPEN_GRAPH_KEYS.join(\", \")}.\\n` +\n ` Inside \\`twitter\\`: ${TWITTER_KEYS.join(\", \")}.\\n` +\n \"Annotating the export — `export const metadata: PageMetadata = { … }` — gets you the \" +\n \"same list as autocomplete in the editor, before the build runs.\",\n );\n this.name = \"UnknownMetadataKeyError\";\n }\n}\n\n/**\n * The AST types, derived from `parse`'s own return type rather than imported\n * from `@babel/types`, for the reason `read-route-exports.ts` gives: the parser\n * resolves its own copy of that package and nodes from one copy are not\n * assignable to the identical types from the other.\n */\ntype PageStatement = ReturnType<typeof parse>[\"program\"][\"body\"][number];\ntype PageExpression = Extract<PageStatement, { type: \"ExpressionStatement\" }>[\"expression\"];\ntype PageObjectExpression = Extract<PageExpression, { type: \"ObjectExpression\" }>;\ntype PageObjectProperty = Extract<\n PageObjectExpression[\"properties\"][number],\n { type: \"ObjectProperty\" }\n>;\ntype PageValueNode = PageObjectProperty[\"value\"];\n\n/** `as const`, `satisfies`, `!` and parentheses wrap a value without changing it. */\nfunction unwrapValue(node: PageValueNode): PageValueNode {\n switch (node.type) {\n case \"TSAsExpression\":\n case \"TSSatisfiesExpression\":\n case \"TSNonNullExpression\":\n case \"TypeCastExpression\":\n case \"ParenthesizedExpression\":\n return unwrapValue(node.expression);\n default:\n return node;\n }\n}\n\n/** Levenshtein distance — small strings, so the plain two-row table is the whole cost. */\nfunction editDistance(left: string, right: string): number {\n let previous = Array.from({ length: right.length + 1 }, (_, index) => index);\n\n for (let row = 1; row <= left.length; row++) {\n const current = [row];\n\n for (let column = 1; column <= right.length; column++) {\n const substitution = previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1);\n current[column] = Math.min(substitution, previous[column] + 1, current[column - 1] + 1);\n }\n\n previous = current;\n }\n\n return previous[right.length];\n}\n\n/**\n * The known key the written one was probably meant to be.\n *\n * Two edits, because that covers the typos this exists for — `tittle`,\n * `descriptoin`, `keywrods` — without reaching so far that `image` gets\n * suggested for `alt`. Case is ignored first, so `Title` resolves exactly.\n */\nfunction suggestKey(written: string, known: readonly string[]): string | undefined {\n const lowered = written.toLowerCase();\n const sameLetters = known.find((candidate) => candidate.toLowerCase() === lowered);\n\n if (sameLetters !== undefined) return sameLetters;\n\n let best: string | undefined;\n let bestDistance = Number.POSITIVE_INFINITY;\n\n for (const candidate of known) {\n const distance = editDistance(lowered, candidate.toLowerCase());\n\n if (distance < bestDistance) {\n best = candidate;\n bestDistance = distance;\n }\n }\n\n return bestDistance <= 2 ? best : undefined;\n}\n\n/** The name an object key denotes, or `undefined` when knowing it needs evaluation. */\nfunction propertyKeyName(property: PageObjectProperty): string | undefined {\n if (property.computed) return undefined;\n\n const { key } = property;\n\n if (key.type === \"Identifier\") return key.name;\n if (key.type === \"StringLiteral\") return key.value;\n\n return undefined;\n}\n\n/** The nested objects that carry a key set of their own. */\nconst NESTED_METADATA_KEYS: Record<string, readonly string[]> = {\n openGraph: OPEN_GRAPH_KEYS,\n twitter: TWITTER_KEYS,\n};\n\n/**\n * Every unknown key in one metadata object literal, and in the `openGraph` /\n * `twitter` literals inside it.\n *\n * A SPREAD does not suppress the check, unlike the route reader's rule: a\n * spread can only ADD keys, and no value it contributes can make a key written\n * out beside it correct. A COMPUTED key is skipped — its name is not knowable\n * without running the page, and refusing what cannot be read would fail builds\n * that are fine. Both are silence in the narrow places where the parse genuinely\n * does not know, and the annotation is the second net there.\n */\nfunction collectUnknownKeys(\n object: PageObjectExpression,\n allowed: readonly string[],\n container: string,\n into: UnknownMetadataKey[],\n): void {\n for (const property of object.properties) {\n if (property.type === \"SpreadElement\") continue;\n\n const key = propertyKeyName(property as PageObjectProperty);\n\n if (key === undefined) continue;\n\n if (!allowed.includes(key)) {\n const suggestion = suggestKey(key, allowed);\n\n into.push({\n container,\n key,\n line: property.loc?.start.line ?? 0,\n ...(suggestion === undefined ? {} : { suggestion }),\n });\n\n continue;\n }\n\n const nested = container === \"metadata\" ? NESTED_METADATA_KEYS[key] : undefined;\n\n if (nested === undefined || property.type !== \"ObjectProperty\") continue;\n\n const value = unwrapValue(property.value);\n\n if (value.type === \"ObjectExpression\") {\n collectUnknownKeys(value, nested, `${container}.${key}`, into);\n }\n }\n}\n\n/**\n * Every object literal a function form RETURNS, without descending into\n * functions nested inside it — a callback's return value is not the metadata.\n *\n * A generic walk rather than a statement-by-statement one because a `return` is\n * legal anywhere a statement is: inside an `if`, a `switch`, a `try`. Enumerating\n * the statement types that may contain one is a list that is wrong the moment\n * the language grows.\n */\nfunction collectReturnedObjects(node: unknown, into: PageObjectExpression[]): void {\n if (node === null || typeof node !== \"object\") return;\n\n if (Array.isArray(node)) {\n for (const item of node) collectReturnedObjects(item, into);\n\n return;\n }\n\n const candidate = node as { type?: string; argument?: unknown };\n\n if (\n candidate.type === \"FunctionDeclaration\" ||\n candidate.type === \"FunctionExpression\" ||\n candidate.type === \"ArrowFunctionExpression\" ||\n candidate.type === \"ObjectMethod\" ||\n candidate.type === \"ClassMethod\"\n ) {\n return;\n }\n\n if (candidate.type === \"ReturnStatement\") {\n if (candidate.argument === null || candidate.argument === undefined) return;\n\n const returned = unwrapValue(candidate.argument as PageValueNode);\n\n if (returned.type === \"ObjectExpression\") into.push(returned);\n\n // Not descending into the returned value: a `return` inside it belongs to a\n // function this walk is deliberately not entering.\n return;\n }\n\n for (const value of Object.values(node as Record<string, unknown>)) {\n collectReturnedObjects(value, into);\n }\n}\n\n/** The metadata object literals one `metadata` export declares, if any can be seen at all. */\nfunction metadataObjectsOf(init: PageValueNode): PageObjectExpression[] {\n const value = unwrapValue(init);\n\n if (value.type === \"ObjectExpression\") return [value];\n\n if (value.type === \"ArrowFunctionExpression\" || value.type === \"FunctionExpression\") {\n const body = unwrapValue(value.body as PageValueNode);\n\n // The concise arrow body — `({ data }) => ({ title: data.name })`, which is\n // how every function-form metadata export in the reference app is written.\n if (body.type === \"ObjectExpression\") return [body];\n\n const returned: PageObjectExpression[] = [];\n\n collectReturnedObjects(value.body, returned);\n\n return returned;\n }\n\n // `export const metadata = buildMetadata()`, or a bare identifier: the keys\n // are not in this file. Silent by design — see `collectUnknownKeys`.\n return [];\n}\n\n/**\n * The unknown keys a page's `metadata` export declares, read by PARSING — the\n * same rule the rest of this module lives by, and the reason this check can run\n * before anything is built.\n *\n * Empty for a page with no `metadata` export, for one whose metadata is a value\n * this file cannot see into, and for a correct one.\n */\nexport function readMetadataKeys(pageFile: string, source: string): UnknownMetadataKey[] {\n let program: ReturnType<typeof parse>[\"program\"];\n\n try {\n program = parse(source, {\n sourceType: \"module\",\n plugins: [\"typescript\", \"jsx\"],\n errorRecovery: false,\n }).program;\n } catch (error) {\n throw new Error(\n `Cannot read the \\`metadata\\` export of \"${pageFile}\": the file could not be parsed ` +\n `(${(error as Error).message}). Fix the syntax error and the build will continue.`,\n );\n }\n\n const unknownKeys: UnknownMetadataKey[] = [];\n\n for (const statement of program.body) {\n if (statement.type !== \"ExportNamedDeclaration\" || statement.exportKind === \"type\") continue;\n\n const { declaration } = statement;\n\n if (declaration?.type !== \"VariableDeclaration\") continue;\n\n for (const declarator of declaration.declarations) {\n if (declarator.id.type !== \"Identifier\" || declarator.id.name !== \"metadata\") continue;\n if (declarator.init === null || declarator.init === undefined) continue;\n\n for (const object of metadataObjectsOf(declarator.init)) {\n collectUnknownKeys(object, METADATA_KEYS, \"metadata\", unknownKeys);\n }\n }\n }\n\n return unknownKeys;\n}\n\n/**\n * The declared exports of one file, or a thrown\n * {@link NonLiteralRouteExportError} when they cannot be read without running\n * the application. Layouts are read once per run and remembered: a layout is\n * the nearest one for every page beside it, and parsing it once per page would\n * be the same answer bought repeatedly.\n *\n * `source` is the file's text when the caller already holds it — the page loop\n * reads each page once and spends that read on both the route declarations and\n * the metadata check, rather than opening the same file twice.\n */\nfunction readDeclarations(\n sourceFile: string,\n cache: Map<string, RouteExportsReadResult>,\n source?: string,\n) {\n let result = cache.get(sourceFile);\n\n if (result === undefined) {\n result = readRouteExports(sourceFile, source);\n cache.set(sourceFile, result);\n }\n\n if (!result.ok) {\n throw new NonLiteralRouteExportError(result.rejection);\n }\n\n return result;\n}\n\n/**\n * What a layout DOES, read by parsing it — the facts the layout policy's rule\n * needs and, being a pure module, cannot go and find for itself.\n */\ntype LayoutShape = {\n /**\n * Whether the module has a default export — the export that puts an element\n * in the document, and therefore the one thing that makes a layout count\n * against the single-rendering-layout rule.\n */\n renders: boolean;\n /** Whether the module exports `middleware`, or might via a re-export this cannot see through. */\n hasMiddleware: boolean;\n};\n\n/**\n * Parses one layout and reports its shape. Remembered per run for the same\n * reason declarations are: a layout is on the path of every page beneath it.\n */\nfunction readLayoutShape(layoutFile: string, cache: Map<string, LayoutShape>): LayoutShape {\n const cached = cache.get(layoutFile);\n\n if (cached !== undefined) return cached;\n\n const source = fs.readFileSync(layoutFile, \"utf-8\");\n let program: ReturnType<typeof parse>[\"program\"];\n\n try {\n program = parse(source, {\n sourceType: \"module\",\n // Every file this reads is a layout, i.e. `.tsx`.\n plugins: [\"typescript\", \"jsx\"],\n errorRecovery: false,\n }).program;\n } catch (error) {\n throw new Error(\n `Cannot read the exports of \"${layoutFile}\": the file could not be parsed ` +\n `(${(error as Error).message}). Fix the syntax error and the build will continue.`,\n );\n }\n\n const shape: LayoutShape = { renders: false, hasMiddleware: false };\n\n for (const statement of program.body) {\n if (statement.type === \"ExportDefaultDeclaration\") {\n shape.renders = true;\n continue;\n }\n\n // `export * from \"./guard\"` cannot re-export a default — the language\n // excludes it — but it CAN contribute `middleware`, and no parse can see\n // through it without resolving and reading another module. Reading it as\n // \"no middleware here\" is exactly the silent unguarding this slice exists\n // to prevent, so it is read as \"possibly\" and fails loudly downstream.\n if (statement.type === \"ExportAllDeclaration\") {\n shape.hasMiddleware = true;\n continue;\n }\n\n if (statement.type !== \"ExportNamedDeclaration\" || statement.exportKind === \"type\") continue;\n\n for (const specifier of statement.specifiers) {\n if (specifier.type !== \"ExportSpecifier\" || specifier.exportKind === \"type\") continue;\n\n const exported =\n specifier.exported.type === \"Identifier\"\n ? specifier.exported.name\n : specifier.exported.value;\n\n if (exported === \"default\") shape.renders = true;\n if (exported === \"middleware\") shape.hasMiddleware = true;\n }\n\n const { declaration } = statement;\n\n if (declaration === null || declaration === undefined) continue;\n\n if (declaration.type === \"VariableDeclaration\") {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === \"Identifier\" && declarator.id.name === \"middleware\") {\n shape.hasMiddleware = true;\n }\n }\n\n continue;\n }\n\n if (\n (declaration.type === \"FunctionDeclaration\" || declaration.type === \"ClassDeclaration\") &&\n declaration.id?.name === \"middleware\"\n ) {\n shape.hasMiddleware = true;\n }\n }\n\n cache.set(layoutFile, shape);\n\n return shape;\n}\n\n/**\n * Scans the page root and returns the pages in a defined total order.\n *\n * Zero pages is a legal result, not an error: a project may be configured\n * with web and have nothing to serve yet. What is an error is a `*.page.tsx`\n * with a route or metadata export that cannot be read statically; two pages\n * claiming one effective path or route name, which this refuses\n * to return at all — the alternative is an artefact in which one of them is\n * silently unreachable; a `route` or `prefix` that cannot be read without\n * running the application, which is refused before any page is reported at\n * all; a `metadata` export declaring a key nothing reads, which no compiler\n * catches unless the page opted into the type and which otherwise serves a page\n * with a silently missing tag; and a page whose layout chain holds more than one RENDERING layout, which\n * the production installer would refuse anyway — discovery refuses it first so\n * that artefact is never produced.\n */\nexport function discoverPages(options: DiscoverPagesOptions): DiscoveredPage[] {\n const { appRoot } = options;\n const srcRoot = path.join(appRoot, options.srcDir ?? \"src\");\n const webRoots = discoverWebRoots(srcRoot);\n const appFile = path.join(srcRoot, \"web\", \"root.tsx\");\n const hasAppFile = isFile(appFile);\n const declarations = new Map<string, RouteExportsReadResult>();\n const layoutShapes = new Map<string, LayoutShape>();\n const relativeToApp = (file: string) => toPosix(path.relative(appRoot, file));\n\n const pages: DiscoveredPage[] = [];\n const explicitRouteFiles = new Set<string>();\n let errorPage: DiscoveredErrorPage | undefined;\n\n for (const webRoot of webRoots) {\n for (const pageFile of walkFiles(webRoot, (fileName) => fileName.endsWith(\".page.tsx\"))) {\n const pageSource = fs.readFileSync(pageFile, \"utf-8\");\n assertPageHasDefaultExport(relativeToApp(pageFile), pageSource);\n const { route } = readDeclarations(pageFile, declarations, pageSource);\n if (isErrorPageFile(pageFile)) {\n if (route !== undefined) throw new ErrorPageDeclaresRouteError(relativeToApp(pageFile));\n\n if (errorPage !== undefined) {\n throw new DuplicateErrorPageError(relativeToApp(errorPage.pageFile), relativeToApp(pageFile));\n }\n\n errorPage = { type: \"error\", pageFile, webRoot, ...(hasAppFile ? { appFile } : {}) };\n continue;\n }\n const isNotFoundPage = isNotFoundPageFile(pageFile);\n\n // THE NOT-FOUND PAGE IS THE ONE PAGE WITH NO URL, in both directions.\n //\n // Every ordinary page may derive its URL from the filesystem.\n // `404.page.tsx` is reached by NOT matching, so the opposite remains the\n // error: a `route` export here reads as a promise that some path is\n // browsable, which the installers never keep.\n //\n // Discovery still reports it, with the SAME reserved identity both\n // installers register it under, so the emitted artefacts agree with the\n // server about which entry is the not-found page — and so the client\n // registry carries the module the SSR'd document has to hydrate against.\n if (isNotFoundPage && route !== undefined) {\n throw new NotFoundPageDeclaresRouteError(relativeToApp(pageFile));\n }\n\n // The page contract is not only `route`. `metadata` is the other export\n // every page may declare, and it is the one with no compiler behind it\n // unless the author opted in to a type annotation — so it is checked\n // here, by name, exactly like the route above.\n //\n // AFTER the reserved-404 route check on purpose: an impossible 404 route\n // contract is more fundamental than a malformed `<head>` declaration.\n const unknownMetadataKeys = readMetadataKeys(relativeToApp(pageFile), pageSource);\n\n if (unknownMetadataKeys.length > 0) {\n throw new UnknownMetadataKeyError(relativeToApp(pageFile), unknownMetadataKeys);\n }\n\n // The policy decides which layout the page RENDERS INSIDE, from the FULL\n // enumerated chain: a layout anywhere on the ancestry path counts, not\n // just one in the page's own directory. Discovery supplies the one fact\n // the rule needs and the pure policy cannot learn — whether each layout\n // renders anything at all.\n const layouts = layoutChainFor(pageFile, webRoot);\n const shapes = layouts.map((layoutFile) => readLayoutShape(layoutFile, layoutShapes));\n const selection = selectPageLayout(\n layouts.map((layout, index) => ({ layout, renders: shapes[index].renders })),\n );\n\n if (selection.type === \"rejected\") {\n throw new NestedLayoutsNotSupportedError(\n relativeToApp(pageFile),\n selection.layouts.map(relativeToApp),\n );\n }\n\n // Every layout that declares a guard, outermost first. Both installers\n // now CONCATENATE the whole chain into the pipeline's single layout slot\n // (`../server/install-page-routes.ts`, `../server/install-page-routes-from-manifest.ts`),\n // so a guard anywhere on the path runs, in this order — which is why the\n // temporary refusal that used to stand here is gone rather than relaxed.\n const middlewareLayouts = layouts.filter((_, index) => shapes[index].hasMiddleware);\n\n // EVERY prefix on the path, outermost first: a `prefix`-only layout is\n // still a segment of the URL, and composing only the rendering layout's\n // would serve the subtree from a path nobody declared.\n const layoutPrefix = layouts.reduce(\n (composed, layoutFile) =>\n composeRoutePath(composed, readDeclarations(layoutFile, declarations).prefix ?? \"/\"),\n \"/\",\n );\n\n const relativePageFile = toPosix(path.relative(webRoot, pageFile));\n const layoutPrefixes = Object.fromEntries(\n layouts.flatMap((layoutFile) => {\n const prefix = readDeclarations(layoutFile, declarations).prefix;\n if (prefix === undefined) return [];\n\n const directory = toPosix(path.relative(webRoot, path.dirname(layoutFile)));\n return [[directory, prefix]];\n }),\n );\n const effectiveRoutePath = isNotFoundPage\n ? NOT_FOUND_ROUTE_PATH\n : route\n ? composeRoutePath(layoutPrefix, route.path)\n : deriveFilesystemRoutePath({ pageFile: relativePageFile, layoutPrefixes });\n\n if (!isNotFoundPage && route !== undefined) {\n explicitRouteFiles.add(relativeToApp(pageFile));\n }\n\n pages.push({\n type: \"page\",\n routeName: isNotFoundPage\n ? NOT_FOUND_ROUTE_NAME\n : (route?.name ??\n (route\n ? deriveFallbackRouteName({\n routePath: route.path,\n sourceFile: relativeToApp(pageFile),\n })\n : deriveFilesystemRouteName(relativePageFile))),\n // The catch-all, which the client route matcher already understands as\n // a terminal `catch-all` token sorted LAST by specificity\n // (`../client/runtime/matcher.ts`) — so the browser resolves the\n // not-found page for a URL that matched nothing, exactly as the server\n // did, and never in preference to a real page.\n routePath: effectiveRoutePath,\n pageFile,\n webRoot,\n // THE NOT-FOUND PAGE RENDERS INSIDE THE APPLICATION ROOT AND NOTHING\n // ELSE — an EMPTY chain, not the one enumerated above.\n //\n // Both installers render it with `layoutFile: undefined`, deliberately\n // and independently (`../server/install-page-routes.ts`,\n // `../server/install-page-routes-from-manifest.ts`), for the same\n // reason the 404 page takes no loader: a path whose entire job is to\n // handle failure must not depend on chrome that can itself throw,\n // redirect, or need data. Reporting layouts here anyway put them in the\n // client registry and therefore in HYDRATION, so the server rendered\n // `App(Page)` while the browser rebuilt `App(Layout(Page))` — a\n // guaranteed mismatch on the one route nobody is watching, invisible to\n // any application that happens to have no layouts.\n //\n // Aligned by REMOVING them from the client, never by giving them to the\n // server: layouts on the not-found route would make it the most fragile\n // route in the application.\n //\n // The chain above is still enumerated and still validated, so a nested\n // layout on this page's path is refused at build time exactly as it is\n // everywhere else — what changes is only what the page renders inside.\n layouts: isNotFoundPage ? [] : layouts,\n middlewareLayouts: isNotFoundPage ? [] : middlewareLayouts,\n ...(hasAppFile ? { appFile } : {}),\n });\n }\n }\n\n // The error page is captured separately above so a second one can be\n // compared against the first before either is trusted — it joins the\n // returned graph here, once discovery knows there is exactly one.\n if (errorPage !== undefined) pages.push(errorPage);\n\n pages.sort(comparePages);\n\n const routablePages = pages.filter(isDiscoveredRoutablePage);\n assertUniqueRoutePaths(routablePages, appRoot, explicitRouteFiles);\n assertUniqueRouteNames(routablePages, appRoot);\n\n return pages;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgIA,SAAgB,yBAAyB,MAAsD;CAC7F,OAAO,KAAK,SAAS;AACvB;AAEA,SAAgB,gBAAgB,MAAuB;CACrD,OAAO,KAAK,SAAS,IAAI,MAAM;AACjC;AAEA,IAAa,0BAAb,cAA6C,MAAM;CACjD,AAAO,YAAY,WAAmB,YAAoB;EACxD,MACE,gCAAgC,UAAU,SAAS,WAAW,mFAChE;EACA,KAAK,OAAO;CACd;AACF;AAEA,IAAa,8BAAb,cAAiD,MAAM;CACrD,AAAO,YAAY,UAAkB;EACnC,MACE,mBAAmB,SAAS,yGAC9B;EACA,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,8BAAb,cAAiD,MAAM;CAEnC;CACA;CACA;CAHlB,AAAO,YACL,AAAgB,WAChB,AAAgB,WAChB,AAAgB,YAChB;EACA,MACE,6CAA6C,UAAU,MAAM,UAAU,SACjE,WAAW,oLAGnB;EATgB;EACA;EACA;EAQhB,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,8BAAb,cAAiD,MAAM;CAEnC;CACA;CACA;CAHlB,AAAO,YACL,AAAgB,WAChB,AAAgB,WAChB,AAAgB,YAChB;EACA,MACE,6CAA6C,UAAU,MAAM,UAAU,SACjE,WAAW,8HAEnB;EARgB;EACA;EACA;EAOhB,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,MAAM,QAAQ,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CAAC;EACjE,MAAM,iBAAiB,OAAO,YAC5B,QAAQ,SAAS,eAAe;GAC9B,MAAM,SAAS,iBAAiB,YAAY,YAAY,CAAC,CAAC;GAC1D,IAAI,WAAW,QAAW,OAAO,CAAC;GAGlC,OAAO,CAAC,CADU,QAAQ,KAAK,SAAS,SAAS,KAAK,QAAQ,UAAU,CAAC,CACxD,GAAG,MAAM,CAAC;EAC7B,CAAC,CACH;EACA,MAAM,qBAAqB,uBAEvB,QACE,iBAAiB,cAAc,MAAM,IAAI,IACzC,0BAA0B;GAAE,UAAU;GAAkB;EAAe,CAAC;EAE9E,IAAI,CAAC,kBAAkB,UAAU,QAC/B,mBAAmB,IAAI,cAAc,QAAQ,CAAC;EAGhD,MAAM,KAAK;GACT,MAAM;GACN,WAAW,iBACP,uBACC,OAAO,SACL,QACG,wBAAwB;IACtB,WAAW,MAAM;IACjB,YAAY,cAAc,QAAQ;GACpC,CAAC,IACD,0BAA0B,gBAAgB;GAMpD,WAAW;GACX;GACA;GAsBA,SAAS,iBAAiB,CAAC,IAAI;GAC/B,mBAAmB,iBAAiB,CAAC,IAAI;GACzC,GAAI,aAAa,EAAE,QAAQ,IAAI,CAAC;EAClC,CAAC;CACH;CAMF,IAAI,cAAc,QAAW,MAAM,KAAK,SAAS;CAEjD,MAAM,KAAK,YAAY;CAEvB,MAAM,gBAAgB,MAAM,OAAO,wBAAwB;CAC3D,uBAAuB,eAAe,SAAS,kBAAkB;CACjE,uBAAuB,eAAe,OAAO;CAE7C,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"discover-pages.mjs","names":[],"sources":["../../../../../../../web/src/build/discover-pages.ts"],"sourcesContent":["/**\r\n * Static discovery of the application's page graph — the ONE scan every\r\n * provider shares.\r\n *\r\n * This module has a single responsibility: look at the filesystem and produce\r\n * the recipe. It writes nothing, knows nothing about the generated barrel, and\r\n * imports neither Vite nor a single application module. Everything that turns\r\n * the recipe into an artefact (the production barrel, the dev plugin, the\r\n * generated client entry) lives with that artefact and consumes\r\n * {@link discoverPages}.\r\n *\r\n * The reason it is one module rather than one function per consumer: two\r\n * scanners that agree today drift tomorrow, and a page that exists for the\r\n * server but not the client is the silent failure that costs a day to find.\r\n * Sharing the scan makes that disagreement impossible by construction instead\r\n * of catchable by test.\r\n *\r\n * \"Static\" means WITHOUT RUNNING THE APPLICATION — this module globs\r\n * `*.page.tsx`, `layout.tsx` and `root.tsx`, and reads each page's declared\r\n * `route` and each layout's declared `prefix` by PARSING the source\r\n * ({@link readRouteExports}). It still imports no application module.\r\n *\r\n * An explicit `route` export wins. Otherwise the URL is derived from the page's\r\n * path beneath `src/web`: directories contribute segments, `(groups)` do not,\r\n * `index.page.tsx` claims its directory, and `[id]` becomes `:id`. A layout\r\n * `prefix` replaces its own directory segment. The same recipe is emitted to\r\n * every provider so build and boot cannot drift.\r\n *\r\n * Discovery also CLASSIFIES each layout — does its module have a default\r\n * export, does it export `middleware` — because the layout policy\r\n * ({@link \"../routing/layout-policy.ts\"}) owns the rule but may not touch a\r\n * filesystem to learn the facts the rule needs. That classification is another\r\n * parse, never an import: a layout is read exactly the way a page's `route` is.\r\n *\r\n * And it CHECKS the page's `metadata` keys ({@link UnknownMetadataKeyError}) —\r\n * see that error and {@link readMetadataKeys} for why a type alone does not\r\n * close that hole.\r\n */\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { parse } from \"@babel/parser\";\r\nimport { composeRoutePath } from \"../routing/compose-route-path\";\r\n// `../server/not-found-page` is imported for its CONSTANTS and its filename\r\n// predicate only. Its sole runtime import is the default fallback's build-time\r\n// stylesheet data URL; it imports no renderer or application runtime, so this\r\n// edge cannot drag the render pipeline into the build. What a not-found page is,\r\n// and what identity it carries, is decided in one place for discovery and both\r\n// installers.\r\nimport {\r\n isNotFoundPageFile,\r\n NotFoundPageDeclaresRouteError,\r\n NOT_FOUND_ROUTE_NAME,\r\n NOT_FOUND_ROUTE_PATH,\r\n} from \"../server/not-found-page\";\r\n// The metadata key set, as VALUES. `../metadata` is a types-plus-constants\r\n// module with no runtime imports of its own (both its imports are `import\r\n// type`), so this costs the build nothing and buys the one thing a parse cannot\r\n// get from a type: the list of keys a page is allowed to write.\r\nimport { METADATA_KEYS, OPEN_GRAPH_KEYS, TWITTER_KEYS } from \"../metadata\";\r\nimport { NestedLayoutsNotSupportedError, selectPageLayout } from \"../routing/layout-policy\";\r\nimport { deriveFilesystemRoutePath } from \"../routing/filesystem-route\";\r\nimport { canonicalizeRouteExport, resolvePageRouteName } from \"../routing/route-identity\";\r\nimport { assertPageHasDefaultExport } from \"./page-default-export\";\r\nimport type { RouteExportsReadResult } from \"./read-route-exports\";\r\nimport { NonLiteralRouteExportError, readRouteExports } from \"./read-route-exports\";\r\n\r\nexport type DiscoverPagesOptions = {\r\n /** Absolute path to the application root (where `package.json` lives). */\r\n appRoot: string;\r\n /** Source directory name under `appRoot`; defaults to `\"src\"`. */\r\n srcDir?: string;\r\n};\r\n\r\nexport type DiscoveredRoutablePage = {\r\n /** A browsable page. Error pages are deliberately a different discovery kind. */\r\n type: \"page\";\r\n /**\r\n * The page's route name: the `name` its `route` export declares, or its\r\n * filesystem identity as dotted segments, with groups omitted.\r\n *\r\n * Unique across the whole graph — {@link discoverPages} refuses to return a\r\n * result where it is not.\r\n */\r\n routeName: string;\r\n /**\r\n * The page's effective route path. Explicit routes retain their existing\r\n * layout-prefix composition. Derived routes use filesystem segments, with\r\n * each declared layout prefix replacing that layout directory's segment.\r\n * Always `/`-prefixed.\r\n */\r\n routePath: string;\r\n /** Absolute path to the `*.page.tsx` file. */\r\n pageFile: string;\r\n /** The web root this page was found under — the root its layout chain climbs to. */\r\n webRoot: string;\r\n /** Absolute paths of every `layout.tsx` from the web root down to the page's own directory, OUTERMOST FIRST. */\r\n layouts: string[];\r\n /**\r\n * The page's middleware chain: the subset of {@link layouts} whose modules\r\n * export `middleware`, OUTERMOST FIRST — the order they must run in.\r\n *\r\n * Source files rather than the middleware values themselves, because\r\n * discovery never runs application code: this says WHICH layouts contribute a\r\n * guard, and the consumer that already loads those modules reads the values\r\n * off them.\r\n *\r\n * Empty when no layout on the path declares middleware, which is the common\r\n * case; a page with no layouts always has an empty chain.\r\n */\r\n middlewareLayouts: string[];\r\n /** Absolute path to the global `root.tsx` every page renders inside, when it exists. */\r\n appFile?: string;\r\n};\r\n\r\n/** The one application error boundary. It deliberately has no route identity. */\r\nexport type DiscoveredErrorPage = {\r\n type: \"error\";\r\n /** Absolute path to the sole `error.page.tsx` beneath `src/web`. */\r\n pageFile: string;\r\n webRoot: string;\r\n appFile?: string;\r\n};\r\n\r\n/** The complete static web graph: routable leaves plus the optional error boundary. */\r\nexport type DiscoveredPage = DiscoveredRoutablePage | DiscoveredErrorPage;\r\n\r\nexport function isDiscoveredRoutablePage(page: DiscoveredPage): page is DiscoveredRoutablePage {\r\n return page.type === \"page\";\r\n}\r\n\r\nexport function isErrorPageFile(file: string): boolean {\r\n return path.basename(file) === \"error.page.tsx\";\r\n}\r\n\r\nexport class DuplicateErrorPageError extends Error {\r\n public constructor(firstFile: string, secondFile: string) {\r\n super(\r\n `Two error pages were found: \"${firstFile}\" and \"${secondFile}\". An application may own exactly one \\`error.page.tsx\\` anywhere beneath src/web.`,\r\n );\r\n this.name = \"DuplicateErrorPageError\";\r\n }\r\n}\r\n\r\nexport class ErrorPageDeclaresRouteError extends Error {\r\n public constructor(pageFile: string) {\r\n super(\r\n `The error page \"${pageFile}\" exports \\`route\\`. error.page.tsx is an error boundary, not a browsable page; remove the route export.`,\r\n );\r\n this.name = \"ErrorPageDeclaresRouteError\";\r\n }\r\n}\r\n\r\n/** Raised when two pages claim one route name. */\r\nexport class DuplicatePageRouteNameError extends Error {\r\n public constructor(\r\n public readonly routeName: string,\r\n public readonly firstFile: string,\r\n public readonly secondFile: string,\r\n ) {\r\n super(\r\n `Two pages resolve to the same route name \"${routeName}\": \"${firstFile}\" and ` +\r\n `\"${secondFile}\". A route name identifies exactly one page, so the second ` +\r\n \"page would be unreachable. To fix: rename one of the files, or move it so \" +\r\n \"its directory gives it a different route name.\",\r\n );\r\n this.name = \"DuplicatePageRouteNameError\";\r\n }\r\n}\r\n\r\n/** Raised when two different page files resolve to one effective URL. */\r\nexport class DuplicatePageRoutePathError extends Error {\r\n public constructor(\r\n public readonly routePath: string,\r\n public readonly firstFile: string,\r\n public readonly secondFile: string,\r\n ) {\r\n super(\r\n `Two pages resolve to the same route path \"${routePath}\": \"${firstFile}\" and ` +\r\n `\"${secondFile}\". Each URL may identify exactly one page. Rename or move one file, ` +\r\n \"or give one page an explicit route with a different path.\",\r\n );\r\n this.name = \"DuplicatePageRoutePathError\";\r\n }\r\n}\r\n\r\nexport function toPosix(value: string): string {\r\n return value.replace(/\\\\/g, \"/\");\r\n}\r\n\r\nfunction isDirectory(candidate: string): boolean {\r\n try {\r\n return fs.statSync(candidate).isDirectory();\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\nexport function isFile(candidate: string): boolean {\r\n try {\r\n return fs.statSync(candidate).isFile();\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * The page root. It is optional; a project without it has zero pages, which is\r\n * a legal empty state.\r\n */\r\nexport function discoverWebRoots(srcRoot: string): string[] {\r\n const webRoot = path.join(srcRoot, \"web\");\r\n\r\n return isDirectory(webRoot) ? [webRoot] : [];\r\n}\r\n\r\nfunction byName(left: { name: string }, right: { name: string }): number {\r\n return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;\r\n}\r\n\r\nexport type DiscoveredPageFile = {\r\n /** Absolute path to the `*.page.tsx` file. */\r\n pageFile: string;\r\n /** The web root ({@link discoverWebRoots}) this page was found under. */\r\n webRoot: string;\r\n};\r\n\r\n/**\r\n * The subject list: every `*.page.tsx` under the page root, one call for the\r\n * whole graph.\r\n *\r\n * Unlike {@link discoverPages}, this reads no `route` or `prefix` export and\r\n * throws on nothing — it answers only \"which page files exist\", so a provider\r\n * that still resolves a page's route by its own means (dev's\r\n * `ssrLoadModule`-driven installer, chiefly) can share the walk without\r\n * inheriting the static-parsing refusals that answering \"what route is this\"\r\n * requires.\r\n */\r\nexport function discoverPageFiles(srcRoot: string): DiscoveredPageFile[] {\r\n const found: DiscoveredPageFile[] = [];\r\n\r\n for (const webRoot of discoverWebRoots(srcRoot)) {\r\n for (const pageFile of walkFiles(webRoot, (fileName) => fileName.endsWith(\".page.tsx\"))) {\r\n found.push({ pageFile, webRoot });\r\n }\r\n }\r\n\r\n return found;\r\n}\r\n\r\n/** Every file under `dir` (recursive) whose name matches `predicate`. */\r\nexport function walkFiles(dir: string, predicate: (fileName: string) => boolean): string[] {\r\n const found: string[] = [];\r\n\r\n for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort(byName)) {\r\n const full = path.join(dir, entry.name);\r\n\r\n if (entry.isDirectory()) {\r\n found.push(...walkFiles(full, predicate));\r\n } else if (entry.isFile() && predicate(entry.name)) {\r\n found.push(full);\r\n }\r\n }\r\n\r\n return found;\r\n}\r\n\r\n/**\r\n * A page's layout chain: every `layout.tsx` in the directories from its web\r\n * root down to its own directory, OUTERMOST FIRST.\r\n *\r\n * Dev's installer reads only the nearest layout today, because its page module\r\n * triple holds a single layout; the recipe carries the whole chain so the\r\n * runtime side can compose\r\n * nested layouts without a second discovery pass. The nearest layout is always\r\n * the LAST element, so a consumer that still wants dev's one-layout behaviour\r\n * reads `layouts.at(-1)`.\r\n */\r\nexport function layoutChainFor(pageFile: string, webRoot: string): string[] {\r\n const chain: string[] = [];\r\n const relativeDir = path.relative(webRoot, path.dirname(pageFile));\r\n const segments = relativeDir === \"\" ? [] : relativeDir.split(path.sep);\r\n\r\n let current = webRoot;\r\n\r\n for (let index = 0; index <= segments.length; index++) {\r\n if (index > 0) {\r\n current = path.join(current, segments[index - 1]);\r\n }\r\n\r\n const candidate = path.join(current, \"layout.tsx\");\r\n\r\n if (isFile(candidate)) {\r\n chain.push(candidate);\r\n }\r\n }\r\n\r\n return chain;\r\n}\r\n\r\nfunction compareStrings(left: string, right: string): number {\r\n return left < right ? -1 : left > right ? 1 : 0;\r\n}\r\n\r\n/**\r\n * The total order every consumer sees, and the reason discovery returns an\r\n * array rather than a set: the page's SOURCE FILE PATH, lexicographic, POSIX.\r\n *\r\n * Serialization order only; matching precedence is a property of the route\r\n * grammar, not of this array.\r\n *\r\n * The file path rather than the route path, now that the route is the declared\r\n * one: a page's route can be rewritten by editing one line, which would reorder\r\n * an artefact that has not otherwise changed, while the file it lives in is the\r\n * stable identity the artefact is built from. It also carries no suggestion of\r\n * precedence — nobody reads \"sorted by file name\" as \"most specific first\",\r\n * which is the misreading a route-path order invites.\r\n *\r\n * Lexicographic because it is byte-comparable output across every provider,\r\n * which keeps diffs stable and keeps filesystem enumeration order out of the\r\n * artefact: two machines that list a directory differently must still produce\r\n * byte-identical output, or a build is only reproducible by luck.\r\n */\r\nfunction comparePages(left: DiscoveredPage, right: DiscoveredPage): number {\r\n return compareStrings(toPosix(left.pageFile), toPosix(right.pageFile));\r\n}\r\n\r\nfunction assertUniqueRouteNames(pages: readonly DiscoveredRoutablePage[], appRoot: string): void {\r\n const fileByRouteName = new Map<string, string>();\r\n\r\n for (const page of pages) {\r\n const existing = fileByRouteName.get(page.routeName);\r\n const relative = toPosix(path.relative(appRoot, page.pageFile));\r\n\r\n if (existing !== undefined) {\r\n throw new DuplicatePageRouteNameError(page.routeName, existing, relative);\r\n }\r\n\r\n fileByRouteName.set(page.routeName, relative);\r\n }\r\n}\r\n\r\n/**\r\n * A page's declared `route.path` is a choice its author made deliberately, so\r\n * two pages that both declare the same path are the author's call, not an\r\n * accident — {@link assertUniqueRouteNames} is what keeps each of them\r\n * reachable by name. What this refuses is a COLLISION NOBODY CHOSE: at least\r\n * one side's path is filesystem-derived, which is exactly the case a rename\r\n * or a new file can produce without anyone noticing two pages now answer the\r\n * same URL. The reserved not-found path (`\"*\"`) is never a candidate here\r\n * either way — it identifies no browsable URL, and {@link assertUniqueRouteNames}\r\n * already refuses a second `404.page.tsx` by its own reserved name.\r\n */\r\nfunction assertUniqueRoutePaths(\r\n pages: readonly DiscoveredRoutablePage[],\r\n appRoot: string,\r\n explicitFiles: ReadonlySet<string>,\r\n): void {\r\n const fileByRoutePath = new Map<string, string>();\r\n\r\n for (const page of pages) {\r\n if (page.routePath === NOT_FOUND_ROUTE_PATH) continue;\r\n\r\n const existing = fileByRoutePath.get(page.routePath);\r\n const relative = toPosix(path.relative(appRoot, page.pageFile));\r\n\r\n if (existing !== undefined && !(explicitFiles.has(existing) && explicitFiles.has(relative))) {\r\n throw new DuplicatePageRoutePathError(page.routePath, existing, relative);\r\n }\r\n\r\n if (existing === undefined) fileByRoutePath.set(page.routePath, relative);\r\n }\r\n}\r\n\r\n/** One key a page's `metadata` declares that nothing reads, and where it is written. */\r\nexport type UnknownMetadataKey = {\r\n /** The object it was declared in: `metadata`, `metadata.openGraph`, `metadata.twitter`. */\r\n container: string;\r\n /** The key exactly as the page wrote it. */\r\n key: string;\r\n /** 1-based line in the page file, so the message points at the character that is wrong. */\r\n line: number;\r\n /** The known key it is within two edits of, when there is one. Usually the whole answer. */\r\n suggestion?: string;\r\n};\r\n\r\n/**\r\n * Raised when a page's `metadata` export declares a key nothing reads.\r\n *\r\n * THE POINT OF THIS ERROR IS THE UNANNOTATED CASE. A page that writes\r\n * `export const metadata: PageMetadata = { tittle: \"x\" }` is already refused by\r\n * TypeScript, and if that were the whole story this class would not need to\r\n * exist. But the annotation is optional, nobody writes it, and\r\n * `export const metadata = { tittle: \"x\" }` is a perfectly well-typed program:\r\n * the compiler infers `{ tittle: string }`, has nothing to check it against, and\r\n * says nothing. The page is then served with no `<title>` — not a wrong title, a\r\n * missing one — and no error is raised anywhere, at build or at runtime, ever.\r\n *\r\n * So the check lives HERE instead, at the gate every page already passes\r\n * through: a page that silently omits requested metadata is worse than a build\r\n * that stops and says which line to fix.\r\n *\r\n * The alternative considered and rejected was a `defineMetadata({...})` wrapper,\r\n * which would infer the type for free. It also puts framework ceremony in every\r\n * page, and a page is meant to be two lines of framework surface (canon\r\n * `6ea0662f`). The gate gets the same safety without spending that.\r\n */\r\nexport class UnknownMetadataKeyError extends Error {\r\n public constructor(\r\n public readonly pageFile: string,\r\n public readonly unknownKeys: readonly UnknownMetadataKey[],\r\n ) {\r\n const findings = unknownKeys\r\n .map(({ container, key, line, suggestion }) => {\r\n const where = `line ${line}: \\`${container}.${key}\\` — no such key.`;\r\n\r\n return suggestion === undefined ? where : `${where} Did you mean \\`${suggestion}\\`?`;\r\n })\r\n .join(\"\\n \");\r\n\r\n super(\r\n `The \\`metadata\\` export of \"${pageFile}\" declares a key nothing reads:\\n ${findings}\\n` +\r\n \"Nothing writes an unknown key to `<head>`, so the tag it was meant to produce would \" +\r\n \"simply be absent from every response, with no error at build time or at runtime. The \" +\r\n \"build refuses it here instead.\\n\" +\r\n ` Known keys: ${METADATA_KEYS.join(\", \")}.\\n` +\r\n ` Inside \\`openGraph\\`: ${OPEN_GRAPH_KEYS.join(\", \")}.\\n` +\r\n ` Inside \\`twitter\\`: ${TWITTER_KEYS.join(\", \")}.\\n` +\r\n \"Annotating the export — `export const metadata: PageMetadata = { … }` — gets you the \" +\r\n \"same list as autocomplete in the editor, before the build runs.\",\r\n );\r\n this.name = \"UnknownMetadataKeyError\";\r\n }\r\n}\r\n\r\n/**\r\n * The AST types, derived from `parse`'s own return type rather than imported\r\n * from `@babel/types`, for the reason `read-route-exports.ts` gives: the parser\r\n * resolves its own copy of that package and nodes from one copy are not\r\n * assignable to the identical types from the other.\r\n */\r\ntype PageStatement = ReturnType<typeof parse>[\"program\"][\"body\"][number];\r\ntype PageExpression = Extract<PageStatement, { type: \"ExpressionStatement\" }>[\"expression\"];\r\ntype PageObjectExpression = Extract<PageExpression, { type: \"ObjectExpression\" }>;\r\ntype PageObjectProperty = Extract<\r\n PageObjectExpression[\"properties\"][number],\r\n { type: \"ObjectProperty\" }\r\n>;\r\ntype PageValueNode = PageObjectProperty[\"value\"];\r\n\r\n/** `as const`, `satisfies`, `!` and parentheses wrap a value without changing it. */\r\nfunction unwrapValue(node: PageValueNode): PageValueNode {\r\n switch (node.type) {\r\n case \"TSAsExpression\":\r\n case \"TSSatisfiesExpression\":\r\n case \"TSNonNullExpression\":\r\n case \"TypeCastExpression\":\r\n case \"ParenthesizedExpression\":\r\n return unwrapValue(node.expression);\r\n default:\r\n return node;\r\n }\r\n}\r\n\r\n/** Levenshtein distance — small strings, so the plain two-row table is the whole cost. */\r\nfunction editDistance(left: string, right: string): number {\r\n let previous = Array.from({ length: right.length + 1 }, (_, index) => index);\r\n\r\n for (let row = 1; row <= left.length; row++) {\r\n const current = [row];\r\n\r\n for (let column = 1; column <= right.length; column++) {\r\n const substitution = previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1);\r\n current[column] = Math.min(substitution, previous[column] + 1, current[column - 1] + 1);\r\n }\r\n\r\n previous = current;\r\n }\r\n\r\n return previous[right.length];\r\n}\r\n\r\n/**\r\n * The known key the written one was probably meant to be.\r\n *\r\n * Two edits, because that covers the typos this exists for — `tittle`,\r\n * `descriptoin`, `keywrods` — without reaching so far that `image` gets\r\n * suggested for `alt`. Case is ignored first, so `Title` resolves exactly.\r\n */\r\nfunction suggestKey(written: string, known: readonly string[]): string | undefined {\r\n const lowered = written.toLowerCase();\r\n const sameLetters = known.find((candidate) => candidate.toLowerCase() === lowered);\r\n\r\n if (sameLetters !== undefined) return sameLetters;\r\n\r\n let best: string | undefined;\r\n let bestDistance = Number.POSITIVE_INFINITY;\r\n\r\n for (const candidate of known) {\r\n const distance = editDistance(lowered, candidate.toLowerCase());\r\n\r\n if (distance < bestDistance) {\r\n best = candidate;\r\n bestDistance = distance;\r\n }\r\n }\r\n\r\n return bestDistance <= 2 ? best : undefined;\r\n}\r\n\r\n/** The name an object key denotes, or `undefined` when knowing it needs evaluation. */\r\nfunction propertyKeyName(property: PageObjectProperty): string | undefined {\r\n if (property.computed) return undefined;\r\n\r\n const { key } = property;\r\n\r\n if (key.type === \"Identifier\") return key.name;\r\n if (key.type === \"StringLiteral\") return key.value;\r\n\r\n return undefined;\r\n}\r\n\r\n/** The nested objects that carry a key set of their own. */\r\nconst NESTED_METADATA_KEYS: Record<string, readonly string[]> = {\r\n openGraph: OPEN_GRAPH_KEYS,\r\n twitter: TWITTER_KEYS,\r\n};\r\n\r\n/**\r\n * Every unknown key in one metadata object literal, and in the `openGraph` /\r\n * `twitter` literals inside it.\r\n *\r\n * A SPREAD does not suppress the check, unlike the route reader's rule: a\r\n * spread can only ADD keys, and no value it contributes can make a key written\r\n * out beside it correct. A COMPUTED key is skipped — its name is not knowable\r\n * without running the page, and refusing what cannot be read would fail builds\r\n * that are fine. Both are silence in the narrow places where the parse genuinely\r\n * does not know, and the annotation is the second net there.\r\n */\r\nfunction collectUnknownKeys(\r\n object: PageObjectExpression,\r\n allowed: readonly string[],\r\n container: string,\r\n into: UnknownMetadataKey[],\r\n): void {\r\n for (const property of object.properties) {\r\n if (property.type === \"SpreadElement\") continue;\r\n\r\n const key = propertyKeyName(property as PageObjectProperty);\r\n\r\n if (key === undefined) continue;\r\n\r\n if (!allowed.includes(key)) {\r\n const suggestion = suggestKey(key, allowed);\r\n\r\n into.push({\r\n container,\r\n key,\r\n line: property.loc?.start.line ?? 0,\r\n ...(suggestion === undefined ? {} : { suggestion }),\r\n });\r\n\r\n continue;\r\n }\r\n\r\n const nested = container === \"metadata\" ? NESTED_METADATA_KEYS[key] : undefined;\r\n\r\n if (nested === undefined || property.type !== \"ObjectProperty\") continue;\r\n\r\n const value = unwrapValue(property.value);\r\n\r\n if (value.type === \"ObjectExpression\") {\r\n collectUnknownKeys(value, nested, `${container}.${key}`, into);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Every object literal a function form RETURNS, without descending into\r\n * functions nested inside it — a callback's return value is not the metadata.\r\n *\r\n * A generic walk rather than a statement-by-statement one because a `return` is\r\n * legal anywhere a statement is: inside an `if`, a `switch`, a `try`. Enumerating\r\n * the statement types that may contain one is a list that is wrong the moment\r\n * the language grows.\r\n */\r\nfunction collectReturnedObjects(node: unknown, into: PageObjectExpression[]): void {\r\n if (node === null || typeof node !== \"object\") return;\r\n\r\n if (Array.isArray(node)) {\r\n for (const item of node) collectReturnedObjects(item, into);\r\n\r\n return;\r\n }\r\n\r\n const candidate = node as { type?: string; argument?: unknown };\r\n\r\n if (\r\n candidate.type === \"FunctionDeclaration\" ||\r\n candidate.type === \"FunctionExpression\" ||\r\n candidate.type === \"ArrowFunctionExpression\" ||\r\n candidate.type === \"ObjectMethod\" ||\r\n candidate.type === \"ClassMethod\"\r\n ) {\r\n return;\r\n }\r\n\r\n if (candidate.type === \"ReturnStatement\") {\r\n if (candidate.argument === null || candidate.argument === undefined) return;\r\n\r\n const returned = unwrapValue(candidate.argument as PageValueNode);\r\n\r\n if (returned.type === \"ObjectExpression\") into.push(returned);\r\n\r\n // Not descending into the returned value: a `return` inside it belongs to a\r\n // function this walk is deliberately not entering.\r\n return;\r\n }\r\n\r\n for (const value of Object.values(node as Record<string, unknown>)) {\r\n collectReturnedObjects(value, into);\r\n }\r\n}\r\n\r\n/** The metadata object literals one `metadata` export declares, if any can be seen at all. */\r\nfunction metadataObjectsOf(init: PageValueNode): PageObjectExpression[] {\r\n const value = unwrapValue(init);\r\n\r\n if (value.type === \"ObjectExpression\") return [value];\r\n\r\n if (value.type === \"ArrowFunctionExpression\" || value.type === \"FunctionExpression\") {\r\n const body = unwrapValue(value.body as PageValueNode);\r\n\r\n // The concise arrow body — `({ data }) => ({ title: data.name })`, which is\r\n // how every function-form metadata export in the reference app is written.\r\n if (body.type === \"ObjectExpression\") return [body];\r\n\r\n const returned: PageObjectExpression[] = [];\r\n\r\n collectReturnedObjects(value.body, returned);\r\n\r\n return returned;\r\n }\r\n\r\n // `export const metadata = buildMetadata()`, or a bare identifier: the keys\r\n // are not in this file. Silent by design — see `collectUnknownKeys`.\r\n return [];\r\n}\r\n\r\n/**\r\n * The unknown keys a page's `metadata` export declares, read by PARSING — the\r\n * same rule the rest of this module lives by, and the reason this check can run\r\n * before anything is built.\r\n *\r\n * Empty for a page with no `metadata` export, for one whose metadata is a value\r\n * this file cannot see into, and for a correct one.\r\n */\r\nexport function readMetadataKeys(pageFile: string, source: string): UnknownMetadataKey[] {\r\n let program: ReturnType<typeof parse>[\"program\"];\r\n\r\n try {\r\n program = parse(source, {\r\n sourceType: \"module\",\r\n plugins: [\"typescript\", \"jsx\"],\r\n errorRecovery: false,\r\n }).program;\r\n } catch (error) {\r\n throw new Error(\r\n `Cannot read the \\`metadata\\` export of \"${pageFile}\": the file could not be parsed ` +\r\n `(${(error as Error).message}). Fix the syntax error and the build will continue.`,\r\n );\r\n }\r\n\r\n const unknownKeys: UnknownMetadataKey[] = [];\r\n\r\n for (const statement of program.body) {\r\n if (statement.type !== \"ExportNamedDeclaration\" || statement.exportKind === \"type\") continue;\r\n\r\n const { declaration } = statement;\r\n\r\n if (declaration?.type !== \"VariableDeclaration\") continue;\r\n\r\n for (const declarator of declaration.declarations) {\r\n if (declarator.id.type !== \"Identifier\" || declarator.id.name !== \"metadata\") continue;\r\n if (declarator.init === null || declarator.init === undefined) continue;\r\n\r\n for (const object of metadataObjectsOf(declarator.init)) {\r\n collectUnknownKeys(object, METADATA_KEYS, \"metadata\", unknownKeys);\r\n }\r\n }\r\n }\r\n\r\n return unknownKeys;\r\n}\r\n\r\n/**\r\n * The declared exports of one file, or a thrown\r\n * {@link NonLiteralRouteExportError} when they cannot be read without running\r\n * the application. Layouts are read once per run and remembered: a layout is\r\n * the nearest one for every page beside it, and parsing it once per page would\r\n * be the same answer bought repeatedly.\r\n *\r\n * `source` is the file's text when the caller already holds it — the page loop\r\n * reads each page once and spends that read on both the route declarations and\r\n * the metadata check, rather than opening the same file twice.\r\n */\r\nfunction readDeclarations(\r\n sourceFile: string,\r\n cache: Map<string, RouteExportsReadResult>,\r\n source?: string,\r\n) {\r\n let result = cache.get(sourceFile);\r\n\r\n if (result === undefined) {\r\n result = readRouteExports(sourceFile, source);\r\n cache.set(sourceFile, result);\r\n }\r\n\r\n if (!result.ok) {\r\n throw new NonLiteralRouteExportError(result.rejection);\r\n }\r\n\r\n return result;\r\n}\r\n\r\n/**\r\n * What a layout DOES, read by parsing it — the facts the layout policy's rule\r\n * needs and, being a pure module, cannot go and find for itself.\r\n */\r\ntype LayoutShape = {\r\n /**\r\n * Whether the module has a default export — the export that puts an element\r\n * in the document, and therefore the one thing that makes a layout count\r\n * against the single-rendering-layout rule.\r\n */\r\n renders: boolean;\r\n /** Whether the module exports `middleware`, or might via a re-export this cannot see through. */\r\n hasMiddleware: boolean;\r\n};\r\n\r\n/**\r\n * Parses one layout and reports its shape. Remembered per run for the same\r\n * reason declarations are: a layout is on the path of every page beneath it.\r\n */\r\nfunction readLayoutShape(layoutFile: string, cache: Map<string, LayoutShape>): LayoutShape {\r\n const cached = cache.get(layoutFile);\r\n\r\n if (cached !== undefined) return cached;\r\n\r\n const source = fs.readFileSync(layoutFile, \"utf-8\");\r\n let program: ReturnType<typeof parse>[\"program\"];\r\n\r\n try {\r\n program = parse(source, {\r\n sourceType: \"module\",\r\n // Every file this reads is a layout, i.e. `.tsx`.\r\n plugins: [\"typescript\", \"jsx\"],\r\n errorRecovery: false,\r\n }).program;\r\n } catch (error) {\r\n throw new Error(\r\n `Cannot read the exports of \"${layoutFile}\": the file could not be parsed ` +\r\n `(${(error as Error).message}). Fix the syntax error and the build will continue.`,\r\n );\r\n }\r\n\r\n const shape: LayoutShape = { renders: false, hasMiddleware: false };\r\n\r\n for (const statement of program.body) {\r\n if (statement.type === \"ExportDefaultDeclaration\") {\r\n shape.renders = true;\r\n continue;\r\n }\r\n\r\n // `export * from \"./guard\"` cannot re-export a default — the language\r\n // excludes it — but it CAN contribute `middleware`, and no parse can see\r\n // through it without resolving and reading another module. Reading it as\r\n // \"no middleware here\" is exactly the silent unguarding this slice exists\r\n // to prevent, so it is read as \"possibly\" and fails loudly downstream.\r\n if (statement.type === \"ExportAllDeclaration\") {\r\n shape.hasMiddleware = true;\r\n continue;\r\n }\r\n\r\n if (statement.type !== \"ExportNamedDeclaration\" || statement.exportKind === \"type\") continue;\r\n\r\n for (const specifier of statement.specifiers) {\r\n if (specifier.type !== \"ExportSpecifier\" || specifier.exportKind === \"type\") continue;\r\n\r\n const exported =\r\n specifier.exported.type === \"Identifier\"\r\n ? specifier.exported.name\r\n : specifier.exported.value;\r\n\r\n if (exported === \"default\") shape.renders = true;\r\n if (exported === \"middleware\") shape.hasMiddleware = true;\r\n }\r\n\r\n const { declaration } = statement;\r\n\r\n if (declaration === null || declaration === undefined) continue;\r\n\r\n if (declaration.type === \"VariableDeclaration\") {\r\n for (const declarator of declaration.declarations) {\r\n if (declarator.id.type === \"Identifier\" && declarator.id.name === \"middleware\") {\r\n shape.hasMiddleware = true;\r\n }\r\n }\r\n\r\n continue;\r\n }\r\n\r\n if (\r\n (declaration.type === \"FunctionDeclaration\" || declaration.type === \"ClassDeclaration\") &&\r\n declaration.id?.name === \"middleware\"\r\n ) {\r\n shape.hasMiddleware = true;\r\n }\r\n }\r\n\r\n cache.set(layoutFile, shape);\r\n\r\n return shape;\r\n}\r\n\r\n/**\r\n * Scans the page root and returns the pages in a defined total order.\r\n *\r\n * Zero pages is a legal result, not an error: a project may be configured\r\n * with web and have nothing to serve yet. What is an error is a `*.page.tsx`\r\n * with a route or metadata export that cannot be read statically; two pages\r\n * claiming one effective path or route name, which this refuses\r\n * to return at all — the alternative is an artefact in which one of them is\r\n * silently unreachable; a `route` or `prefix` that cannot be read without\r\n * running the application, which is refused before any page is reported at\r\n * all; a `metadata` export declaring a key nothing reads, which no compiler\r\n * catches unless the page opted into the type and which otherwise serves a page\r\n * with a silently missing tag; and a page whose layout chain holds more than one RENDERING layout, which\r\n * the production installer would refuse anyway — discovery refuses it first so\r\n * that artefact is never produced.\r\n */\r\nexport function discoverPages(options: DiscoverPagesOptions): DiscoveredPage[] {\r\n const { appRoot } = options;\r\n const srcRoot = path.join(appRoot, options.srcDir ?? \"src\");\r\n const webRoots = discoverWebRoots(srcRoot);\r\n const appFile = path.join(srcRoot, \"web\", \"root.tsx\");\r\n const hasAppFile = isFile(appFile);\r\n const declarations = new Map<string, RouteExportsReadResult>();\r\n const layoutShapes = new Map<string, LayoutShape>();\r\n const relativeToApp = (file: string) => toPosix(path.relative(appRoot, file));\r\n\r\n const pages: DiscoveredPage[] = [];\r\n const explicitRouteFiles = new Set<string>();\r\n let errorPage: DiscoveredErrorPage | undefined;\r\n\r\n for (const webRoot of webRoots) {\r\n for (const pageFile of walkFiles(webRoot, (fileName) => fileName.endsWith(\".page.tsx\"))) {\r\n const pageSource = fs.readFileSync(pageFile, \"utf-8\");\r\n assertPageHasDefaultExport(relativeToApp(pageFile), pageSource);\r\n const { route } = readDeclarations(pageFile, declarations, pageSource);\r\n if (isErrorPageFile(pageFile)) {\r\n if (route !== undefined) throw new ErrorPageDeclaresRouteError(relativeToApp(pageFile));\r\n\r\n if (errorPage !== undefined) {\r\n throw new DuplicateErrorPageError(\r\n relativeToApp(errorPage.pageFile),\r\n relativeToApp(pageFile),\r\n );\r\n }\r\n\r\n errorPage = { type: \"error\", pageFile, webRoot, ...(hasAppFile ? { appFile } : {}) };\r\n continue;\r\n }\r\n const isNotFoundPage = isNotFoundPageFile(pageFile);\r\n\r\n // THE NOT-FOUND PAGE IS THE ONE PAGE WITH NO URL, in both directions.\r\n //\r\n // Every ordinary page may derive its URL from the filesystem.\r\n // `404.page.tsx` is reached by NOT matching, so the opposite remains the\r\n // error: a `route` export here reads as a promise that some path is\r\n // browsable, which the installers never keep.\r\n //\r\n // Discovery still reports it, with the SAME reserved identity both\r\n // installers register it under, so the emitted artefacts agree with the\r\n // server about which entry is the not-found page — and so the client\r\n // registry carries the module the SSR'd document has to hydrate against.\r\n if (isNotFoundPage && route !== undefined) {\r\n throw new NotFoundPageDeclaresRouteError(relativeToApp(pageFile));\r\n }\r\n\r\n // The page contract is not only `route`. `metadata` is the other export\r\n // every page may declare, and it is the one with no compiler behind it\r\n // unless the author opted in to a type annotation — so it is checked\r\n // here, by name, exactly like the route above.\r\n //\r\n // AFTER the reserved-404 route check on purpose: an impossible 404 route\r\n // contract is more fundamental than a malformed `<head>` declaration.\r\n const unknownMetadataKeys = readMetadataKeys(relativeToApp(pageFile), pageSource);\r\n\r\n if (unknownMetadataKeys.length > 0) {\r\n throw new UnknownMetadataKeyError(relativeToApp(pageFile), unknownMetadataKeys);\r\n }\r\n\r\n // The policy decides which layout the page RENDERS INSIDE, from the FULL\r\n // enumerated chain: a layout anywhere on the ancestry path counts, not\r\n // just one in the page's own directory. Discovery supplies the one fact\r\n // the rule needs and the pure policy cannot learn — whether each layout\r\n // renders anything at all.\r\n const layouts = layoutChainFor(pageFile, webRoot);\r\n const shapes = layouts.map((layoutFile) => readLayoutShape(layoutFile, layoutShapes));\r\n const selection = selectPageLayout(\r\n layouts.map((layout, index) => ({ layout, renders: shapes[index].renders })),\r\n );\r\n\r\n if (selection.type === \"rejected\") {\r\n throw new NestedLayoutsNotSupportedError(\r\n relativeToApp(pageFile),\r\n selection.layouts.map(relativeToApp),\r\n );\r\n }\r\n\r\n // Every layout that declares a guard, outermost first. Both installers\r\n // now CONCATENATE the whole chain into the pipeline's single layout slot\r\n // (`../server/install-page-routes.ts`, `../server/install-page-routes-from-manifest.ts`),\r\n // so a guard anywhere on the path runs, in this order — which is why the\r\n // temporary refusal that used to stand here is gone rather than relaxed.\r\n const middlewareLayouts = layouts.filter((_, index) => shapes[index].hasMiddleware);\r\n\r\n // EVERY prefix on the path, outermost first: a `prefix`-only layout is\r\n // still a segment of the URL, and composing only the rendering layout's\r\n // would serve the subtree from a path nobody declared.\r\n const layoutPrefix = layouts.reduce(\r\n (composed, layoutFile) =>\r\n composeRoutePath(composed, readDeclarations(layoutFile, declarations).prefix ?? \"/\"),\r\n \"/\",\r\n );\r\n\r\n const relativePageFile = toPosix(path.relative(webRoot, pageFile));\r\n const layoutPrefixes = Object.fromEntries(\r\n layouts.flatMap((layoutFile) => {\r\n const prefix = readDeclarations(layoutFile, declarations).prefix;\r\n if (prefix === undefined) return [];\r\n\r\n const directory = toPosix(path.relative(webRoot, path.dirname(layoutFile)));\r\n return [[directory, prefix]];\r\n }),\r\n );\r\n // Routed through `canonicalizeRouteExport` — the ONE seam that validates\r\n // a declared `route.path` (`../routing/route-identity.ts`) — rather than\r\n // reading `route.path` directly, so `effectiveRoutePath` can never carry\r\n // a path the grammar has rejected. This does not depend on `routeName`\r\n // (below) also validating: even if that field were reordered, made\r\n // conditional, or removed, an unsupported declared path still cannot\r\n // reach `effectiveRoutePath` unvalidated.\r\n const canonicalRoute =\r\n !isNotFoundPage && route ? canonicalizeRouteExport(route, relativePageFile) : undefined;\r\n\r\n const effectiveRoutePath = isNotFoundPage\r\n ? NOT_FOUND_ROUTE_PATH\r\n : canonicalRoute\r\n ? composeRoutePath(layoutPrefix, canonicalRoute.path)\r\n : deriveFilesystemRoutePath({ pageFile: relativePageFile, layoutPrefixes });\r\n\r\n if (!isNotFoundPage && route !== undefined) {\r\n explicitRouteFiles.add(relativeToApp(pageFile));\r\n }\r\n\r\n pages.push({\r\n type: \"page\",\r\n routeName: isNotFoundPage\r\n ? NOT_FOUND_ROUTE_NAME\r\n : resolvePageRouteName(route, relativePageFile),\r\n // The catch-all, which the client route matcher already understands as\r\n // a terminal `catch-all` token sorted LAST by specificity\r\n // (`../client/runtime/matcher.ts`) — so the browser resolves the\r\n // not-found page for a URL that matched nothing, exactly as the server\r\n // did, and never in preference to a real page.\r\n routePath: effectiveRoutePath,\r\n pageFile,\r\n webRoot,\r\n // THE NOT-FOUND PAGE RENDERS INSIDE THE APPLICATION ROOT AND NOTHING\r\n // ELSE — an EMPTY chain, not the one enumerated above.\r\n //\r\n // Both installers render it with `layoutFile: undefined`, deliberately\r\n // and independently (`../server/install-page-routes.ts`,\r\n // `../server/install-page-routes-from-manifest.ts`), for the same\r\n // reason the 404 page takes no loader: a path whose entire job is to\r\n // handle failure must not depend on chrome that can itself throw,\r\n // redirect, or need data. Reporting layouts here anyway put them in the\r\n // client registry and therefore in HYDRATION, so the server rendered\r\n // `App(Page)` while the browser rebuilt `App(Layout(Page))` — a\r\n // guaranteed mismatch on the one route nobody is watching, invisible to\r\n // any application that happens to have no layouts.\r\n //\r\n // Aligned by REMOVING them from the client, never by giving them to the\r\n // server: layouts on the not-found route would make it the most fragile\r\n // route in the application.\r\n //\r\n // The chain above is still enumerated and still validated, so a nested\r\n // layout on this page's path is refused at build time exactly as it is\r\n // everywhere else — what changes is only what the page renders inside.\r\n layouts: isNotFoundPage ? [] : layouts,\r\n middlewareLayouts: isNotFoundPage ? [] : middlewareLayouts,\r\n ...(hasAppFile ? { appFile } : {}),\r\n });\r\n }\r\n }\r\n\r\n // The error page is captured separately above so a second one can be\r\n // compared against the first before either is trusted — it joins the\r\n // returned graph here, once discovery knows there is exactly one.\r\n if (errorPage !== undefined) pages.push(errorPage);\r\n\r\n pages.sort(comparePages);\r\n\r\n const routablePages = pages.filter(isDiscoveredRoutablePage);\r\n assertUniqueRoutePaths(routablePages, appRoot, explicitRouteFiles);\r\n assertUniqueRouteNames(routablePages, appRoot);\r\n\r\n return pages;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8HA,SAAgB,yBAAyB,MAAsD;CAC7F,OAAO,KAAK,SAAS;AACvB;AAEA,SAAgB,gBAAgB,MAAuB;CACrD,OAAO,KAAK,SAAS,IAAI,MAAM;AACjC;AAEA,IAAa,0BAAb,cAA6C,MAAM;CACjD,AAAO,YAAY,WAAmB,YAAoB;EACxD,MACE,gCAAgC,UAAU,SAAS,WAAW,mFAChE;EACA,KAAK,OAAO;CACd;AACF;AAEA,IAAa,8BAAb,cAAiD,MAAM;CACrD,AAAO,YAAY,UAAkB;EACnC,MACE,mBAAmB,SAAS,yGAC9B;EACA,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,8BAAb,cAAiD,MAAM;CAEnC;CACA;CACA;CAHlB,AAAO,YACL,AAAgB,WAChB,AAAgB,WAChB,AAAgB,YAChB;EACA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e,SAAS,kBAAkB;CACjE,uBAAuB,eAAe,OAAO;CAE7C,OAAO;AACT"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { hydrateShared } from "../shared.mjs";
|
|
2
2
|
import { DocumentContext } from "../components/document-context.mjs";
|
|
3
3
|
import { readHydrationPayload } from "../hydration-payload.mjs";
|
|
4
|
-
import { hydrateRoot } from "react-dom/client";
|
|
5
4
|
import { jsx } from "react/jsx-runtime";
|
|
5
|
+
import { hydrateRoot } from "react-dom/client";
|
|
6
6
|
|
|
7
7
|
//#region ../web/src/client/hydrate-page.tsx
|
|
8
8
|
/**
|
|
@@ -31,8 +31,9 @@ function reportHydrationFailure(error) {
|
|
|
31
31
|
/**
|
|
32
32
|
* The one hydration entry point. Mounts at `#root` only — the page subtree —
|
|
33
33
|
* never `document`/`html`/`head`/`body` (hydration-payload-contract-2026-08-22.md
|
|
34
|
-
* §2): `metadata`, `
|
|
35
|
-
*
|
|
34
|
+
* §2): `metadata`, `dir`, and `nonce` are not used to rebuild the mounted tree;
|
|
35
|
+
* the declared `locale` key is consumed by `NavigationRoot`'s provider.
|
|
36
|
+
* `readHydrationPayload` (web/src/hydration-payload.ts,
|
|
36
37
|
* Vega's slice B) is the one place ABSENT/MALFORMED are decided, so this
|
|
37
38
|
* function does not re-implement that check — reusing it is what keeps the
|
|
38
39
|
* two throw messages from drifting apart at a second site. On ABSENT/MALFORMED
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydrate-page.mjs","names":[],"sources":["../../../../../../../web/src/client/hydrate-page.tsx"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport { DocumentContext, type DocumentContextValue } from \"../components/document-context\";\nimport { readHydrationPayload, type HydrationDocumentPayloadSource } from \"../hydration-payload\";\nimport { hydrateShared } from \"../shared\";\n\n/**\n * The hydration MOUNT point — a different id from the payload script's id.\n * Not exported anywhere as a named constant (`default-app.tsx:39` only\n * renders the literal `<div id=\"root\">`), so a local literal is fine here:\n * the contract's no-duplicate-literal rule is specifically about the payload\n * script id, which `readHydrationPayload` already owns exclusively\n * (hydration-payload-contract-2026-08-22.md §4).\n */\nconst MOUNT_ELEMENT_ID = \"root\";\n\n/**\n * Receives the VALIDATED payload and returns the ReactNode to hydrate. A\n * callback rather than a ready-made ReactNode: composing the real Layout(Page)\n * tree needs `payload.layoutData`/`pageData`/`shared`, which only exist after\n * `readHydrationPayload()` has already succeeded — building the tree first and\n * validating second would get the order backwards.\n *\n * A Promise is allowed because the real composer resolves the page's chunk\n * through the registry's dynamic `import()`. Returning it does NOT move the\n * payload check later: the callback is still only reached once the payload has\n * validated, and only the tree it produces is awaited.\n */\nexport type BuildHydratedTree = (\n payload: HydrationDocumentPayloadSource,\n) => ReactNode | Promise<ReactNode>;\n\nfunction isPromise(value: ReactNode | Promise<ReactNode>): value is Promise<ReactNode> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * The awaited path's failure sink. By the time a `buildTree` promise rejects\n * the synchronous stack is gone, so there is no caller left to throw at — and\n * an un-attached rejection is a blank console, which is the silent-failure\n * class this pipeline keeps regressing into. Reported loudly, and deliberately\n * WITHOUT touching `#root`: the server's markup is correct and visible, it is\n * only un-hydrated, so clearing it would turn a degraded page into a blank one.\n */\nfunction reportHydrationFailure(error: unknown): void {\n console.error(\n \"Warlock hydration failed after the page tree was requested. The server-rendered \" +\n \"markup is left on screen un-hydrated; #root was not cleared.\",\n error,\n );\n}\n\n/**\n * The one hydration entry point. Mounts at `#root` only — the page subtree —\n * never `document`/`html`/`head`/`body` (hydration-payload-contract-2026-08-22.md\n * §2): `metadata`, `
|
|
1
|
+
{"version":3,"file":"hydrate-page.mjs","names":[],"sources":["../../../../../../../web/src/client/hydrate-page.tsx"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport { DocumentContext, type DocumentContextValue } from \"../components/document-context\";\nimport { readHydrationPayload, type HydrationDocumentPayloadSource } from \"../hydration-payload\";\nimport { hydrateShared } from \"../shared\";\n\n/**\n * The hydration MOUNT point — a different id from the payload script's id.\n * Not exported anywhere as a named constant (`default-app.tsx:39` only\n * renders the literal `<div id=\"root\">`), so a local literal is fine here:\n * the contract's no-duplicate-literal rule is specifically about the payload\n * script id, which `readHydrationPayload` already owns exclusively\n * (hydration-payload-contract-2026-08-22.md §4).\n */\nconst MOUNT_ELEMENT_ID = \"root\";\n\n/**\n * Receives the VALIDATED payload and returns the ReactNode to hydrate. A\n * callback rather than a ready-made ReactNode: composing the real Layout(Page)\n * tree needs `payload.layoutData`/`pageData`/`shared`, which only exist after\n * `readHydrationPayload()` has already succeeded — building the tree first and\n * validating second would get the order backwards.\n *\n * A Promise is allowed because the real composer resolves the page's chunk\n * through the registry's dynamic `import()`. Returning it does NOT move the\n * payload check later: the callback is still only reached once the payload has\n * validated, and only the tree it produces is awaited.\n */\nexport type BuildHydratedTree = (\n payload: HydrationDocumentPayloadSource,\n) => ReactNode | Promise<ReactNode>;\n\nfunction isPromise(value: ReactNode | Promise<ReactNode>): value is Promise<ReactNode> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * The awaited path's failure sink. By the time a `buildTree` promise rejects\n * the synchronous stack is gone, so there is no caller left to throw at — and\n * an un-attached rejection is a blank console, which is the silent-failure\n * class this pipeline keeps regressing into. Reported loudly, and deliberately\n * WITHOUT touching `#root`: the server's markup is correct and visible, it is\n * only un-hydrated, so clearing it would turn a degraded page into a blank one.\n */\nfunction reportHydrationFailure(error: unknown): void {\n console.error(\n \"Warlock hydration failed after the page tree was requested. The server-rendered \" +\n \"markup is left on screen un-hydrated; #root was not cleared.\",\n error,\n );\n}\n\n/**\n * The one hydration entry point. Mounts at `#root` only — the page subtree —\n * never `document`/`html`/`head`/`body` (hydration-payload-contract-2026-08-22.md\n * §2): `metadata`, `dir`, and `nonce` are not used to rebuild the mounted tree;\n * the declared `locale` key is consumed by `NavigationRoot`'s provider.\n * `readHydrationPayload` (web/src/hydration-payload.ts,\n * Vega's slice B) is the one place ABSENT/MALFORMED are decided, so this\n * function does not re-implement that check — reusing it is what keeps the\n * two throw messages from drifting apart at a second site. On ABSENT/MALFORMED\n * it throws before touching `#root`, so the server-rendered markup stays\n * visible; nothing is cleared or re-rendered.\n *\n * Order is load-bearing and unchanged by the async tree: payload validated,\n * shared snapshot installed, `#root` resolved and its absence thrown on — all\n * SYNCHRONOUSLY, so those three failures still reject the call itself — and\n * only then is the tree built and, if it is a promise, awaited. Nothing is\n * cleared on any failure path.\n */\nexport function hydratePage(buildTree: BuildHydratedTree): void {\n const payload = readHydrationPayload(document);\n\n hydrateShared(payload.shared);\n\n const mountElement = document.getElementById(MOUNT_ELEMENT_ID);\n\n if (mountElement === null) {\n throw new Error(\n `Warlock hydration aborted: no element with id \"${MOUNT_ELEMENT_ID}\" was found. The ` +\n 'server is expected to render <div id=\"root\"> as the hydration mount point ' +\n \"(web/src/components/default-app.tsx:39).\",\n );\n }\n\n const value: DocumentContextValue = { metadata: undefined, payload };\n\n const mount = (tree: ReactNode): void => {\n hydrateRoot(\n mountElement,\n <DocumentContext.Provider value={value}>{tree}</DocumentContext.Provider>,\n );\n };\n\n const tree = buildTree(payload);\n\n if (isPromise(tree)) {\n // `void` on an ALREADY-handled chain: the rejection handler is attached\n // here, so nothing escapes as an unhandled rejection.\n void tree.then(mount, reportHydrationFailure);\n\n return;\n }\n\n mount(tree);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,MAAM,mBAAmB;AAkBzB,SAAS,UAAU,OAAoE;CACrF,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS;AAElD;;;;;;;;;AAUA,SAAS,uBAAuB,OAAsB;CACpD,QAAQ,MACN,gJAEA,KACF;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,YAAY,WAAoC;CAC9D,MAAM,UAAU,qBAAqB,QAAQ;CAE7C,cAAc,QAAQ,MAAM;CAE5B,MAAM,eAAe,SAAS,eAAe,gBAAgB;CAE7D,IAAI,iBAAiB,MACnB,MAAM,IAAI,MACR,kDAAkD,iBAAiB,oIAGrE;CAGF,MAAM,QAA8B;EAAE,UAAU;EAAW;CAAQ;CAEnE,MAAM,SAAS,SAA0B;EACvC,YACE,cACA,oBAAC,gBAAgB,UAAjB;GAAiC;aAAQ;EAA+B,EAC1E;CACF;CAEA,MAAM,OAAO,UAAU,OAAO;CAE9B,IAAI,UAAU,IAAI,GAAG;EAGnB,AAAK,KAAK,KAAK,OAAO,sBAAsB;EAE5C;CACF;CAEA,MAAM,IAAI;AACZ"}
|
|
@@ -40,7 +40,7 @@ function isPayloadResponse(response) {
|
|
|
40
40
|
* page-defined and may legitimately be anything, including `null`.
|
|
41
41
|
*/
|
|
42
42
|
function isPayloadShape(value) {
|
|
43
|
-
return typeof value === "object" && value !== null && typeof value.name === "string";
|
|
43
|
+
return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.locale === "string" && value.locale.length > 0;
|
|
44
44
|
}
|
|
45
45
|
async function fetchPageData(url) {
|
|
46
46
|
let response;
|
|
@@ -83,7 +83,7 @@ async function fetchPageData(url) {
|
|
|
83
83
|
if (!isPayloadShape(parsed)) return {
|
|
84
84
|
type: "hard-navigate",
|
|
85
85
|
url,
|
|
86
|
-
reason: "payload
|
|
86
|
+
reason: "payload is missing required navigation identity"
|
|
87
87
|
};
|
|
88
88
|
return {
|
|
89
89
|
type: "payload",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-page-data.mjs","names":[],"sources":["../../../../../../../../web/src/client/navigation/fetch-page-data.ts"],"sourcesContent":["/**\n * Ask the server for a URL's page data instead of its document.\n *\n * This is the browser half of the representation split: the same route the user\n * would have loaded, asked for as JSON via the `x-warlock-data` marker. What\n * comes back is exactly the payload a full page load embeds, so the caller can\n * rebuild the tree from it with no second code path.\n *\n * ## Every failure degrades to a REAL navigation, never to an error screen\n *\n * A client navigation is an OPTIMISATION over what the browser already does\n * perfectly well. So nothing here reports a failure to the user — it reports\n * `hard-navigate`, and the caller hands the URL back to the browser. The user\n * gets the page; they just get it the slow way.\n *\n * That is what makes the whole feature safe to add: the worst case of a bug in\n * this file is the behaviour we had before the file existed. Rendering our own\n * \"navigation failed\" state would be strictly worse than the fallback we\n * already have, and would turn every unhandled edge — an auth redirect to an\n * external IdP, a maintenance page, a proxy that strips the header, a deploy\n * that changed the payload shape mid-session — into a dead end.\n */\nimport {\n DATA_RESPONSE_CONTENT_TYPE,\n WARLOCK_DATA_REQUEST_HEADER,\n WARLOCK_DATA_REQUEST_VALUE,\n} from \"../../routing/data-request\";\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\n\nexport type PageDataResult =\n | {\n type: \"payload\";\n /**\n * The payload to rebuild the tree from.\n */\n payload: HydrationDocumentPayloadSource;\n /**\n * The URL the response actually came from — NOT the one requested. A\n * redirect is followed by `fetch` transparently, so a login-required page\n * answers from `/login`, and pushing the requested URL into history would\n * leave the address bar lying about what is on screen.\n */\n url: string;\n }\n | {\n type: \"hard-navigate\";\n url: string;\n /** Why, for a console warning — never shown to the user. */\n reason: string;\n };\n\n/**\n * Whether the body is the payload we asked for.\n *\n * Checked rather than assumed because a 200 does not mean \"this came from the\n * page pipeline\": a captive portal, an SSO interstitial or a proxy error page\n * all answer 200 with HTML. Parsing that as JSON would throw; treating a\n * successful parse of *something else* as a payload would render garbage.\n */\nfunction isPayloadResponse(response: Response): boolean {\n return (response.headers.get(\"content-type\") ?? \"\").includes(DATA_RESPONSE_CONTENT_TYPE);\n}\n\n/**\n * The shape check, kept deliberately narrow: `name` is the only field the tree\n * builder cannot proceed without — it selects the page. The data fields are\n * page-defined and may legitimately be anything, including `null`.\n */\nfunction isPayloadShape(value: unknown): value is HydrationDocumentPayloadSource {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { name?: unknown }).name === \"string\"\n );\n}\n\nexport async function fetchPageData(url: string): Promise<PageDataResult> {\n let response: Response;\n\n try {\n response = await fetch(url, {\n headers: {\n [WARLOCK_DATA_REQUEST_HEADER]: WARLOCK_DATA_REQUEST_VALUE,\n accept: DATA_RESPONSE_CONTENT_TYPE,\n },\n // Same-origin credentials so a navigation carries the session exactly as\n // a document request would. Without this a client navigation could be\n // logged out while a full load of the same URL is not.\n credentials: \"same-origin\",\n // Redirects are FOLLOWED, not intercepted: the marker header is re-sent,\n // so the destination answers with a payload too, and `response.url` tells\n // us where we ended up. Handling redirects ourselves would mean\n // re-implementing the rules the browser already has.\n redirect: \"follow\",\n });\n } catch (error) {\n // Offline, DNS, CORS, an aborted connection. The browser can render its own\n // network error far better than we can fake one.\n return { type: \"hard-navigate\", url, reason: `request failed: ${String(error)}` };\n }\n\n if (!response.ok) {\n // 404, 500, 403 — all of these have a real page the server renders. Letting\n // the browser load it gets the correct status AND the correct document,\n // rather than us inventing a client-side error state that the server's own\n // error page already covers.\n return { type: \"hard-navigate\", url, reason: `status ${response.status}` };\n }\n\n if (!isPayloadResponse(response)) {\n return {\n type: \"hard-navigate\",\n url,\n reason: `unexpected content-type \"${response.headers.get(\"content-type\") ?? \"none\"}\"`,\n };\n }\n\n let parsed: unknown;\n\n try {\n parsed = await response.json();\n } catch (error) {\n return { type: \"hard-navigate\", url, reason: `malformed JSON: ${String(error)}` };\n }\n\n if (!isPayloadShape(parsed)) {\n return {
|
|
1
|
+
{"version":3,"file":"fetch-page-data.mjs","names":[],"sources":["../../../../../../../../web/src/client/navigation/fetch-page-data.ts"],"sourcesContent":["/**\n * Ask the server for a URL's page data instead of its document.\n *\n * This is the browser half of the representation split: the same route the user\n * would have loaded, asked for as JSON via the `x-warlock-data` marker. What\n * comes back is exactly the payload a full page load embeds, so the caller can\n * rebuild the tree from it with no second code path.\n *\n * ## Every failure degrades to a REAL navigation, never to an error screen\n *\n * A client navigation is an OPTIMISATION over what the browser already does\n * perfectly well. So nothing here reports a failure to the user — it reports\n * `hard-navigate`, and the caller hands the URL back to the browser. The user\n * gets the page; they just get it the slow way.\n *\n * That is what makes the whole feature safe to add: the worst case of a bug in\n * this file is the behaviour we had before the file existed. Rendering our own\n * \"navigation failed\" state would be strictly worse than the fallback we\n * already have, and would turn every unhandled edge — an auth redirect to an\n * external IdP, a maintenance page, a proxy that strips the header, a deploy\n * that changed the payload shape mid-session — into a dead end.\n */\nimport {\n DATA_RESPONSE_CONTENT_TYPE,\n WARLOCK_DATA_REQUEST_HEADER,\n WARLOCK_DATA_REQUEST_VALUE,\n} from \"../../routing/data-request\";\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\n\nexport type PageDataResult =\n | {\n type: \"payload\";\n /**\n * The payload to rebuild the tree from.\n */\n payload: HydrationDocumentPayloadSource;\n /**\n * The URL the response actually came from — NOT the one requested. A\n * redirect is followed by `fetch` transparently, so a login-required page\n * answers from `/login`, and pushing the requested URL into history would\n * leave the address bar lying about what is on screen.\n */\n url: string;\n }\n | {\n type: \"hard-navigate\";\n url: string;\n /** Why, for a console warning — never shown to the user. */\n reason: string;\n };\n\n/**\n * Whether the body is the payload we asked for.\n *\n * Checked rather than assumed because a 200 does not mean \"this came from the\n * page pipeline\": a captive portal, an SSO interstitial or a proxy error page\n * all answer 200 with HTML. Parsing that as JSON would throw; treating a\n * successful parse of *something else* as a payload would render garbage.\n */\nfunction isPayloadResponse(response: Response): boolean {\n return (response.headers.get(\"content-type\") ?? \"\").includes(DATA_RESPONSE_CONTENT_TYPE);\n}\n\n/**\n * The shape check, kept deliberately narrow: `name` is the only field the tree\n * builder cannot proceed without — it selects the page. The data fields are\n * page-defined and may legitimately be anything, including `null`.\n */\nfunction isPayloadShape(value: unknown): value is HydrationDocumentPayloadSource {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { name?: unknown }).name === \"string\" &&\n typeof (value as { locale?: unknown }).locale === \"string\" &&\n (value as { locale: string }).locale.length > 0\n );\n}\n\nexport async function fetchPageData(url: string): Promise<PageDataResult> {\n let response: Response;\n\n try {\n response = await fetch(url, {\n headers: {\n [WARLOCK_DATA_REQUEST_HEADER]: WARLOCK_DATA_REQUEST_VALUE,\n accept: DATA_RESPONSE_CONTENT_TYPE,\n },\n // Same-origin credentials so a navigation carries the session exactly as\n // a document request would. Without this a client navigation could be\n // logged out while a full load of the same URL is not.\n credentials: \"same-origin\",\n // Redirects are FOLLOWED, not intercepted: the marker header is re-sent,\n // so the destination answers with a payload too, and `response.url` tells\n // us where we ended up. Handling redirects ourselves would mean\n // re-implementing the rules the browser already has.\n redirect: \"follow\",\n });\n } catch (error) {\n // Offline, DNS, CORS, an aborted connection. The browser can render its own\n // network error far better than we can fake one.\n return { type: \"hard-navigate\", url, reason: `request failed: ${String(error)}` };\n }\n\n if (!response.ok) {\n // 404, 500, 403 — all of these have a real page the server renders. Letting\n // the browser load it gets the correct status AND the correct document,\n // rather than us inventing a client-side error state that the server's own\n // error page already covers.\n return { type: \"hard-navigate\", url, reason: `status ${response.status}` };\n }\n\n if (!isPayloadResponse(response)) {\n return {\n type: \"hard-navigate\",\n url,\n reason: `unexpected content-type \"${response.headers.get(\"content-type\") ?? \"none\"}\"`,\n };\n }\n\n let parsed: unknown;\n\n try {\n parsed = await response.json();\n } catch (error) {\n return { type: \"hard-navigate\", url, reason: `malformed JSON: ${String(error)}` };\n }\n\n if (!isPayloadShape(parsed)) {\n // Deliberately recover through a full document load: malformed navigation\n // data must not crash the client when the server can still render the URL.\n return {\n type: \"hard-navigate\",\n url,\n reason: \"payload is missing required navigation identity\",\n };\n }\n\n // `response.url` is absolute and reflects any redirect that was followed.\n // Falling back to the requested URL keeps this working under test doubles\n // that do not set it.\n return { type: \"payload\", payload: parsed, url: response.url || url };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAS,kBAAkB,UAA6B;CACtD,QAAQ,SAAS,QAAQ,IAAI,cAAc,KAAK,GAAE,CAAE,SAAS,0BAA0B;AACzF;;;;;;AAOA,SAAS,eAAe,OAAyD;CAC/E,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS,YAC9C,OAAQ,MAA+B,WAAW,YACjD,MAA6B,OAAO,SAAS;AAElD;AAEA,eAAsB,cAAc,KAAsC;CACxE,IAAI;CAEJ,IAAI;EACF,WAAW,MAAM,MAAM,KAAK;GAC1B,SAAS;KACN;IACD,QAAQ;GACV;GAIA,aAAa;GAKb,UAAU;EACZ,CAAC;CACH,SAAS,OAAO;EAGd,OAAO;GAAE,MAAM;GAAiB;GAAK,QAAQ,mBAAmB,OAAO,KAAK;EAAI;CAClF;CAEA,IAAI,CAAC,SAAS,IAKZ,OAAO;EAAE,MAAM;EAAiB;EAAK,QAAQ,UAAU,SAAS;CAAS;CAG3E,IAAI,CAAC,kBAAkB,QAAQ,GAC7B,OAAO;EACL,MAAM;EACN;EACA,QAAQ,4BAA4B,SAAS,QAAQ,IAAI,cAAc,KAAK,OAAO;CACrF;CAGF,IAAI;CAEJ,IAAI;EACF,SAAS,MAAM,SAAS,KAAK;CAC/B,SAAS,OAAO;EACd,OAAO;GAAE,MAAM;GAAiB;GAAK,QAAQ,mBAAmB,OAAO,KAAK;EAAI;CAClF;CAEA,IAAI,CAAC,eAAe,MAAM,GAGxB,OAAO;EACL,MAAM;EACN;EACA,QAAQ;CACV;CAMF,OAAO;EAAE,MAAM;EAAW,SAAS;EAAQ,KAAK,SAAS,OAAO;CAAI;AACtE"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { hydrateShared } from "../../shared.mjs";
|
|
2
|
+
import { LocaleProvider } from "../../localization.mjs";
|
|
2
3
|
import { fetchPageData } from "./fetch-page-data.mjs";
|
|
3
4
|
import { takePrefetchedPageData } from "./prefetch.mjs";
|
|
4
5
|
import { connectNavigator } from "../../routing/navigator.mjs";
|
|
@@ -224,7 +225,10 @@ function NavigationRoot({ pages, initialPayload, initialTree, buildTree }) {
|
|
|
224
225
|
metadata: current.payload.metadata,
|
|
225
226
|
payload: current.payload
|
|
226
227
|
},
|
|
227
|
-
children:
|
|
228
|
+
children: /* @__PURE__ */ jsx(LocaleProvider, {
|
|
229
|
+
locale: current.payload.locale,
|
|
230
|
+
children: current.tree
|
|
231
|
+
})
|
|
228
232
|
});
|
|
229
233
|
}
|
|
230
234
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"navigation-root.mjs","names":[],"sources":["../../../../../../../../web/src/client/navigation/navigation-root.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from \"react\";\r\nimport { DocumentContext } from \"../../components/document-context\";\r\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\r\nimport type { MetadataOutput } from \"../../metadata\";\r\nimport { connectNavigator } from \"../../routing/navigator\";\r\nimport {\r\n fragmentOf,\r\n samePageFragment,\r\n withFragmentFrom,\r\n withoutFragment,\r\n} from \"../../routing/url-fragment\";\r\nimport { hydrateShared } from \"../../shared\";\r\nimport type { ClientPageEntry } from \"../runtime\";\r\nimport { recordCurrentRoute } from \"./current-route\";\r\nimport { fetchPageData } from \"./fetch-page-data\";\r\nimport { takePrefetchedPageData } from \"./prefetch\";\r\nimport { connectRefresher, createRefresher, type RefreshablePage } from \"./refresh\";\r\nimport { scrollToFragment } from \"./scroll-to-fragment\";\r\n\r\n/**\r\n * The component that makes a page REPLACEABLE.\r\n *\r\n * Hydration mounts a fixed tree — correct, because the first render must match\r\n * the server's markup byte for byte. Client navigation needs that same position\r\n * in the tree to be able to hold a *different* page later, which means state,\r\n * which means a component. This is that component and nothing more.\r\n *\r\n * ## Why the layout stays mounted\r\n *\r\n * The new tree is built by the same `buildHydratedTree` the server's payload\r\n * went through, so a navigation within one layout produces an element whose\r\n * layout components are the same types in the same positions. React reconciles\r\n * them rather than remounting, so layout state — an open menu, a scroll\r\n * container, a video — survives. That is the entire user-visible benefit of\r\n * client navigation, and it is a consequence of reusing the builder rather than\r\n * anything this file does.\r\n */\r\n\r\n/**\r\n * ONE tag `<head>` may hold at most one of, addressed the way the browser\r\n * already addresses it. No marker attribute: the tags this replaces were\r\n * rendered by `<Head/>` on the server and carry none, and a marker would make\r\n * the applier ignore exactly the tags it exists to correct — the first\r\n * navigation's.\r\n */\r\ntype ManagedTag = {\r\n /** Finds the existing tag, server-rendered or applied by a previous swap. */\r\n selector: string;\r\n create: (documentNode: Document) => Element;\r\n write: (element: Element, value: string) => void;\r\n};\r\n\r\nfunction metaTag(attribute: \"name\" | \"property\", key: string): ManagedTag {\r\n return {\r\n selector: `meta[${attribute}=\"${key}\"]`,\r\n create: documentNode => {\r\n const element = documentNode.createElement(\"meta\");\r\n\r\n element.setAttribute(attribute, key);\r\n\r\n return element;\r\n },\r\n write: (element, value) => element.setAttribute(\"content\", value),\r\n };\r\n}\r\n\r\nconst TITLE_TAG: ManagedTag = {\r\n selector: \"title\",\r\n create: documentNode => documentNode.createElement(\"title\"),\r\n write: (element, value) => {\r\n element.textContent = value;\r\n },\r\n};\r\n\r\nconst CANONICAL_TAG: ManagedTag = {\r\n selector: 'link[rel=\"canonical\"]',\r\n create: documentNode => {\r\n const element = documentNode.createElement(\"link\");\r\n\r\n element.setAttribute(\"rel\", \"canonical\");\r\n\r\n return element;\r\n },\r\n write: (element, value) => element.setAttribute(\"href\", value),\r\n};\r\n\r\n/**\r\n * The metadata, resolved into (tag, value) pairs in `<Head/>`'s ORDER and by\r\n * `<Head/>`'s RULES — including the og fallbacks and the fact that they apply\r\n * only when `openGraph` is present (`components/head.ts:21-24,43-48`).\r\n *\r\n * The duplication is deliberate and it is the known cost here. `<Head/>` is a\r\n * React component that renders elements into a tree; this writes elements into\r\n * a live `<head>` that no client tree owns. They cannot be one function today,\r\n * but they MUST agree: the head after navigating to a URL has to equal the head\r\n * after landing on it, or a share preview depends on how the visitor arrived.\r\n * The fix is a shared descriptor list both consume — see the report's followup.\r\n */\r\nfunction resolveManagedTags(\r\n metadata: MetadataOutput | undefined,\r\n): readonly (readonly [ManagedTag, string | undefined])[] {\r\n const keywords =\r\n metadata?.keywords === undefined\r\n ? undefined\r\n : Array.isArray(metadata.keywords)\r\n ? metadata.keywords.join(\", \")\r\n : (metadata.keywords as string);\r\n\r\n const openGraph = metadata?.openGraph;\r\n const twitter = metadata?.twitter;\r\n\r\n return [\r\n [TITLE_TAG, metadata?.title],\r\n [metaTag(\"name\", \"description\"), metadata?.description],\r\n [metaTag(\"name\", \"keywords\"), keywords],\r\n [CANONICAL_TAG, metadata?.canonical],\r\n [metaTag(\"name\", \"robots\"), metadata?.robots],\r\n [metaTag(\"property\", \"og:title\"), openGraph && (openGraph.title ?? metadata?.title)],\r\n [\r\n metaTag(\"property\", \"og:description\"),\r\n openGraph && (openGraph.description ?? metadata?.description),\r\n ],\r\n [metaTag(\"property\", \"og:image\"), openGraph?.image],\r\n [metaTag(\"property\", \"og:url\"), openGraph?.url],\r\n [metaTag(\"property\", \"og:type\"), openGraph?.type],\r\n [metaTag(\"name\", \"twitter:card\"), twitter?.card],\r\n [metaTag(\"name\", \"twitter:title\"), twitter?.title],\r\n [metaTag(\"name\", \"twitter:description\"), twitter?.description],\r\n [metaTag(\"name\", \"twitter:image\"), twitter?.image],\r\n ];\r\n}\r\n\r\n/**\r\n * Make `<head>` describe the page now on screen.\r\n *\r\n * ## Why this is imperative, and why that is not a shortcut\r\n *\r\n * `<Head/>` renders inside the App level, and the App level is deliberately NOT\r\n * in the hydrated tree — the client mounts at `#root`, which App contains\r\n * (`client/build-hydrated-tree.ts`'s header). So no client render can reach\r\n * `<head>`, and a swap either writes it directly or leaves the previous page's\r\n * title in the tab. It leaves it today; that is the bug.\r\n *\r\n * ## ABSENT MEANS REMOVED\r\n *\r\n * Every managed tag the new metadata does not set is REMOVED, not left alone.\r\n * `/` sets a description and `/contact-us` does not: keeping it would describe\r\n * the contact page with the home page's words to every crawler, share preview\r\n * and assistive reader that looks — a wrong answer, where an absent one is\r\n * merely absent. A title the new page does not set goes too, and the tab falls\r\n * back to the URL, which is the honest rendering of \"this page did not name\r\n * itself\".\r\n *\r\n * Only the tags `<Head/>` renders FROM METADATA are touched. The charset meta\r\n * is rendered unconditionally and belongs to the document, so it is left alone.\r\n *\r\n * Takes the document as an argument rather than reaching for the global, which\r\n * is what makes it provable in a suite with no DOM.\r\n */\r\nexport function applyDocumentMetadata(\r\n documentNode: Document,\r\n metadata: MetadataOutput | undefined,\r\n): void {\r\n for (const [tag, value] of resolveManagedTags(metadata)) {\r\n const existing = documentNode.querySelector(tag.selector);\r\n\r\n if (value === undefined) {\r\n existing?.remove();\r\n continue;\r\n }\r\n\r\n if (existing !== null) {\r\n tag.write(existing, value);\r\n continue;\r\n }\r\n\r\n const created = tag.create(documentNode);\r\n\r\n tag.write(created, value);\r\n documentNode.head.appendChild(created);\r\n }\r\n}\r\n\r\nexport type NavigationRootProps = {\r\n pages: readonly ClientPageEntry[];\r\n /** The payload the document was rendered from — the hydration one. */\r\n initialPayload: HydrationDocumentPayloadSource;\r\n /** The tree already built from {@link initialPayload}, rendered as-is first. */\r\n initialTree: ReactNode;\r\n /**\r\n * How a payload becomes a tree. Injected rather than imported so this\r\n * component is testable without the page registry or a bundler — the same\r\n * reason `hydratePage` takes its builder as an argument.\r\n */\r\n buildTree: (\r\n pages: readonly ClientPageEntry[],\r\n payload: HydrationDocumentPayloadSource,\r\n ) => Promise<ReactNode>;\r\n};\r\n\r\n/**\r\n * The page on screen. Defined in `refresh.ts` because the third field is that\r\n * file's decision: `routeSource` is the payload object `current-route.ts`\r\n * identifies the route by, which is `payload` after a navigation but the\r\n * PREVIOUS page's object after a refresh — a refresh must not shift\r\n * `previousRoute()` onto the page the user is already looking at.\r\n */\r\ntype Current = RefreshablePage;\r\n\r\nexport function NavigationRoot({\r\n pages,\r\n initialPayload,\r\n initialTree,\r\n buildTree,\r\n}: NavigationRootProps) {\r\n const [current, setCurrent] = useState<Current>({\r\n payload: initialPayload,\r\n tree: initialTree,\r\n routeSource: initialPayload,\r\n });\r\n\r\n /*\r\n The latest state, readable from the effect below — which closes over the\r\n render that created it and would otherwise see the page the user was on\r\n when the runtime connected. A ref rather than an effect dependency because\r\n re-running the effect on every swap would disconnect and reconnect the\r\n navigator mid-navigation.\r\n */\r\n const currentRef = useRef(current);\r\n\r\n currentRef.current = current;\r\n\r\n /*\r\n THE ORDERING PROBLEM, and this ref is half of the answer to it.\r\n\r\n The element a fragment names lives in the tree that has not been built yet:\r\n at the moment `apply` finishes fetching, the DOM still holds the page the\r\n user is LEAVING. Scrolling there finds nothing, and finding nothing is\r\n silent — indistinguishable from the fragment bug itself.\r\n\r\n So the fragment is not scrolled to; it is HANDED OVER. `apply` parks it here\r\n immediately before the `setCurrent` that swaps the tree, and the layout\r\n effect below — which React runs after it has committed that tree to the DOM\r\n and before the browser paints — spends it. Read the two together; neither\r\n half means anything alone.\r\n */\r\n const pendingFragment = useRef<string | undefined>(undefined);\r\n\r\n useEffect(() => {\r\n /*\r\n THE RACE THIS COUNTER EXISTS FOR. Two clicks in quick succession start two\r\n fetches; the second can easily answer first (a cached page beating an\r\n uncached one is the common case, not the exotic one). Without a token the\r\n slower FIRST response lands last and the user ends up on the page they\r\n navigated away from, with the address bar showing the other one.\r\n\r\n Every navigation takes a token; a result is applied only if its token is\r\n still the newest. Superseded responses are dropped silently — they are not\r\n errors, they are answers to a question the user stopped asking.\r\n */\r\n let token = 0;\r\n let disposed = false;\r\n /*\r\n The URL this runtime last put in the address bar, so `popstate` can tell a\r\n move BETWEEN pages from a move between two fragments of one page. Seeded\r\n with the URL the document was loaded at, which is the entry the first Back\r\n would come from.\r\n */\r\n let committedUrl = window.location.href;\r\n\r\n /**\r\n * @param honourFragment whether the URL's fragment should be SCROLLED to\r\n * once the new page is on screen. True for a navigation the app asked for\r\n * — a `<Link>` click, `navigateTo` — and false for Back/Forward, where the\r\n * browser has already restored the scroll position of the entry being\r\n * returned to and moving the page again would overwrite the user's own\r\n * position with the anchor they had scrolled away from. (Restoration is\r\n * the browser's, deliberately: canon `0342c0d4`.)\r\n *\r\n * The fragment is still PRESERVED in the URL in both cases — see below.\r\n */\r\n const apply = async (\r\n url: string,\r\n replace: boolean,\r\n honourFragment: boolean,\r\n ): Promise<void> => {\r\n const ticket = ++token;\r\n /*\r\n A prefetched response is CONSUMED, never merely read — `take` removes it,\r\n so the same speculative fetch can satisfy exactly one navigation and a\r\n second click on the same link goes to the network. That matters because\r\n the HTTP cache cannot stand in for this: dev responses are `no-store`\r\n (`server/dev-server.ts:254`) and production is `private` with no\r\n `max-age` (`server/render-page.ts:432`), so the browser will not reliably\r\n replay the speculative response on the real click.\r\n\r\n The race guard below still holds on a cache hit: `??` short-circuits the\r\n await, and the synchronous path reaches the same `ticket !== token` check.\r\n */\r\n const result = takePrefetchedPageData(url) ?? (await fetchPageData(url));\r\n\r\n if (disposed || ticket !== token) return;\r\n\r\n if (result.type === \"hard-navigate\") {\r\n // The documented degradation: hand the URL back to the browser. The\r\n // user still gets the page — see `fetch-page-data.ts`.\r\n console.warn(`Warlock navigation fell back to a full load (${result.reason}):`, url);\r\n window.location.assign(url);\r\n\r\n return;\r\n }\r\n\r\n let tree: ReactNode;\r\n\r\n try {\r\n tree = await buildTree(pages, result.payload);\r\n } catch (error) {\r\n // The payload was fine but its page chunk would not load or compose —\r\n // a stale bundle after a deploy is the realistic cause. A full load\r\n // fetches the current bundle, which is also the fix.\r\n console.warn(\"Warlock navigation could not build the page tree:\", error);\r\n window.location.assign(url);\r\n\r\n return;\r\n }\r\n\r\n if (disposed || ticket !== token) return;\r\n\r\n /*\r\n Shared state BEFORE the render that consumes it. `hydrateShared`\r\n installs the snapshot `useShared()` reads; swapping the tree first would\r\n render one frame of the new page against the previous page's shared\r\n state — locale, permissions, the current user.\r\n */\r\n hydrateShared(result.payload.shared);\r\n\r\n /*\r\n The fragment PUT BACK. `result.url` comes from `response.url`, and a\r\n fragment is never sent to a server, so the URL a navigation would\r\n otherwise be written to history from has had it stripped — which is how\r\n `<Link href=\"/docs#install\">` used to land on `/docs` with the author's\r\n fragment gone from the address bar for good.\r\n\r\n Applied on EVERY path, Back included: a popstate re-fetch that wrote\r\n `result.url` back would delete the fragment from an entry the user is\r\n merely returning to.\r\n */\r\n const finalUrl = withFragmentFrom(result.url, url);\r\n\r\n // History AFTER the fetch succeeded, never before. Pushing optimistically\r\n // would leave the address bar pointing at a page that then failed to\r\n // load, and a Back press would return to a URL the user never saw.\r\n if (replace) {\r\n window.history.replaceState(null, \"\", finalUrl);\r\n } else {\r\n window.history.pushState(null, \"\", finalUrl);\r\n }\r\n\r\n committedUrl = finalUrl;\r\n\r\n // Handed to the layout effect, which runs once React has committed the\r\n // tree below to the DOM — the first moment the target can exist. Set\r\n // unconditionally so a navigation with no fragment CLEARS a fragment left\r\n // pending by one that was superseded.\r\n pendingFragment.current = honourFragment ? fragmentOf(finalUrl) : undefined;\r\n\r\n // A navigation IS the route moving, so the fetched payload is both the\r\n // page and the route's identity.\r\n setCurrent({ payload: result.payload, tree, routeSource: result.payload });\r\n };\r\n\r\n /*\r\n The same counter `apply` above takes its tickets from, handed to\r\n `refresh()` as a predicate. ONE mechanism, not two: a refresh and a\r\n navigation can overtake each other in either direction, and separate\r\n counters would leave each blind to the other.\r\n */\r\n const claimTicket = (): (() => boolean) => {\r\n const ticket = ++token;\r\n\r\n return () => !disposed && ticket === token;\r\n };\r\n\r\n const previousRefresher = connectRefresher(\r\n createRefresher({\r\n readCurrent: () => currentRef.current,\r\n writeCurrent: setCurrent,\r\n buildTree: payload => buildTree(pages, payload),\r\n claimTicket,\r\n }),\r\n );\r\n\r\n const previousNavigator = connectNavigator((url, options) => {\r\n const replace = options?.replace === true;\r\n\r\n /*\r\n THIS page with a fragment on it — `#reviews`, or the current path spelled\r\n out with one appended. No fetch, no tree swap: the page is already here,\r\n and re-fetching it would discard its DOM and everything live in it to\r\n arrive back where we started, one round trip later. Address bar first,\r\n then the jump, which is the order the browser uses for a plain anchor.\r\n */\r\n const fragment = samePageFragment(url, window.location.href);\r\n\r\n if (fragment !== undefined) {\r\n if (replace) {\r\n window.history.replaceState(null, \"\", url);\r\n } else {\r\n window.history.pushState(null, \"\", url);\r\n }\r\n\r\n committedUrl = window.location.href;\r\n\r\n // The target is in the DOM already, so there is nothing to wait for —\r\n // and nothing to hand to the layout effect, which no swap would fire.\r\n scrollToFragment(document, fragment);\r\n\r\n return true;\r\n }\r\n\r\n void apply(url, replace, true);\r\n\r\n // Accepted: the caller suppresses the browser's default. Returning `true`\r\n // before the fetch resolves is deliberate — the decision to handle a link\r\n // cannot wait on the network without the browser having already followed\r\n // it.\r\n return true;\r\n });\r\n\r\n /*\r\n Back/Forward. The entry is already in history and the URL has already\r\n changed by the time this fires, so the page is fetched and swapped with\r\n `replace` — pushing here would append a duplicate entry and make Back\r\n require two presses.\r\n */\r\n const onPopState = (): void => {\r\n const target = window.location.href;\r\n /*\r\n A hash-only move within one page — Back off a `#section` click, or\r\n Forward onto one. The document is the same document and the tree on\r\n screen is already the right tree, so there is nothing to fetch: the\r\n browser has changed the URL and restored the position for that entry\r\n itself, and re-fetching would throw away a live page to rebuild the one\r\n already showing. Scroll restoration stays the browser's (canon\r\n `0342c0d4`), which is exactly what leaving this alone means.\r\n */\r\n const hashOnlyMove = withoutFragment(target) === withoutFragment(committedUrl);\r\n\r\n committedUrl = target;\r\n\r\n if (hashOnlyMove) return;\r\n\r\n void apply(target, true, false);\r\n };\r\n\r\n window.addEventListener(\"popstate\", onPopState);\r\n\r\n return () => {\r\n disposed = true;\r\n window.removeEventListener(\"popstate\", onPopState);\r\n connectNavigator(previousNavigator);\r\n connectRefresher(previousRefresher);\r\n };\r\n }, [pages, buildTree]);\r\n\r\n /*\r\n THE OTHER HALF OF THE ORDERING PROBLEM (see `pendingFragment` above).\r\n\r\n `useLayoutEffect`, not `useEffect`, and the difference is the whole point:\r\n React runs a layout effect after it has COMMITTED this render to the DOM and\r\n BEFORE the browser paints. That is the earliest instant the new page's\r\n elements exist — a scroll any sooner finds nothing — and the last instant\r\n before the user sees anything, so the page is never painted at the top and\r\n then jumped. `useEffect` would satisfy the first requirement and not the\r\n second: it runs after paint, which is a visible flash of the wrong position.\r\n\r\n Keyed on `current` rather than reaching for a fresh render: the effect fires\r\n on the swap that put the target in the DOM, so no polling, no rAF, no\r\n timeout. What it CANNOT wait for is content that arrives later still — an\r\n image without dimensions above the target, a component that suspends — which\r\n moves the target after we have scrolled to where it was. That is the known\r\n limit of this mechanism and it is the same one a browser has.\r\n\r\n Consumed once: the fragment is cleared as it is read, so a later re-render\r\n (a refresh, a parent's state change) does not yank the page back to an\r\n anchor the user has since scrolled away from.\r\n */\r\n useLayoutEffect(() => {\r\n const fragment = pendingFragment.current;\r\n\r\n if (fragment === undefined) return;\r\n\r\n pendingFragment.current = undefined;\r\n\r\n scrollToFragment(document, fragment);\r\n }, [current]);\r\n\r\n /*\r\n The payload whose metadata `<head>` currently reflects. Seeded with the\r\n HYDRATION payload, which is the point: on the initial mount the head is the\r\n server's own render of this very metadata, so there is nothing to correct —\r\n and re-applying would be a chance to get it wrong, since a payload from a\r\n build with no `metadata` key would wipe a head the server filled in\r\n correctly. The head is applied on SWAPS only.\r\n */\r\n const appliedMetadataSource = useRef(current.payload);\r\n\r\n useEffect(() => {\r\n if (appliedMetadataSource.current === current.payload) return;\r\n\r\n appliedMetadataSource.current = current.payload;\r\n\r\n /*\r\n Keyed on the payload's identity, so this covers a refresh as well as a\r\n navigation: `refresh()` produces a NEW payload for the page already on\r\n screen, and a page whose metadata is a function of its loader data can\r\n legitimately re-title itself when that data changes. One applier at the\r\n one place the page changes, rather than a call in each pathway that could\r\n be forgotten in the next one.\r\n */\r\n applyDocumentMetadata(document, current.payload.metadata);\r\n }, [current.payload]);\r\n\r\n /*\r\n DURING RENDER, not in an effect, and that placement is the requirement\r\n rather than a shortcut. A page component calling `currentRoute()` does it\r\n while IT is rendering, and child effects run before a parent's, so anything\r\n recorded from an effect here would be recorded too late to answer the first\r\n render of the page it describes — which on the initial mount is the only\r\n render there has been, and the server's match is all there is.\r\n\r\n Recording is keyed on the payload's identity (`current-route.ts`), so the\r\n extra passes render gives us for free — StrictMode's double invoke, a parent\r\n re-render — are recognised as the same page rather than counted as\r\n navigations.\r\n\r\n `routeSource`, NOT `payload`: they are the same object for every navigation,\r\n and differ only after a refresh, which produces a new payload for the page\r\n already on screen and must not be counted as a move (see `refresh.ts`).\r\n */\r\n recordCurrentRoute(current.routeSource);\r\n\r\n /*\r\n An INNER DocumentContext provider, nested inside the one `hydratePage`\r\n mounted. That outer provider is created once with the hydration payload and\r\n never changes, so anything reading the document context after a navigation\r\n would see the payload of the page the user has left. The nearest provider\r\n wins, so this one keeps it current.\r\n */\r\n /*\r\n `metadata` from the PAYLOAD, not `undefined`. The document context is the\r\n universal shape — the server provides the resolved metadata around the same\r\n tree — so handing the client's readers `undefined` was a lie the payload can\r\n now correct. It also removes a latent mismatch: a `<Head/>` rendered inside\r\n a Layout (not the App level) renders its tags into `#root` server-side, and\r\n hydrating that markup against `metadata: undefined` produced a tree the\r\n server never rendered.\r\n */\r\n return (\r\n <DocumentContext.Provider\r\n value={{ metadata: current.payload.metadata, payload: current.payload }}\r\n >\r\n {current.tree}\r\n </DocumentContext.Provider>\r\n );\r\n}\r\n"],"mappings":";;;;;;;;;;;;;AAoDA,SAAS,QAAQ,WAAgC,KAAyB;CACxE,OAAO;EACL,UAAU,QAAQ,UAAU,IAAI,IAAI;EACpC,SAAQ,iBAAgB;GACtB,MAAM,UAAU,aAAa,cAAc,MAAM;GAEjD,QAAQ,aAAa,WAAW,GAAG;GAEnC,OAAO;EACT;EACA,QAAQ,SAAS,UAAU,QAAQ,aAAa,WAAW,KAAK;CAClE;AACF;AAEA,MAAM,YAAwB;CAC5B,UAAU;CACV,SAAQ,iBAAgB,aAAa,cAAc,OAAO;CAC1D,QAAQ,SAAS,UAAU;EACzB,QAAQ,cAAc;CACxB;AACF;AAEA,MAAM,gBAA4B;CAChC,UAAU;CACV,SAAQ,iBAAgB;EACtB,MAAM,UAAU,aAAa,cAAc,MAAM;EAEjD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,SAAS;EAEvD,sBAAsB,UAAU,QAAQ;EAUxC,sBAAsB,UAAU,QAAQ,QAAQ,QAAQ;CAC1D,GAAG,CAAC,QAAQ,OAAO,CAAC;CAmBpB,mBAAmB,QAAQ,WAAW;CAkBtC,OACE,oBAAC,gBAAgB,UAAjB;EACE,OAAO;GAAE,UAAU,QAAQ,QAAQ;GAAU,SAAS,QAAQ;EAAQ;YAErE,QAAQ;CACe;AAE9B"}
|
|
1
|
+
{"version":3,"file":"navigation-root.mjs","names":[],"sources":["../../../../../../../../web/src/client/navigation/navigation-root.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from \"react\";\r\nimport { DocumentContext } from \"../../components/document-context\";\nimport { LocaleProvider } from \"../../localization\";\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\r\nimport type { MetadataOutput } from \"../../metadata\";\r\nimport { connectNavigator } from \"../../routing/navigator\";\r\nimport {\r\n fragmentOf,\r\n samePageFragment,\r\n withFragmentFrom,\r\n withoutFragment,\r\n} from \"../../routing/url-fragment\";\r\nimport { hydrateShared } from \"../../shared\";\r\nimport type { ClientPageEntry } from \"../runtime\";\r\nimport { recordCurrentRoute } from \"./current-route\";\r\nimport { fetchPageData } from \"./fetch-page-data\";\r\nimport { takePrefetchedPageData } from \"./prefetch\";\r\nimport { connectRefresher, createRefresher, type RefreshablePage } from \"./refresh\";\r\nimport { scrollToFragment } from \"./scroll-to-fragment\";\r\n\r\n/**\r\n * The component that makes a page REPLACEABLE.\r\n *\r\n * Hydration mounts a fixed tree — correct, because the first render must match\r\n * the server's markup byte for byte. Client navigation needs that same position\r\n * in the tree to be able to hold a *different* page later, which means state,\r\n * which means a component. This is that component and nothing more.\r\n *\r\n * ## Why the layout stays mounted\r\n *\r\n * The new tree is built by the same `buildHydratedTree` the server's payload\r\n * went through, so a navigation within one layout produces an element whose\r\n * layout components are the same types in the same positions. React reconciles\r\n * them rather than remounting, so layout state — an open menu, a scroll\r\n * container, a video — survives. That is the entire user-visible benefit of\r\n * client navigation, and it is a consequence of reusing the builder rather than\r\n * anything this file does.\r\n */\r\n\r\n/**\r\n * ONE tag `<head>` may hold at most one of, addressed the way the browser\r\n * already addresses it. No marker attribute: the tags this replaces were\r\n * rendered by `<Head/>` on the server and carry none, and a marker would make\r\n * the applier ignore exactly the tags it exists to correct — the first\r\n * navigation's.\r\n */\r\ntype ManagedTag = {\r\n /** Finds the existing tag, server-rendered or applied by a previous swap. */\r\n selector: string;\r\n create: (documentNode: Document) => Element;\r\n write: (element: Element, value: string) => void;\r\n};\r\n\r\nfunction metaTag(attribute: \"name\" | \"property\", key: string): ManagedTag {\r\n return {\r\n selector: `meta[${attribute}=\"${key}\"]`,\r\n create: documentNode => {\r\n const element = documentNode.createElement(\"meta\");\r\n\r\n element.setAttribute(attribute, key);\r\n\r\n return element;\r\n },\r\n write: (element, value) => element.setAttribute(\"content\", value),\r\n };\r\n}\r\n\r\nconst TITLE_TAG: ManagedTag = {\r\n selector: \"title\",\r\n create: documentNode => documentNode.createElement(\"title\"),\r\n write: (element, value) => {\r\n element.textContent = value;\r\n },\r\n};\r\n\r\nconst CANONICAL_TAG: ManagedTag = {\r\n selector: 'link[rel=\"canonical\"]',\r\n create: documentNode => {\r\n const element = documentNode.createElement(\"link\");\r\n\r\n element.setAttribute(\"rel\", \"canonical\");\r\n\r\n return element;\r\n },\r\n write: (element, value) => element.setAttribute(\"href\", value),\r\n};\r\n\r\n/**\r\n * The metadata, resolved into (tag, value) pairs in `<Head/>`'s ORDER and by\r\n * `<Head/>`'s RULES — including the og fallbacks and the fact that they apply\r\n * only when `openGraph` is present (`components/head.ts:21-24,43-48`).\r\n *\r\n * The duplication is deliberate and it is the known cost here. `<Head/>` is a\r\n * React component that renders elements into a tree; this writes elements into\r\n * a live `<head>` that no client tree owns. They cannot be one function today,\r\n * but they MUST agree: the head after navigating to a URL has to equal the head\r\n * after landing on it, or a share preview depends on how the visitor arrived.\r\n * The fix is a shared descriptor list both consume — see the report's followup.\r\n */\r\nfunction resolveManagedTags(\r\n metadata: MetadataOutput | undefined,\r\n): readonly (readonly [ManagedTag, string | undefined])[] {\r\n const keywords =\r\n metadata?.keywords === undefined\r\n ? undefined\r\n : Array.isArray(metadata.keywords)\r\n ? metadata.keywords.join(\", \")\r\n : (metadata.keywords as string);\r\n\r\n const openGraph = metadata?.openGraph;\r\n const twitter = metadata?.twitter;\r\n\r\n return [\r\n [TITLE_TAG, metadata?.title],\r\n [metaTag(\"name\", \"description\"), metadata?.description],\r\n [metaTag(\"name\", \"keywords\"), keywords],\r\n [CANONICAL_TAG, metadata?.canonical],\r\n [metaTag(\"name\", \"robots\"), metadata?.robots],\r\n [metaTag(\"property\", \"og:title\"), openGraph && (openGraph.title ?? metadata?.title)],\r\n [\r\n metaTag(\"property\", \"og:description\"),\r\n openGraph && (openGraph.description ?? metadata?.description),\r\n ],\r\n [metaTag(\"property\", \"og:image\"), openGraph?.image],\r\n [metaTag(\"property\", \"og:url\"), openGraph?.url],\r\n [metaTag(\"property\", \"og:type\"), openGraph?.type],\r\n [metaTag(\"name\", \"twitter:card\"), twitter?.card],\r\n [metaTag(\"name\", \"twitter:title\"), twitter?.title],\r\n [metaTag(\"name\", \"twitter:description\"), twitter?.description],\r\n [metaTag(\"name\", \"twitter:image\"), twitter?.image],\r\n ];\r\n}\r\n\r\n/**\r\n * Make `<head>` describe the page now on screen.\r\n *\r\n * ## Why this is imperative, and why that is not a shortcut\r\n *\r\n * `<Head/>` renders inside the App level, and the App level is deliberately NOT\r\n * in the hydrated tree — the client mounts at `#root`, which App contains\r\n * (`client/build-hydrated-tree.ts`'s header). So no client render can reach\r\n * `<head>`, and a swap either writes it directly or leaves the previous page's\r\n * title in the tab. It leaves it today; that is the bug.\r\n *\r\n * ## ABSENT MEANS REMOVED\r\n *\r\n * Every managed tag the new metadata does not set is REMOVED, not left alone.\r\n * `/` sets a description and `/contact-us` does not: keeping it would describe\r\n * the contact page with the home page's words to every crawler, share preview\r\n * and assistive reader that looks — a wrong answer, where an absent one is\r\n * merely absent. A title the new page does not set goes too, and the tab falls\r\n * back to the URL, which is the honest rendering of \"this page did not name\r\n * itself\".\r\n *\r\n * Only the tags `<Head/>` renders FROM METADATA are touched. The charset meta\r\n * is rendered unconditionally and belongs to the document, so it is left alone.\r\n *\r\n * Takes the document as an argument rather than reaching for the global, which\r\n * is what makes it provable in a suite with no DOM.\r\n */\r\nexport function applyDocumentMetadata(\r\n documentNode: Document,\r\n metadata: MetadataOutput | undefined,\r\n): void {\r\n for (const [tag, value] of resolveManagedTags(metadata)) {\r\n const existing = documentNode.querySelector(tag.selector);\r\n\r\n if (value === undefined) {\r\n existing?.remove();\r\n continue;\r\n }\r\n\r\n if (existing !== null) {\r\n tag.write(existing, value);\r\n continue;\r\n }\r\n\r\n const created = tag.create(documentNode);\r\n\r\n tag.write(created, value);\r\n documentNode.head.appendChild(created);\r\n }\r\n}\r\n\r\nexport type NavigationRootProps = {\r\n pages: readonly ClientPageEntry[];\r\n /** The payload the document was rendered from — the hydration one. */\r\n initialPayload: HydrationDocumentPayloadSource;\r\n /** The tree already built from {@link initialPayload}, rendered as-is first. */\r\n initialTree: ReactNode;\r\n /**\r\n * How a payload becomes a tree. Injected rather than imported so this\r\n * component is testable without the page registry or a bundler — the same\r\n * reason `hydratePage` takes its builder as an argument.\r\n */\r\n buildTree: (\r\n pages: readonly ClientPageEntry[],\r\n payload: HydrationDocumentPayloadSource,\r\n ) => Promise<ReactNode>;\r\n};\r\n\r\n/**\r\n * The page on screen. Defined in `refresh.ts` because the third field is that\r\n * file's decision: `routeSource` is the payload object `current-route.ts`\r\n * identifies the route by, which is `payload` after a navigation but the\r\n * PREVIOUS page's object after a refresh — a refresh must not shift\r\n * `previousRoute()` onto the page the user is already looking at.\r\n */\r\ntype Current = RefreshablePage;\r\n\r\nexport function NavigationRoot({\r\n pages,\r\n initialPayload,\r\n initialTree,\r\n buildTree,\r\n}: NavigationRootProps) {\r\n const [current, setCurrent] = useState<Current>({\r\n payload: initialPayload,\r\n tree: initialTree,\r\n routeSource: initialPayload,\r\n });\r\n\r\n /*\r\n The latest state, readable from the effect below — which closes over the\r\n render that created it and would otherwise see the page the user was on\r\n when the runtime connected. A ref rather than an effect dependency because\r\n re-running the effect on every swap would disconnect and reconnect the\r\n navigator mid-navigation.\r\n */\r\n const currentRef = useRef(current);\r\n\r\n currentRef.current = current;\r\n\r\n /*\r\n THE ORDERING PROBLEM, and this ref is half of the answer to it.\r\n\r\n The element a fragment names lives in the tree that has not been built yet:\r\n at the moment `apply` finishes fetching, the DOM still holds the page the\r\n user is LEAVING. Scrolling there finds nothing, and finding nothing is\r\n silent — indistinguishable from the fragment bug itself.\r\n\r\n So the fragment is not scrolled to; it is HANDED OVER. `apply` parks it here\r\n immediately before the `setCurrent` that swaps the tree, and the layout\r\n effect below — which React runs after it has committed that tree to the DOM\r\n and before the browser paints — spends it. Read the two together; neither\r\n half means anything alone.\r\n */\r\n const pendingFragment = useRef<string | undefined>(undefined);\r\n\r\n useEffect(() => {\r\n /*\r\n THE RACE THIS COUNTER EXISTS FOR. Two clicks in quick succession start two\r\n fetches; the second can easily answer first (a cached page beating an\r\n uncached one is the common case, not the exotic one). Without a token the\r\n slower FIRST response lands last and the user ends up on the page they\r\n navigated away from, with the address bar showing the other one.\r\n\r\n Every navigation takes a token; a result is applied only if its token is\r\n still the newest. Superseded responses are dropped silently — they are not\r\n errors, they are answers to a question the user stopped asking.\r\n */\r\n let token = 0;\r\n let disposed = false;\r\n /*\r\n The URL this runtime last put in the address bar, so `popstate` can tell a\r\n move BETWEEN pages from a move between two fragments of one page. Seeded\r\n with the URL the document was loaded at, which is the entry the first Back\r\n would come from.\r\n */\r\n let committedUrl = window.location.href;\r\n\r\n /**\r\n * @param honourFragment whether the URL's fragment should be SCROLLED to\r\n * once the new page is on screen. True for a navigation the app asked for\r\n * — a `<Link>` click, `navigateTo` — and false for Back/Forward, where the\r\n * browser has already restored the scroll position of the entry being\r\n * returned to and moving the page again would overwrite the user's own\r\n * position with the anchor they had scrolled away from. (Restoration is\r\n * the browser's, deliberately: canon `0342c0d4`.)\r\n *\r\n * The fragment is still PRESERVED in the URL in both cases — see below.\r\n */\r\n const apply = async (\r\n url: string,\r\n replace: boolean,\r\n honourFragment: boolean,\r\n ): Promise<void> => {\r\n const ticket = ++token;\r\n /*\r\n A prefetched response is CONSUMED, never merely read — `take` removes it,\r\n so the same speculative fetch can satisfy exactly one navigation and a\r\n second click on the same link goes to the network. That matters because\r\n the HTTP cache cannot stand in for this: dev responses are `no-store`\r\n (`server/dev-server.ts:254`) and production is `private` with no\r\n `max-age` (`server/render-page.ts:432`), so the browser will not reliably\r\n replay the speculative response on the real click.\r\n\r\n The race guard below still holds on a cache hit: `??` short-circuits the\r\n await, and the synchronous path reaches the same `ticket !== token` check.\r\n */\r\n const result = takePrefetchedPageData(url) ?? (await fetchPageData(url));\r\n\r\n if (disposed || ticket !== token) return;\r\n\r\n if (result.type === \"hard-navigate\") {\r\n // The documented degradation: hand the URL back to the browser. The\r\n // user still gets the page — see `fetch-page-data.ts`.\r\n console.warn(`Warlock navigation fell back to a full load (${result.reason}):`, url);\r\n window.location.assign(url);\r\n\r\n return;\r\n }\r\n\r\n let tree: ReactNode;\r\n\r\n try {\r\n tree = await buildTree(pages, result.payload);\r\n } catch (error) {\r\n // The payload was fine but its page chunk would not load or compose —\r\n // a stale bundle after a deploy is the realistic cause. A full load\r\n // fetches the current bundle, which is also the fix.\r\n console.warn(\"Warlock navigation could not build the page tree:\", error);\r\n window.location.assign(url);\r\n\r\n return;\r\n }\r\n\r\n if (disposed || ticket !== token) return;\r\n\r\n /*\r\n Shared state BEFORE the render that consumes it. `hydrateShared`\r\n installs the snapshot `useShared()` reads; swapping the tree first would\r\n render one frame of the new page against the previous page's shared\r\n state — locale, permissions, the current user.\r\n */\r\n hydrateShared(result.payload.shared);\r\n\r\n /*\r\n The fragment PUT BACK. `result.url` comes from `response.url`, and a\r\n fragment is never sent to a server, so the URL a navigation would\r\n otherwise be written to history from has had it stripped — which is how\r\n `<Link href=\"/docs#install\">` used to land on `/docs` with the author's\r\n fragment gone from the address bar for good.\r\n\r\n Applied on EVERY path, Back included: a popstate re-fetch that wrote\r\n `result.url` back would delete the fragment from an entry the user is\r\n merely returning to.\r\n */\r\n const finalUrl = withFragmentFrom(result.url, url);\r\n\r\n // History AFTER the fetch succeeded, never before. Pushing optimistically\r\n // would leave the address bar pointing at a page that then failed to\r\n // load, and a Back press would return to a URL the user never saw.\r\n if (replace) {\r\n window.history.replaceState(null, \"\", finalUrl);\r\n } else {\r\n window.history.pushState(null, \"\", finalUrl);\r\n }\r\n\r\n committedUrl = finalUrl;\r\n\r\n // Handed to the layout effect, which runs once React has committed the\r\n // tree below to the DOM — the first moment the target can exist. Set\r\n // unconditionally so a navigation with no fragment CLEARS a fragment left\r\n // pending by one that was superseded.\r\n pendingFragment.current = honourFragment ? fragmentOf(finalUrl) : undefined;\r\n\r\n // A navigation IS the route moving, so the fetched payload is both the\r\n // page and the route's identity.\r\n setCurrent({ payload: result.payload, tree, routeSource: result.payload });\r\n };\r\n\r\n /*\r\n The same counter `apply` above takes its tickets from, handed to\r\n `refresh()` as a predicate. ONE mechanism, not two: a refresh and a\r\n navigation can overtake each other in either direction, and separate\r\n counters would leave each blind to the other.\r\n */\r\n const claimTicket = (): (() => boolean) => {\r\n const ticket = ++token;\r\n\r\n return () => !disposed && ticket === token;\r\n };\r\n\r\n const previousRefresher = connectRefresher(\r\n createRefresher({\r\n readCurrent: () => currentRef.current,\r\n writeCurrent: setCurrent,\r\n buildTree: payload => buildTree(pages, payload),\r\n claimTicket,\r\n }),\r\n );\r\n\r\n const previousNavigator = connectNavigator((url, options) => {\r\n const replace = options?.replace === true;\r\n\r\n /*\r\n THIS page with a fragment on it — `#reviews`, or the current path spelled\r\n out with one appended. No fetch, no tree swap: the page is already here,\r\n and re-fetching it would discard its DOM and everything live in it to\r\n arrive back where we started, one round trip later. Address bar first,\r\n then the jump, which is the order the browser uses for a plain anchor.\r\n */\r\n const fragment = samePageFragment(url, window.location.href);\r\n\r\n if (fragment !== undefined) {\r\n if (replace) {\r\n window.history.replaceState(null, \"\", url);\r\n } else {\r\n window.history.pushState(null, \"\", url);\r\n }\r\n\r\n committedUrl = window.location.href;\r\n\r\n // The target is in the DOM already, so there is nothing to wait for —\r\n // and nothing to hand to the layout effect, which no swap would fire.\r\n scrollToFragment(document, fragment);\r\n\r\n return true;\r\n }\r\n\r\n void apply(url, replace, true);\r\n\r\n // Accepted: the caller suppresses the browser's default. Returning `true`\r\n // before the fetch resolves is deliberate — the decision to handle a link\r\n // cannot wait on the network without the browser having already followed\r\n // it.\r\n return true;\r\n });\r\n\r\n /*\r\n Back/Forward. The entry is already in history and the URL has already\r\n changed by the time this fires, so the page is fetched and swapped with\r\n `replace` — pushing here would append a duplicate entry and make Back\r\n require two presses.\r\n */\r\n const onPopState = (): void => {\r\n const target = window.location.href;\r\n /*\r\n A hash-only move within one page — Back off a `#section` click, or\r\n Forward onto one. The document is the same document and the tree on\r\n screen is already the right tree, so there is nothing to fetch: the\r\n browser has changed the URL and restored the position for that entry\r\n itself, and re-fetching would throw away a live page to rebuild the one\r\n already showing. Scroll restoration stays the browser's (canon\r\n `0342c0d4`), which is exactly what leaving this alone means.\r\n */\r\n const hashOnlyMove = withoutFragment(target) === withoutFragment(committedUrl);\r\n\r\n committedUrl = target;\r\n\r\n if (hashOnlyMove) return;\r\n\r\n void apply(target, true, false);\r\n };\r\n\r\n window.addEventListener(\"popstate\", onPopState);\r\n\r\n return () => {\r\n disposed = true;\r\n window.removeEventListener(\"popstate\", onPopState);\r\n connectNavigator(previousNavigator);\r\n connectRefresher(previousRefresher);\r\n };\r\n }, [pages, buildTree]);\r\n\r\n /*\r\n THE OTHER HALF OF THE ORDERING PROBLEM (see `pendingFragment` above).\r\n\r\n `useLayoutEffect`, not `useEffect`, and the difference is the whole point:\r\n React runs a layout effect after it has COMMITTED this render to the DOM and\r\n BEFORE the browser paints. That is the earliest instant the new page's\r\n elements exist — a scroll any sooner finds nothing — and the last instant\r\n before the user sees anything, so the page is never painted at the top and\r\n then jumped. `useEffect` would satisfy the first requirement and not the\r\n second: it runs after paint, which is a visible flash of the wrong position.\r\n\r\n Keyed on `current` rather than reaching for a fresh render: the effect fires\r\n on the swap that put the target in the DOM, so no polling, no rAF, no\r\n timeout. What it CANNOT wait for is content that arrives later still — an\r\n image without dimensions above the target, a component that suspends — which\r\n moves the target after we have scrolled to where it was. That is the known\r\n limit of this mechanism and it is the same one a browser has.\r\n\r\n Consumed once: the fragment is cleared as it is read, so a later re-render\r\n (a refresh, a parent's state change) does not yank the page back to an\r\n anchor the user has since scrolled away from.\r\n */\r\n useLayoutEffect(() => {\r\n const fragment = pendingFragment.current;\r\n\r\n if (fragment === undefined) return;\r\n\r\n pendingFragment.current = undefined;\r\n\r\n scrollToFragment(document, fragment);\r\n }, [current]);\r\n\r\n /*\r\n The payload whose metadata `<head>` currently reflects. Seeded with the\r\n HYDRATION payload, which is the point: on the initial mount the head is the\r\n server's own render of this very metadata, so there is nothing to correct —\r\n and re-applying would be a chance to get it wrong, since a payload from a\r\n build with no `metadata` key would wipe a head the server filled in\r\n correctly. The head is applied on SWAPS only.\r\n */\r\n const appliedMetadataSource = useRef(current.payload);\r\n\r\n useEffect(() => {\r\n if (appliedMetadataSource.current === current.payload) return;\r\n\r\n appliedMetadataSource.current = current.payload;\r\n\r\n /*\r\n Keyed on the payload's identity, so this covers a refresh as well as a\r\n navigation: `refresh()` produces a NEW payload for the page already on\r\n screen, and a page whose metadata is a function of its loader data can\r\n legitimately re-title itself when that data changes. One applier at the\r\n one place the page changes, rather than a call in each pathway that could\r\n be forgotten in the next one.\r\n */\r\n applyDocumentMetadata(document, current.payload.metadata);\r\n }, [current.payload]);\r\n\r\n /*\r\n DURING RENDER, not in an effect, and that placement is the requirement\r\n rather than a shortcut. A page component calling `currentRoute()` does it\r\n while IT is rendering, and child effects run before a parent's, so anything\r\n recorded from an effect here would be recorded too late to answer the first\r\n render of the page it describes — which on the initial mount is the only\r\n render there has been, and the server's match is all there is.\r\n\r\n Recording is keyed on the payload's identity (`current-route.ts`), so the\r\n extra passes render gives us for free — StrictMode's double invoke, a parent\r\n re-render — are recognised as the same page rather than counted as\r\n navigations.\r\n\r\n `routeSource`, NOT `payload`: they are the same object for every navigation,\r\n and differ only after a refresh, which produces a new payload for the page\r\n already on screen and must not be counted as a move (see `refresh.ts`).\r\n */\r\n recordCurrentRoute(current.routeSource);\r\n\r\n /*\r\n An INNER DocumentContext provider, nested inside the one `hydratePage`\r\n mounted. That outer provider is created once with the hydration payload and\r\n never changes, so anything reading the document context after a navigation\r\n would see the payload of the page the user has left. The nearest provider\r\n wins, so this one keeps it current.\r\n */\r\n /*\r\n `metadata` from the PAYLOAD, not `undefined`. The document context is the\r\n universal shape — the server provides the resolved metadata around the same\r\n tree — so handing the client's readers `undefined` was a lie the payload can\r\n now correct. It also removes a latent mismatch: a `<Head/>` rendered inside\r\n a Layout (not the App level) renders its tags into `#root` server-side, and\r\n hydrating that markup against `metadata: undefined` produced a tree the\r\n server never rendered.\r\n */\r\n return (\n <DocumentContext.Provider\n value={{ metadata: current.payload.metadata, payload: current.payload }}\n >\n <LocaleProvider locale={current.payload.locale}>{current.tree}</LocaleProvider>\n </DocumentContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAqDA,SAAS,QAAQ,WAAgC,KAAyB;CACxE,OAAO;EACL,UAAU,QAAQ,UAAU,IAAI,IAAI;EACpC,SAAQ,iBAAgB;GACtB,MAAM,UAAU,aAAa,cAAc,MAAM;GAEjD,QAAQ,aAAa,WAAW,GAAG;GAEnC,OAAO;EACT;EACA,QAAQ,SAAS,UAAU,QAAQ,aAAa,WAAW,KAAK;CAClE;AACF;AAEA,MAAM,YAAwB;CAC5B,UAAU;CACV,SAAQ,iBAAgB,aAAa,cAAc,OAAO;CAC1D,QAAQ,SAAS,UAAU;EACzB,QAAQ,cAAc;CACxB;AACF;AAEA,M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