@warlock.js/web 5.1.0 → 5.2.1
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/CHANGELOG.md +182 -0
- package/README.md +126 -12
- package/esm/build/contribution.d.mts +10 -13
- package/esm/build/contribution.mjs +45 -57
- package/esm/build/contribution.mjs.map +1 -1
- package/esm/build/discover-pages.mjs +104 -44
- package/esm/build/discover-pages.mjs.map +1 -1
- package/esm/build/generate-client-registry.mjs +46 -12
- package/esm/build/generate-client-registry.mjs.map +1 -1
- package/esm/build/generate-pages-barrel.mjs +54 -12
- package/esm/build/generate-pages-barrel.mjs.map +1 -1
- package/esm/build/page-default-export.mjs +48 -0
- package/esm/build/page-default-export.mjs.map +1 -0
- package/esm/build/page-routes-manifest.mjs +21 -0
- package/esm/build/page-routes-manifest.mjs.map +1 -0
- package/esm/build/public-files.mjs +45 -0
- package/esm/build/public-files.mjs.map +1 -0
- package/esm/build/read-route-exports.mjs.map +1 -1
- package/esm/client/build-hydrated-tree.mjs +39 -8
- package/esm/client/build-hydrated-tree.mjs.map +1 -1
- package/esm/client/navigation/fetch-page-data.mjs.map +1 -1
- package/esm/client/navigation/prefetch.mjs.map +1 -1
- package/esm/client/runtime/index.d.mts +2 -1
- package/esm/client/runtime/index.mjs +2 -1
- package/esm/client/runtime/manifest.mjs +2 -1
- package/esm/client/runtime/manifest.mjs.map +1 -1
- package/esm/client/runtime/matcher.d.mts +12 -0
- package/esm/client/runtime/matcher.mjs +12 -0
- package/esm/client/runtime/matcher.mjs.map +1 -1
- package/esm/client/runtime/types.d.mts +14 -1
- package/esm/components/document-context.d.mts +39 -1
- package/esm/components/document-context.mjs.map +1 -1
- package/esm/components/link.mjs.map +1 -1
- package/esm/components/scripts.mjs +3 -1
- package/esm/components/scripts.mjs.map +1 -1
- package/esm/context.d.mts +5 -101
- package/esm/hydration-payload.d.mts +1 -1
- package/esm/hydration-payload.mjs +36 -7
- package/esm/hydration-payload.mjs.map +1 -1
- package/esm/index.d.mts +3 -2
- package/esm/loaders.d.mts +6 -35
- package/esm/props.d.mts +15 -7
- package/esm/route.d.mts +1 -16
- package/esm/routing/filesystem-route.mjs +45 -0
- package/esm/routing/filesystem-route.mjs.map +1 -0
- package/esm/routing/layout-policy.mjs.map +1 -1
- package/esm/routing/query-string.mjs.map +1 -1
- package/esm/routing/route-table.mjs.map +1 -1
- package/esm/runtime/register-modules.d.mts +19 -0
- package/esm/runtime/register-modules.mjs +22 -0
- package/esm/runtime/register-modules.mjs.map +1 -0
- package/esm/server/build-hydration-payload.mjs +1 -0
- package/esm/server/build-hydration-payload.mjs.map +1 -1
- package/esm/server/create-page-module-loader.mjs +1 -0
- package/esm/server/create-page-module-loader.mjs.map +1 -1
- package/esm/server/create-page-route-handler.d.mts +30 -5
- package/esm/server/create-page-route-handler.mjs +127 -42
- package/esm/server/create-page-route-handler.mjs.map +1 -1
- package/esm/server/dev-server.mjs +1 -12
- package/esm/server/dev-server.mjs.map +1 -1
- package/esm/server/error-page.d.mts +14 -0
- package/esm/server/error-page.mjs +39 -0
- package/esm/server/error-page.mjs.map +1 -0
- package/esm/server/execute-page-request.d.mts +6 -3
- package/esm/server/execute-page-request.mjs +78 -79
- package/esm/server/execute-page-request.mjs.map +1 -1
- package/esm/server/execute-page-request.types.d.mts +32 -91
- package/esm/server/hydration-client-url.mjs +1 -1
- package/esm/server/index.d.mts +5 -5
- package/esm/server/index.mjs +3 -4
- package/esm/server/install-page-routes-from-manifest.d.mts +16 -6
- package/esm/server/install-page-routes-from-manifest.mjs +70 -9
- package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
- package/esm/server/install-page-routes.d.mts +31 -14
- package/esm/server/install-page-routes.mjs +90 -38
- package/esm/server/install-page-routes.mjs.map +1 -1
- package/esm/server/install-production-page-routes.mjs +2 -35
- package/esm/server/install-production-page-routes.mjs.map +1 -1
- package/esm/server/match-page-route.mjs +1 -1
- package/esm/server/match-page-route.mjs.map +1 -1
- package/esm/server/not-found-page.mjs +1 -1
- package/esm/server/not-found-page.mjs.map +1 -1
- package/esm/server/page-context.d.mts +2 -8
- package/esm/server/page-context.mjs +2 -15
- package/esm/server/page-context.mjs.map +1 -1
- package/esm/server/page-file-change.mjs +77 -0
- package/esm/server/page-file-change.mjs.map +1 -0
- package/esm/server/page-manifest.d.mts +24 -9
- package/esm/server/page-manifest.mjs.map +1 -1
- package/esm/server/page-render-bundle.mjs +38 -0
- package/esm/server/page-render-bundle.mjs.map +1 -0
- package/esm/server/page-route-reload.mjs +54 -0
- package/esm/server/page-route-reload.mjs.map +1 -0
- package/esm/server/register-production-public-files.mjs +40 -0
- package/esm/server/register-production-public-files.mjs.map +1 -0
- package/esm/server/render-page.d.mts +10 -13
- package/esm/server/render-page.mjs +153 -27
- package/esm/server/render-page.mjs.map +1 -1
- package/esm/server/resolve-page-metadata.mjs +1 -1
- package/esm/server/resolve-page-metadata.mjs.map +1 -1
- package/esm/server/settle-page-response.d.mts +58 -1
- package/esm/server/settle-page-response.mjs +110 -45
- package/esm/server/settle-page-response.mjs.map +1 -1
- package/esm/server/stylesheet-urls.d.mts +40 -29
- package/esm/server/stylesheet-urls.mjs +136 -51
- package/esm/server/stylesheet-urls.mjs.map +1 -1
- package/esm/server/unregistered-pages.mjs +42 -0
- package/esm/server/unregistered-pages.mjs.map +1 -0
- package/esm/server/web-connector-factory.d.mts +1 -2
- package/esm/server/web-connector-factory.mjs +6 -5
- package/esm/server/web-connector-factory.mjs.map +1 -1
- package/esm/server/web-connector.mjs +137 -17
- package/esm/server/web-connector.mjs.map +1 -1
- package/esm/shared.d.mts +17 -2
- package/esm/shared.mjs +2 -6
- package/esm/shared.mjs.map +1 -1
- package/esm/vite/build-client.mjs +1 -1
- package/esm/vite/build-client.mjs.map +1 -1
- package/esm/vite/gate-a-resolve.mjs +66 -12
- package/esm/vite/gate-a-resolve.mjs.map +1 -1
- package/esm/vite/gate-b-secrets.mjs +34 -16
- package/esm/vite/gate-b-secrets.mjs.map +1 -1
- package/esm/vite/gate-c-verify.mjs +5 -5
- package/esm/vite/gate-c-verify.mjs.map +1 -1
- package/esm/vite/hydration-entries.mjs +1 -1
- package/esm/vite/hydration-entries.mjs.map +1 -1
- package/esm/vite/index.d.mts +8 -5
- package/esm/vite/index.mjs +123 -10
- package/esm/vite/index.mjs.map +1 -1
- package/esm/vite/page-registry-plugin.d.mts +21 -2
- package/esm/vite/page-registry-plugin.mjs +47 -13
- package/esm/vite/page-registry-plugin.mjs.map +1 -1
- package/esm/vite/projection.d.mts +1 -1
- package/esm/vite/projection.mjs +37 -14
- package/esm/vite/projection.mjs.map +1 -1
- package/llms-full.txt +220 -56
- package/llms.txt +5 -3
- package/package.json +3 -3
- package/skills/add-web-to-an-app/SKILL.md +3 -3
- package/skills/create-a-page/SKILL.md +117 -10
- package/skills/load-page-data/SKILL.md +92 -12
- package/skills/navigate-on-the-client/SKILL.md +1 -1
- package/skills/serve-styles/SKILL.md +13 -12
- package/skills/use-layouts/SKILL.md +14 -8
- package/skills/write-the-root/SKILL.md +3 -1
- package/esm/server/buffered-response.d.mts +0 -58
- package/esm/server/buffered-response.mjs +0 -115
- package/esm/server/buffered-response.mjs.map +0 -1
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { composeRoutePath } from "../routing/compose-route-path.mjs";
|
|
2
|
+
import { deriveFilesystemRouteName, deriveFilesystemRoutePath } from "../routing/filesystem-route.mjs";
|
|
2
3
|
import { NestedLayoutsNotSupportedError, selectPageLayout } from "../routing/layout-policy.mjs";
|
|
3
4
|
import { deriveFallbackRouteName } from "../routing/route-identity.mjs";
|
|
4
5
|
import { NOT_FOUND_ROUTE_NAME, NOT_FOUND_ROUTE_PATH, NotFoundPageDeclaresRouteError, isNotFoundPageFile } from "../server/not-found-page.mjs";
|
|
5
6
|
import { METADATA_KEYS, OPEN_GRAPH_KEYS, TWITTER_KEYS } from "../metadata.mjs";
|
|
7
|
+
import { assertPageHasDefaultExport } from "./page-default-export.mjs";
|
|
6
8
|
import { NonLiteralRouteExportError, readRouteExports } from "./read-route-exports.mjs";
|
|
7
|
-
import path from "node:path";
|
|
8
9
|
import fs from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
9
11
|
import { parse } from "@babel/parser";
|
|
10
12
|
|
|
11
13
|
//#region ../web/src/build/discover-pages.ts
|
|
@@ -31,13 +33,11 @@ import { parse } from "@babel/parser";
|
|
|
31
33
|
* `route` and each layout's declared `prefix` by PARSING the source
|
|
32
34
|
* ({@link readRouteExports}). It still imports no application module.
|
|
33
35
|
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* deliberately and in one direction: build and boot agree because one of them
|
|
40
|
-
* copies the other, not because two conventions were written to match.
|
|
36
|
+
* An explicit `route` export wins. Otherwise the URL is derived from the page's
|
|
37
|
+
* path beneath `src/web`: directories contribute segments, `(groups)` do not,
|
|
38
|
+
* `index.page.tsx` claims its directory, and `[id]` becomes `:id`. A layout
|
|
39
|
+
* `prefix` replaces its own directory segment. The same recipe is emitted to
|
|
40
|
+
* every provider so build and boot cannot drift.
|
|
41
41
|
*
|
|
42
42
|
* Discovery also CLASSIFIES each layout — does its module have a default
|
|
43
43
|
* export, does it export `middleware` — because the layout policy
|
|
@@ -49,6 +49,24 @@ import { parse } from "@babel/parser";
|
|
|
49
49
|
* see that error and {@link readMetadataKeys} for why a type alone does not
|
|
50
50
|
* close that hole.
|
|
51
51
|
*/
|
|
52
|
+
function isDiscoveredRoutablePage(page) {
|
|
53
|
+
return page.type === "page";
|
|
54
|
+
}
|
|
55
|
+
function isErrorPageFile(file) {
|
|
56
|
+
return path.basename(file) === "error.page.tsx";
|
|
57
|
+
}
|
|
58
|
+
var DuplicateErrorPageError = class extends Error {
|
|
59
|
+
constructor(firstFile, secondFile) {
|
|
60
|
+
super(`Two error pages were found: "${firstFile}" and "${secondFile}". An application may own exactly one \`error.page.tsx\` anywhere beneath src/web.`);
|
|
61
|
+
this.name = "DuplicateErrorPageError";
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
var ErrorPageDeclaresRouteError = class extends Error {
|
|
65
|
+
constructor(pageFile) {
|
|
66
|
+
super(`The error page "${pageFile}" exports \`route\`. error.page.tsx is an error boundary, not a browsable page; remove the route export.`);
|
|
67
|
+
this.name = "ErrorPageDeclaresRouteError";
|
|
68
|
+
}
|
|
69
|
+
};
|
|
52
70
|
/** Raised when two pages claim one route name. */
|
|
53
71
|
var DuplicatePageRouteNameError = class extends Error {
|
|
54
72
|
routeName;
|
|
@@ -62,6 +80,19 @@ var DuplicatePageRouteNameError = class extends Error {
|
|
|
62
80
|
this.name = "DuplicatePageRouteNameError";
|
|
63
81
|
}
|
|
64
82
|
};
|
|
83
|
+
/** Raised when two different page files resolve to one effective URL. */
|
|
84
|
+
var DuplicatePageRoutePathError = class extends Error {
|
|
85
|
+
routePath;
|
|
86
|
+
firstFile;
|
|
87
|
+
secondFile;
|
|
88
|
+
constructor(routePath, firstFile, secondFile) {
|
|
89
|
+
super(`Two pages resolve to the same route path "${routePath}": "${firstFile}" and "${secondFile}". Each URL may identify exactly one page. Rename or move one file, or give one page an explicit route with a different path.`);
|
|
90
|
+
this.routePath = routePath;
|
|
91
|
+
this.firstFile = firstFile;
|
|
92
|
+
this.secondFile = secondFile;
|
|
93
|
+
this.name = "DuplicatePageRoutePathError";
|
|
94
|
+
}
|
|
95
|
+
};
|
|
65
96
|
function toPosix(value) {
|
|
66
97
|
return value.replace(/\\/g, "/");
|
|
67
98
|
}
|
|
@@ -80,27 +111,18 @@ function isFile(candidate) {
|
|
|
80
111
|
}
|
|
81
112
|
}
|
|
82
113
|
/**
|
|
83
|
-
* The
|
|
84
|
-
*
|
|
85
|
-
* neither has zero pages, which is a legal empty state.
|
|
114
|
+
* The page root. It is optional; a project without it has zero pages, which is
|
|
115
|
+
* a legal empty state.
|
|
86
116
|
*/
|
|
87
117
|
function discoverWebRoots(srcRoot) {
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
if (isDirectory(globalRoot)) roots.push(globalRoot);
|
|
91
|
-
const appDir = path.join(srcRoot, "app");
|
|
92
|
-
if (isDirectory(appDir)) for (const entry of fs.readdirSync(appDir, { withFileTypes: true }).sort(byName)) {
|
|
93
|
-
if (!entry.isDirectory()) continue;
|
|
94
|
-
const moduleWebRoot = path.join(appDir, entry.name, "web");
|
|
95
|
-
if (isDirectory(moduleWebRoot)) roots.push(moduleWebRoot);
|
|
96
|
-
}
|
|
97
|
-
return roots;
|
|
118
|
+
const webRoot = path.join(srcRoot, "web");
|
|
119
|
+
return isDirectory(webRoot) ? [webRoot] : [];
|
|
98
120
|
}
|
|
99
121
|
function byName(left, right) {
|
|
100
122
|
return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;
|
|
101
123
|
}
|
|
102
124
|
/**
|
|
103
|
-
* The subject list: every `*.page.tsx` under
|
|
125
|
+
* The subject list: every `*.page.tsx` under the page root, one call for the
|
|
104
126
|
* whole graph.
|
|
105
127
|
*
|
|
106
128
|
* Unlike {@link discoverPages}, this reads no `route` or `prefix` export and
|
|
@@ -185,15 +207,27 @@ function assertUniqueRouteNames(pages, appRoot) {
|
|
|
185
207
|
fileByRouteName.set(page.routeName, relative);
|
|
186
208
|
}
|
|
187
209
|
}
|
|
188
|
-
/**
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
210
|
+
/**
|
|
211
|
+
* A page's declared `route.path` is a choice its author made deliberately, so
|
|
212
|
+
* two pages that both declare the same path are the author's call, not an
|
|
213
|
+
* accident — {@link assertUniqueRouteNames} is what keeps each of them
|
|
214
|
+
* reachable by name. What this refuses is a COLLISION NOBODY CHOSE: at least
|
|
215
|
+
* one side's path is filesystem-derived, which is exactly the case a rename
|
|
216
|
+
* or a new file can produce without anyone noticing two pages now answer the
|
|
217
|
+
* same URL. The reserved not-found path (`"*"`) is never a candidate here
|
|
218
|
+
* either way — it identifies no browsable URL, and {@link assertUniqueRouteNames}
|
|
219
|
+
* already refuses a second `404.page.tsx` by its own reserved name.
|
|
220
|
+
*/
|
|
221
|
+
function assertUniqueRoutePaths(pages, appRoot, explicitFiles) {
|
|
222
|
+
const fileByRoutePath = /* @__PURE__ */ new Map();
|
|
223
|
+
for (const page of pages) {
|
|
224
|
+
if (page.routePath === "*") continue;
|
|
225
|
+
const existing = fileByRoutePath.get(page.routePath);
|
|
226
|
+
const relative = toPosix(path.relative(appRoot, page.pageFile));
|
|
227
|
+
if (existing !== void 0 && !(explicitFiles.has(existing) && explicitFiles.has(relative))) throw new DuplicatePageRoutePathError(page.routePath, existing, relative);
|
|
228
|
+
if (existing === void 0) fileByRoutePath.set(page.routePath, relative);
|
|
195
229
|
}
|
|
196
|
-
}
|
|
230
|
+
}
|
|
197
231
|
/**
|
|
198
232
|
* Raised when a page's `metadata` export declares a key nothing reads.
|
|
199
233
|
*
|
|
@@ -207,9 +241,8 @@ var MissingRouteExportError = class extends Error {
|
|
|
207
241
|
* missing one — and no error is raised anywhere, at build or at runtime, ever.
|
|
208
242
|
*
|
|
209
243
|
* So the check lives HERE instead, at the gate every page already passes
|
|
210
|
-
* through
|
|
211
|
-
*
|
|
212
|
-
* which line to fix.
|
|
244
|
+
* through: a page that silently omits requested metadata is worse than a build
|
|
245
|
+
* that stops and says which line to fix.
|
|
213
246
|
*
|
|
214
247
|
* The alternative considered and rejected was a `defineMetadata({...})` wrapper,
|
|
215
248
|
* which would infer the type for free. It also puts framework ceremony in every
|
|
@@ -461,13 +494,12 @@ function readLayoutShape(layoutFile, cache) {
|
|
|
461
494
|
return shape;
|
|
462
495
|
}
|
|
463
496
|
/**
|
|
464
|
-
* Scans
|
|
497
|
+
* Scans the page root and returns the pages in a defined total order.
|
|
465
498
|
*
|
|
466
499
|
* Zero pages is a legal result, not an error: a project may be configured
|
|
467
500
|
* with web and have nothing to serve yet. What is an error is a `*.page.tsx`
|
|
468
|
-
* with
|
|
469
|
-
*
|
|
470
|
-
* production 404s on; two pages claiming one route name, which this refuses
|
|
501
|
+
* with a route or metadata export that cannot be read statically; two pages
|
|
502
|
+
* claiming one effective path or route name, which this refuses
|
|
471
503
|
* to return at all — the alternative is an artefact in which one of them is
|
|
472
504
|
* silently unreachable; a `route` or `prefix` that cannot be read without
|
|
473
505
|
* running the application, which is refused before any page is reported at
|
|
@@ -487,12 +519,25 @@ function discoverPages(options) {
|
|
|
487
519
|
const layoutShapes = /* @__PURE__ */ new Map();
|
|
488
520
|
const relativeToApp = (file) => toPosix(path.relative(appRoot, file));
|
|
489
521
|
const pages = [];
|
|
522
|
+
const explicitRouteFiles = /* @__PURE__ */ new Set();
|
|
523
|
+
let errorPage;
|
|
490
524
|
for (const webRoot of webRoots) for (const pageFile of walkFiles(webRoot, (fileName) => fileName.endsWith(".page.tsx"))) {
|
|
491
525
|
const pageSource = fs.readFileSync(pageFile, "utf-8");
|
|
526
|
+
assertPageHasDefaultExport(relativeToApp(pageFile), pageSource);
|
|
492
527
|
const { route } = readDeclarations(pageFile, declarations, pageSource);
|
|
528
|
+
if (isErrorPageFile(pageFile)) {
|
|
529
|
+
if (route !== void 0) throw new ErrorPageDeclaresRouteError(relativeToApp(pageFile));
|
|
530
|
+
if (errorPage !== void 0) throw new DuplicateErrorPageError(relativeToApp(errorPage.pageFile), relativeToApp(pageFile));
|
|
531
|
+
errorPage = {
|
|
532
|
+
type: "error",
|
|
533
|
+
pageFile,
|
|
534
|
+
webRoot,
|
|
535
|
+
...hasAppFile ? { appFile } : {}
|
|
536
|
+
};
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
493
539
|
const isNotFoundPage = isNotFoundPageFile(pageFile);
|
|
494
540
|
if (isNotFoundPage && route !== void 0) throw new NotFoundPageDeclaresRouteError(relativeToApp(pageFile));
|
|
495
|
-
if (route === void 0 && !isNotFoundPage) throw new MissingRouteExportError(relativeToApp(pageFile));
|
|
496
541
|
const unknownMetadataKeys = readMetadataKeys(relativeToApp(pageFile), pageSource);
|
|
497
542
|
if (unknownMetadataKeys.length > 0) throw new UnknownMetadataKeyError(relativeToApp(pageFile), unknownMetadataKeys);
|
|
498
543
|
const layouts = layoutChainFor(pageFile, webRoot);
|
|
@@ -504,12 +549,24 @@ function discoverPages(options) {
|
|
|
504
549
|
if (selection.type === "rejected") throw new NestedLayoutsNotSupportedError(relativeToApp(pageFile), selection.layouts.map(relativeToApp));
|
|
505
550
|
const middlewareLayouts = layouts.filter((_, index) => shapes[index].hasMiddleware);
|
|
506
551
|
const layoutPrefix = layouts.reduce((composed, layoutFile) => composeRoutePath(composed, readDeclarations(layoutFile, declarations).prefix ?? "/"), "/");
|
|
552
|
+
const relativePageFile = toPosix(path.relative(webRoot, pageFile));
|
|
553
|
+
const layoutPrefixes = Object.fromEntries(layouts.flatMap((layoutFile) => {
|
|
554
|
+
const prefix = readDeclarations(layoutFile, declarations).prefix;
|
|
555
|
+
if (prefix === void 0) return [];
|
|
556
|
+
return [[toPosix(path.relative(webRoot, path.dirname(layoutFile))), prefix]];
|
|
557
|
+
}));
|
|
558
|
+
const effectiveRoutePath = isNotFoundPage ? "*" : route ? composeRoutePath(layoutPrefix, route.path) : deriveFilesystemRoutePath({
|
|
559
|
+
pageFile: relativePageFile,
|
|
560
|
+
layoutPrefixes
|
|
561
|
+
});
|
|
562
|
+
if (!isNotFoundPage && route !== void 0) explicitRouteFiles.add(relativeToApp(pageFile));
|
|
507
563
|
pages.push({
|
|
508
|
-
|
|
509
|
-
|
|
564
|
+
type: "page",
|
|
565
|
+
routeName: isNotFoundPage ? NOT_FOUND_ROUTE_NAME : route?.name ?? (route ? deriveFallbackRouteName({
|
|
566
|
+
routePath: route.path,
|
|
510
567
|
sourceFile: relativeToApp(pageFile)
|
|
511
|
-
}),
|
|
512
|
-
routePath:
|
|
568
|
+
}) : deriveFilesystemRouteName(relativePageFile)),
|
|
569
|
+
routePath: effectiveRoutePath,
|
|
513
570
|
pageFile,
|
|
514
571
|
webRoot,
|
|
515
572
|
layouts: isNotFoundPage ? [] : layouts,
|
|
@@ -517,11 +574,14 @@ function discoverPages(options) {
|
|
|
517
574
|
...hasAppFile ? { appFile } : {}
|
|
518
575
|
});
|
|
519
576
|
}
|
|
577
|
+
if (errorPage !== void 0) pages.push(errorPage);
|
|
520
578
|
pages.sort(comparePages);
|
|
521
|
-
|
|
579
|
+
const routablePages = pages.filter(isDiscoveredRoutablePage);
|
|
580
|
+
assertUniqueRoutePaths(routablePages, appRoot, explicitRouteFiles);
|
|
581
|
+
assertUniqueRouteNames(routablePages, appRoot);
|
|
522
582
|
return pages;
|
|
523
583
|
}
|
|
524
584
|
|
|
525
585
|
//#endregion
|
|
526
|
-
export { DuplicatePageRouteNameError,
|
|
586
|
+
export { DuplicatePageRouteNameError, ErrorPageDeclaresRouteError, discoverPageFiles, discoverPages, discoverWebRoots, isDiscoveredRoutablePage, isErrorPageFile, isFile, layoutChainFor, toPosix, walkFiles };
|
|
527
587
|
//# sourceMappingURL=discover-pages.mjs.map
|
|
@@ -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 * The route a page is served under is the one the page DECLARES, not the one\n * its directory suggests, so that is the route discovery reports. The\n * composition — EVERY layout `prefix` on the page's path, outermost first, plus\n * the page's own `route` path — and the fallback used when a route omits its\n * name are mirrored from the server's installer (`installPageRoutes`),\n * deliberately and in one direction: build and boot agree because one of them\n * copies the other, not because two conventions were written to match.\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 { deriveFallbackRouteName } from \"../routing/route-identity\";\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 DiscoveredPage = {\n /**\n * The page's route name: the `name` its `route` export declares, or the\n * server's own fallback derivation — `<module>.<declared path with dots>` for\n * a page in a module's web tree, the dotted path alone for one in the global\n * tree, and `index` when neither has anything to say.\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: the declared `prefix` of EVERY layout on\n * its path — outermost first, wherever in the ancestry each lives — composed\n * in order with the page's own declared `route` path, which is the path the\n * server registers it under. A layout that declares no `prefix` contributes\n * nothing. Always `/`-prefixed.\n *\n * Every layout, not just the rendering one: a `prefix`-only layout is a real\n * segment of the URL its subtree lives under, and skipping it would serve the\n * subtree from a path nobody wrote down.\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/** 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\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 two page roots: the global `src/web/**` tree and each\n * module's `src/app/<module>/web/**` tree. Both are optional; a project with\n * neither has zero pages, which is a legal empty state.\n */\nexport function discoverWebRoots(srcRoot: string): string[] {\n const roots: string[] = [];\n const globalRoot = path.join(srcRoot, \"web\");\n\n if (isDirectory(globalRoot)) {\n roots.push(globalRoot);\n }\n\n const appDir = path.join(srcRoot, \"app\");\n\n if (isDirectory(appDir)) {\n for (const entry of fs.readdirSync(appDir, { withFileTypes: true }).sort(byName)) {\n if (!entry.isDirectory()) continue;\n\n const moduleWebRoot = path.join(appDir, entry.name, \"web\");\n\n if (isDirectory(moduleWebRoot)) {\n roots.push(moduleWebRoot);\n }\n }\n }\n\n return roots;\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 BOTH web roots, 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 DiscoveredPage[], 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/** Raised when a `*.page.tsx` declares no `route` export. */\nexport class MissingRouteExportError extends Error {\n public constructor(public readonly pageFile: string) {\n super(\n `\"${pageFile}\" is a page file but declares no \\`route\\` export. A page with no route is a ` +\n \"page nothing can ever reach, so both the dev server and the build refuse it instead of \" +\n `serving a silent 404. For example: export const route = \"/list\";`,\n );\n this.name = \"MissingRouteExportError\";\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, where a `route`-less page is refused by name for the same reason: a\n * page that silently does not work is worse than a build that stops and says\n * 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 both web roots 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 no `route` export, which is refused rather than silently omitted — an\n * artefact that leaves a page out is a page the dev server still serves and\n * production 404s on; two pages claiming one 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\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 const { route } = readDeclarations(pageFile, declarations, pageSource);\n const isNotFoundPage = isNotFoundPageFile(pageFile);\n\n // THE NOT-FOUND PAGE IS THE ONE PAGE WITH NO URL, in both directions.\n //\n // A missing `route` is refused for every other page because a page\n // nothing can reach is a page that was written by mistake. `404.page.tsx`\n // is reached by NOT matching, so the premise does not hold for it — and\n // the opposite is the error: a `route` export here reads as a promise\n // that some path is 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 if (route === undefined && !isNotFoundPage) {\n throw new MissingRouteExportError(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 route check on purpose: a page nothing can reach is a bigger\n // problem than a page reached with the wrong `<head>`, and reporting the\n // smaller one first would send the developer to the wrong line.\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 pages.push({\n routeName: isNotFoundPage\n ? NOT_FOUND_ROUTE_NAME\n : (route?.name ??\n deriveFallbackRouteName({\n routePath: route?.path ?? \"/\",\n sourceFile: relativeToApp(pageFile),\n })),\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: isNotFoundPage\n ? NOT_FOUND_ROUTE_PATH\n : composeRoutePath(layoutPrefix, route?.path ?? \"/\"),\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 pages.sort(comparePages);\n\n assertUniqueRouteNames(pages, appRoot);\n\n return pages;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuHA,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;AAEA,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,MAAM,QAAQ,OAAO,GAAG;AACjC;AAEA,SAAS,YAAY,WAA4B;CAC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uBAAuB,OAAO,OAAO;CAErC,OAAO;AACT"}
|
|
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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,MAAM,OAAO,wBAAwB;CAC3D,uBAAuB,eAAe,SAAS,kBAAkB;CACjE,uBAAuB,eAAe,OAAO;CAE7C,OAAO;AACT"}
|
|
@@ -1,4 +1,31 @@
|
|
|
1
|
+
import { isDiscoveredRoutablePage } from "./discover-pages.mjs";
|
|
2
|
+
|
|
1
3
|
//#region ../web/src/build/generate-client-registry.ts
|
|
4
|
+
/**
|
|
5
|
+
* The CLIENT half of the build→runtime handoff: the source of a generated
|
|
6
|
+
* module that carries the page graph into the BROWSER.
|
|
7
|
+
*
|
|
8
|
+
* `generate-pages-barrel.ts` is the server half. The two are deliberately not
|
|
9
|
+
* one function, because they want opposite things from the same recipe: the
|
|
10
|
+
* server barrel emits STATIC `import * as` so every page lands in the one
|
|
11
|
+
* server bundle and its route can be read off the module at boot, while the
|
|
12
|
+
* browser must never download page B to render page A — so every module
|
|
13
|
+
* reference here is a dynamic `import()`, and `name`/`path` are baked in as
|
|
14
|
+
* DATA so the client runtime can match a route before loading anything.
|
|
15
|
+
*
|
|
16
|
+
* This function is PURE. It reads no filesystem, writes no file, and does not
|
|
17
|
+
* call {@link discoverPages} — the caller passes the already-discovered graph
|
|
18
|
+
* in. That is what keeps the "one discovery run, one graph" invariant: names
|
|
19
|
+
* and paths agree with the server's because there is only ever one scan, not
|
|
20
|
+
* because two scanners were written to match.
|
|
21
|
+
*
|
|
22
|
+
* Module RESOLUTION is the one thing that legitimately differs between the dev
|
|
23
|
+
* provider and the production provider, so it is injected as
|
|
24
|
+
* {@link GenerateClientRegistryOptions.toImportSpecifier} rather than computed
|
|
25
|
+
* here. No provider-specific data — no Vite ids, no `/@fs/` prefixes, no
|
|
26
|
+
* hashed chunk urls, no HMR metadata — reaches the emitted entry, and every
|
|
27
|
+
* other property stays testable with a trivial mapper.
|
|
28
|
+
*/
|
|
2
29
|
/** The name of the array the generated module exports. */
|
|
3
30
|
const CLIENT_REGISTRY_EXPORT_NAME = "pages";
|
|
4
31
|
/** The specifier the generated module imports its entry type from. */
|
|
@@ -58,36 +85,41 @@ function assertUniqueNames(pages) {
|
|
|
58
85
|
* already module-cached by the bundler, so the correct implementation is to
|
|
59
86
|
* let the cache do the caching.
|
|
60
87
|
*/
|
|
61
|
-
function loadSource(page, toImportSpecifier) {
|
|
62
|
-
const bindings = ["
|
|
88
|
+
function loadSource(page, errorPageFile, toImportSpecifier) {
|
|
89
|
+
const bindings = ["PageModule"];
|
|
63
90
|
const specifiers = [toImportSpecifier(page.pageFile)];
|
|
64
91
|
const layoutBindings = page.layouts.map((layoutFile, index) => {
|
|
65
|
-
bindings.push(`
|
|
92
|
+
bindings.push(`layoutModule${index}`);
|
|
66
93
|
specifiers.push(toImportSpecifier(layoutFile));
|
|
67
|
-
return `
|
|
94
|
+
return `layoutModule${index}`;
|
|
68
95
|
});
|
|
69
96
|
if (page.appFile !== void 0) {
|
|
70
|
-
bindings.push("
|
|
97
|
+
bindings.push("AppModule");
|
|
71
98
|
specifiers.push(toImportSpecifier(page.appFile));
|
|
72
99
|
}
|
|
73
|
-
|
|
100
|
+
if (errorPageFile !== void 0) {
|
|
101
|
+
bindings.push("ErrorPageModule");
|
|
102
|
+
specifiers.push(toImportSpecifier(errorPageFile));
|
|
103
|
+
}
|
|
104
|
+
const app = page.appFile === void 0 ? "" : ", App: AppModule";
|
|
105
|
+
const errorPage = errorPageFile === void 0 ? "" : ", ErrorPage: ErrorPageModule";
|
|
74
106
|
return [
|
|
75
107
|
" load: async () => {",
|
|
76
108
|
` const [${bindings.join(", ")}] = await Promise.all([`,
|
|
77
109
|
...specifiers.map((specifier) => ` import(${quote(specifier)}),`),
|
|
78
110
|
" ]);",
|
|
79
111
|
"",
|
|
80
|
-
` return { Page, layouts: [${layoutBindings.join(", ")}]${app} };`,
|
|
112
|
+
` return { Page: PageModule, layouts: [${layoutBindings.join(", ")}]${app}${errorPage} };`,
|
|
81
113
|
" },"
|
|
82
114
|
];
|
|
83
115
|
}
|
|
84
|
-
function entrySource(page, toImportSpecifier) {
|
|
116
|
+
function entrySource(page, errorPageFile, toImportSpecifier) {
|
|
85
117
|
return [
|
|
86
118
|
" {",
|
|
87
119
|
" type: \"page\",",
|
|
88
120
|
` name: ${quote(page.routeName)},`,
|
|
89
121
|
` path: ${quote(page.routePath)},`,
|
|
90
|
-
...loadSource(page, toImportSpecifier),
|
|
122
|
+
...loadSource(page, errorPageFile, toImportSpecifier),
|
|
91
123
|
" },"
|
|
92
124
|
];
|
|
93
125
|
}
|
|
@@ -100,9 +132,11 @@ function entrySource(page, toImportSpecifier) {
|
|
|
100
132
|
*/
|
|
101
133
|
function generateClientRegistry(options) {
|
|
102
134
|
const { pages, toImportSpecifier } = options;
|
|
103
|
-
|
|
135
|
+
const routablePages = pages.filter(isDiscoveredRoutablePage);
|
|
136
|
+
const errorPageFile = pages.find((page) => page.type === "error")?.pageFile;
|
|
137
|
+
assertUniqueNames(routablePages);
|
|
104
138
|
const declaration = `export const ${CLIENT_REGISTRY_EXPORT_NAME}: readonly ClientPageEntry[] =`;
|
|
105
|
-
if (
|
|
139
|
+
if (routablePages.length === 0) return [
|
|
106
140
|
...HEADER,
|
|
107
141
|
"",
|
|
108
142
|
`${declaration} [];`,
|
|
@@ -112,7 +146,7 @@ function generateClientRegistry(options) {
|
|
|
112
146
|
...HEADER,
|
|
113
147
|
"",
|
|
114
148
|
`${declaration} [`,
|
|
115
|
-
...
|
|
149
|
+
...routablePages.flatMap((page) => entrySource(page, errorPageFile, toImportSpecifier)),
|
|
116
150
|
"];",
|
|
117
151
|
""
|
|
118
152
|
].join("\n");
|