@k8ordo/framework 1.4.3 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/generated.d.mts +23 -2
- package/dist/runtime/app-router.d.mts +10 -10
- package/dist/runtime/app-router.mjs +119 -83
- package/dist/runtime/browser-payloads.mjs +2 -1
- package/dist/runtime/client-files.d.mts +11 -0
- package/dist/runtime/client-files.mjs +42 -0
- package/dist/runtime/client-ready.d.mts +3 -2
- package/dist/runtime/document-root.mjs +1 -1
- package/dist/runtime/entry.browser.d.mts +1 -1
- package/dist/runtime/entry.browser.mjs +8 -12
- package/dist/runtime/entry.rsc.mjs +148 -102
- package/dist/runtime/entry.ssr.d.mts +21 -1
- package/dist/runtime/entry.ssr.mjs +10 -13
- package/dist/runtime/head-scripts.d.mts +18 -0
- package/dist/runtime/head-scripts.mjs +159 -0
- package/dist/runtime/hydrating-pathname.d.mts +16 -0
- package/dist/runtime/hydrating-pathname.mjs +26 -0
- package/dist/runtime/mount.d.mts +16 -11
- package/dist/runtime/mount.mjs +29 -18
- package/dist/runtime/payload.d.mts +22 -23
- package/dist/runtime/payload.mjs +11 -16
- package/dist/runtime/prefetch.d.mts +60 -25
- package/dist/runtime/prefetch.mjs +166 -38
- package/dist/runtime/recover.d.mts +2 -0
- package/dist/runtime/recover.mjs +11 -7
- package/dist/runtime/redirect.d.mts +20 -14
- package/dist/runtime/redirect.mjs +42 -15
- package/dist/runtime/request-scope.d.mts +1 -1
- package/dist/runtime/request-scope.mjs +11 -23
- package/dist/runtime/server.d.mts +6 -0
- package/dist/runtime/server.mjs +3 -0
- package/dist/runtime/stylesheets.d.mts +13 -0
- package/dist/runtime/stylesheets.mjs +15 -0
- package/dist/serve.d.mts +1 -0
- package/dist/serve.mjs +5 -11
- package/dist/{static-6z8_6B1U.d.mts → static-DnbgGIoy.d.mts} +2 -1
- package/dist/static-file-BAjwBMMl.mjs +1274 -0
- package/dist/{static-host-C6D_11Gp.mjs → static-host-B-1fAfAw.mjs} +49 -74
- package/dist/vercel.d.mts +1 -2
- package/dist/vercel.mjs +20 -20
- package/dist/vite.d.mts +1 -1
- package/dist/vite.mjs +232 -1469
- package/docs/GUIDE.md +6 -3
- package/docs/llms.txt +8 -4
- package/docs/references/csp.md +11 -9
- package/docs/references/deploy.md +17 -20
- package/docs/references/errors.md +0 -34
- package/docs/references/params.md +5 -5
- package/docs/references/routing.md +104 -20
- package/package.json +6 -6
- package/dist/runtime/redirect-file.d.mts +0 -20
- package/dist/runtime/redirect-file.mjs +0 -42
- package/dist/runtime/tree-pathname.d.mts +0 -2
- package/dist/runtime/tree-pathname.mjs +0 -11
- package/dist/server.d.mts +0 -110
- package/dist/server.mjs +0 -97
|
@@ -0,0 +1,1274 @@
|
|
|
1
|
+
import { normalizePathname } from "@k8ordo/router";
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import path, { posix } from "node:path";
|
|
4
|
+
// ../framework-engine/dist/grammar/tree.mjs
|
|
5
|
+
const CONVENTION = {
|
|
6
|
+
"page.tsx": "page",
|
|
7
|
+
"layout.tsx": "layout",
|
|
8
|
+
"not-found.tsx": "notFound",
|
|
9
|
+
"error.tsx": "error",
|
|
10
|
+
"redirect.ts": "redirect",
|
|
11
|
+
"guard.ts": "guard",
|
|
12
|
+
"route.ts": "route",
|
|
13
|
+
"loading.tsx": "loading",
|
|
14
|
+
"fallback.tsx": "fallback"
|
|
15
|
+
};
|
|
16
|
+
const ROUTE_FILES = Object.keys(CONVENTION).join(", ");
|
|
17
|
+
const PARAM = /^\[([A-Za-z_][A-Za-z0-9_]*)\]$/u;
|
|
18
|
+
const GROUP = /^\(([A-Za-z0-9_-]+)\)$/u;
|
|
19
|
+
const LITERAL = /^[A-Za-z0-9._~-]+$/u;
|
|
20
|
+
/**
|
|
21
|
+
* A dotfile belongs to the system or an editor (`.DS_Store`, a swap file), not
|
|
22
|
+
* to the application, so a stray one must not break the build.
|
|
23
|
+
*/
|
|
24
|
+
const isHidden = (segment) => segment.startsWith(".");
|
|
25
|
+
/**
|
|
26
|
+
* Which slot a file fills, by its path relative to the routes root — `null`
|
|
27
|
+
* for anything the grammar does not read: a hidden file, or a name outside
|
|
28
|
+
* the convention (which the parse reports). One module at a time, for a
|
|
29
|
+
* caller that is handed a module rather than the tree (a dev server's
|
|
30
|
+
* transform).
|
|
31
|
+
*/
|
|
32
|
+
const slotOf = (file) => {
|
|
33
|
+
const segments = file.split("/").filter((segment) => segment !== "");
|
|
34
|
+
if (segments.some((segment) => isHidden(segment))) return null;
|
|
35
|
+
const basename = segments.at(-1);
|
|
36
|
+
if (basename === void 0) return null;
|
|
37
|
+
return CONVENTION[basename] ?? null;
|
|
38
|
+
};
|
|
39
|
+
const emptyDir = () => ({
|
|
40
|
+
files: /* @__PURE__ */ new Map(),
|
|
41
|
+
dirs: /* @__PURE__ */ new Map()
|
|
42
|
+
});
|
|
43
|
+
const build = (files) => {
|
|
44
|
+
const root = emptyDir();
|
|
45
|
+
for (const file of files) {
|
|
46
|
+
const segments = file.split("/").filter((segment) => segment !== "");
|
|
47
|
+
const basename = segments.pop();
|
|
48
|
+
if (basename === void 0 || isHidden(basename)) continue;
|
|
49
|
+
if (segments.some((segment) => isHidden(segment))) continue;
|
|
50
|
+
let current = root;
|
|
51
|
+
for (const segment of segments) {
|
|
52
|
+
let next = current.dirs.get(segment);
|
|
53
|
+
if (next === void 0) {
|
|
54
|
+
next = emptyDir();
|
|
55
|
+
current.dirs.set(segment, next);
|
|
56
|
+
}
|
|
57
|
+
current = next;
|
|
58
|
+
}
|
|
59
|
+
current.files.set(basename, file);
|
|
60
|
+
}
|
|
61
|
+
return root;
|
|
62
|
+
};
|
|
63
|
+
const classify = (name, path, problems) => {
|
|
64
|
+
const param = PARAM.exec(name);
|
|
65
|
+
if (param !== null) return {
|
|
66
|
+
kind: "param",
|
|
67
|
+
key: `/:${param[1]}`,
|
|
68
|
+
param: param[1]
|
|
69
|
+
};
|
|
70
|
+
if (GROUP.exec(name) !== null) return {
|
|
71
|
+
kind: "group",
|
|
72
|
+
key: `/${name}`,
|
|
73
|
+
param: null
|
|
74
|
+
};
|
|
75
|
+
if (name.startsWith("[") || name.endsWith("]")) problems.push({
|
|
76
|
+
path,
|
|
77
|
+
message: `"${name}" is not a valid param directory — use [name] with a letter or underscore first`
|
|
78
|
+
});
|
|
79
|
+
else if (name.startsWith("(") || name.endsWith(")")) problems.push({
|
|
80
|
+
path,
|
|
81
|
+
message: `"${name}" is not a valid route group — use (name)`
|
|
82
|
+
});
|
|
83
|
+
else if (!LITERAL.test(name)) problems.push({
|
|
84
|
+
path,
|
|
85
|
+
message: `"${name}" cannot be a URL segment — use letters, digits, . _ ~ or -`
|
|
86
|
+
});
|
|
87
|
+
return {
|
|
88
|
+
kind: "literal",
|
|
89
|
+
key: `/${name}`,
|
|
90
|
+
param: null
|
|
91
|
+
};
|
|
92
|
+
};
|
|
93
|
+
const convert = (raw, name, path, kind, key, problems) => {
|
|
94
|
+
const slots = {};
|
|
95
|
+
for (const [basename, file] of raw.files) {
|
|
96
|
+
const slot = CONVENTION[basename];
|
|
97
|
+
if (slot === void 0) {
|
|
98
|
+
problems.push({
|
|
99
|
+
path: file,
|
|
100
|
+
message: `routes/ holds only ${ROUTE_FILES} — move "${basename}" out of routes/`
|
|
101
|
+
});
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
slots[slot] = file;
|
|
105
|
+
}
|
|
106
|
+
const here = path === "" ? "/" : path;
|
|
107
|
+
if (slots.page !== void 0 && slots.redirect !== void 0) problems.push({
|
|
108
|
+
path: slots.redirect,
|
|
109
|
+
message: `"${here}" cannot both render page.tsx and redirect — keep one`
|
|
110
|
+
});
|
|
111
|
+
if (slots.route !== void 0 && slots.page !== void 0) problems.push({
|
|
112
|
+
path: slots.route,
|
|
113
|
+
message: `"${here}" cannot both render page.tsx and answer from route.ts — keep one`
|
|
114
|
+
});
|
|
115
|
+
if (slots.route !== void 0 && slots.redirect !== void 0) problems.push({
|
|
116
|
+
path: slots.route,
|
|
117
|
+
message: `"${here}" cannot both redirect and answer from route.ts — keep one`
|
|
118
|
+
});
|
|
119
|
+
const children = [...raw.dirs.entries()].map(([childName, childRaw]) => {
|
|
120
|
+
const childPath = path === "" ? childName : `${path}/${childName}`;
|
|
121
|
+
const classified = classify(childName, childPath, problems);
|
|
122
|
+
return convert(childRaw, childName, childPath, classified.kind, classified.key, problems);
|
|
123
|
+
});
|
|
124
|
+
return {
|
|
125
|
+
name,
|
|
126
|
+
kind,
|
|
127
|
+
key,
|
|
128
|
+
path,
|
|
129
|
+
page: slots.page ?? null,
|
|
130
|
+
layout: slots.layout ?? null,
|
|
131
|
+
notFound: slots.notFound ?? null,
|
|
132
|
+
error: slots.error ?? null,
|
|
133
|
+
loading: slots.loading ?? null,
|
|
134
|
+
redirect: slots.redirect ?? null,
|
|
135
|
+
guard: slots.guard ?? null,
|
|
136
|
+
route: slots.route ?? null,
|
|
137
|
+
fallback: slots.fallback ?? null,
|
|
138
|
+
children
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
const declaresRoute = (dir) => dir.page !== null || dir.route !== null || dir.notFound !== null || dir.redirect !== null || dir.children.some(declaresRoute);
|
|
142
|
+
/**
|
|
143
|
+
* Walks the tree the way the router's own table walk does, so the patterns
|
|
144
|
+
* checked here are the patterns that will exist at runtime.
|
|
145
|
+
*/
|
|
146
|
+
const eachPattern = (dir, prefix, visit) => {
|
|
147
|
+
const here = dir.kind === "root" ? "" : prefix;
|
|
148
|
+
if (dir.page !== null) visit(here === "" ? "/" : here, dir.page);
|
|
149
|
+
if (dir.route !== null && dir.page === null) visit(here === "" ? "/" : here, dir.route);
|
|
150
|
+
if (dir.redirect !== null && dir.page === null && dir.route === null) visit(here === "" ? "/" : here, dir.redirect);
|
|
151
|
+
if (dir.notFound !== null) visit(`${here}/*`, dir.notFound);
|
|
152
|
+
for (const child of dir.children) {
|
|
153
|
+
const next = child.kind === "group" ? here : `${here}${child.key}`;
|
|
154
|
+
eachPattern(child, next, visit);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
const checkFallback = (dir, file, pattern, params, above) => {
|
|
158
|
+
const here = dir.path === "" ? "/" : dir.path;
|
|
159
|
+
const refuse = (message) => ({ problem: {
|
|
160
|
+
path: file,
|
|
161
|
+
message
|
|
162
|
+
} });
|
|
163
|
+
if (dir.page === null) return refuse(`fallback.tsx stands in for the page.tsx beside it, and "${here}" has none`);
|
|
164
|
+
if (dir.layout !== null) return refuse(`fallback.tsx cannot sit beside layout.tsx — that layout receives every parameter of "${here}", so no shell could leave one to the browser; move the layout one directory up, or into page.tsx and fallback.tsx`);
|
|
165
|
+
if (params.length === 0) return refuse(`fallback.tsx stands in for values the build did not write, and "${pattern}" has no parameter; remove it`);
|
|
166
|
+
const open = params.filter((name) => !(above?.params ?? []).includes(name));
|
|
167
|
+
if (open.length === 0 && above !== null) return refuse(`fallback.tsx has nothing to leave to the browser — ${above.file} receives every parameter of "${pattern}"; remove fallback.tsx and list the values in paths`);
|
|
168
|
+
return { shape: {
|
|
169
|
+
pattern,
|
|
170
|
+
file,
|
|
171
|
+
page: dir.page,
|
|
172
|
+
params,
|
|
173
|
+
open,
|
|
174
|
+
layout: above?.file ?? null
|
|
175
|
+
} };
|
|
176
|
+
};
|
|
177
|
+
/**
|
|
178
|
+
* Every `fallback.tsx` the directories hold, as a shape or as the problem
|
|
179
|
+
* that refuses it — one walk, so the grammar, the generated table and the
|
|
180
|
+
* static build never disagree about which params a shell may leave open.
|
|
181
|
+
* A directory that declares no route is skipped with everything below it:
|
|
182
|
+
* that problem is reported on its own.
|
|
183
|
+
*/
|
|
184
|
+
const checkFallbacks = (tree) => {
|
|
185
|
+
const found = [];
|
|
186
|
+
const walk = (dir, prefix, inherited, above) => {
|
|
187
|
+
if (!declaresRoute(dir)) return;
|
|
188
|
+
const here = dir.kind === "root" ? "" : prefix;
|
|
189
|
+
const params = dir.kind === "param" ? [...inherited, dir.key.slice(2)] : inherited;
|
|
190
|
+
if (dir.fallback !== null) found.push(checkFallback(dir, dir.fallback, here === "" ? "/" : here, params, above));
|
|
191
|
+
const below = dir.layout === null ? above : {
|
|
192
|
+
file: dir.layout,
|
|
193
|
+
params
|
|
194
|
+
};
|
|
195
|
+
for (const child of dir.children) walk(child, child.kind === "group" ? here : `${here}${child.key}`, params, below);
|
|
196
|
+
};
|
|
197
|
+
walk(tree, "", [], null);
|
|
198
|
+
return found;
|
|
199
|
+
};
|
|
200
|
+
/**
|
|
201
|
+
* The page patterns with a `fallback.tsx` beside them that the grammar
|
|
202
|
+
* accepts, with the params a shell may leave to the browser — those no layout
|
|
203
|
+
* above the fallback receives.
|
|
204
|
+
*/
|
|
205
|
+
const fallbackShapes = (tree) => checkFallbacks(tree).flatMap((each) => each.shape === void 0 ? [] : [each.shape]);
|
|
206
|
+
const validate = (root, problems) => {
|
|
207
|
+
const walk = (dir, inherited) => {
|
|
208
|
+
let params = inherited;
|
|
209
|
+
if (dir.kind === "param") {
|
|
210
|
+
const name = dir.key.slice(2);
|
|
211
|
+
if (params.includes(name)) problems.push({
|
|
212
|
+
path: dir.path,
|
|
213
|
+
message: `":${name}" is already taken by an ancestor — params must be unique within a path`
|
|
214
|
+
});
|
|
215
|
+
params = [...params, name];
|
|
216
|
+
}
|
|
217
|
+
if (!declaresRoute(dir)) {
|
|
218
|
+
problems.push({
|
|
219
|
+
path: dir.path === "" ? "." : dir.path,
|
|
220
|
+
message: dir.layout === null ? "declares no route — every directory needs a page.tsx (or a redirect.ts or route.ts) somewhere below it" : "has a layout but no page.tsx below it, so it can never render"
|
|
221
|
+
});
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
for (const child of dir.children) walk(child, params);
|
|
225
|
+
};
|
|
226
|
+
walk(root, []);
|
|
227
|
+
for (const each of checkFallbacks(root)) if (each.problem !== void 0) problems.push(each.problem);
|
|
228
|
+
const owners = /* @__PURE__ */ new Map();
|
|
229
|
+
eachPattern(root, "", (pattern, file) => {
|
|
230
|
+
const first = owners.get(pattern);
|
|
231
|
+
if (first === void 0) {
|
|
232
|
+
owners.set(pattern, file);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
problems.push({
|
|
236
|
+
path: file,
|
|
237
|
+
message: `"${pattern}" is already declared by ${first} — route groups do not separate URLs`
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* @param files paths relative to the routes root, POSIX separators.
|
|
243
|
+
*/
|
|
244
|
+
const parseRouteTree = (files) => {
|
|
245
|
+
const problems = [];
|
|
246
|
+
const tree = convert(build(files), "", "", "root", "/", problems);
|
|
247
|
+
validate(tree, problems);
|
|
248
|
+
return {
|
|
249
|
+
tree,
|
|
250
|
+
problems
|
|
251
|
+
};
|
|
252
|
+
};
|
|
253
|
+
// ../framework-engine/dist/runtime/route.mjs
|
|
254
|
+
/** The request methods a `route.ts` answers by exporting a function named so. */
|
|
255
|
+
const ROUTE_METHODS = [
|
|
256
|
+
"GET",
|
|
257
|
+
"HEAD",
|
|
258
|
+
"POST",
|
|
259
|
+
"PUT",
|
|
260
|
+
"PATCH",
|
|
261
|
+
"DELETE",
|
|
262
|
+
"OPTIONS"
|
|
263
|
+
];
|
|
264
|
+
// ../framework-engine/dist/host.mjs
|
|
265
|
+
/**
|
|
266
|
+
* The package the application actually installed. This engine is bundled
|
|
267
|
+
* into it rather than published on its own, so it is the only name
|
|
268
|
+
* resolvable from the project root: anything the optimizer is asked to
|
|
269
|
+
* prebundle is addressed through it, and the generated files name it.
|
|
270
|
+
*/
|
|
271
|
+
const FRAMEWORK = "@k8ordo/framework";
|
|
272
|
+
// ../framework-engine/dist/generate/emit.mjs
|
|
273
|
+
/** What answers a directory's own URL: its page, or its route.ts. */
|
|
274
|
+
const ownFile = (dir) => dir.page ?? dir.route;
|
|
275
|
+
/**
|
|
276
|
+
* What holds a directory's own place in the table. A redirect.ts renders
|
|
277
|
+
* nothing and is not what a guard or a schema answers for, but it matches in
|
|
278
|
+
* declaration order with the pages, literals before params, as they do.
|
|
279
|
+
*/
|
|
280
|
+
const placeOf = (dir) => ownFile(dir) ?? dir.redirect;
|
|
281
|
+
/**
|
|
282
|
+
* A directory with nothing but a page (or a route.ts, or a redirect.ts) is
|
|
283
|
+
* that, itself — except a group: it adds no segment, so the router refuses it
|
|
284
|
+
* as a leaf (it would redeclare its parent's index) and takes it only as a
|
|
285
|
+
* branch.
|
|
286
|
+
*/
|
|
287
|
+
const isLeaf = (dir) => dir.kind !== "group" && placeOf(dir) !== null && dir.layout === null && dir.error === null && dir.loading === null && dir.notFound === null && dir.children.length === 0;
|
|
288
|
+
/**
|
|
289
|
+
* What a subtree offers the matcher first: a literal, a parameter, or only a
|
|
290
|
+
* catch-all. A group contributes its children's URLs rather than one of its
|
|
291
|
+
* own, so it ranks as whatever the best of them is — otherwise a `[slug]`
|
|
292
|
+
* tucked inside a group would still be tried before a literal sibling.
|
|
293
|
+
*/
|
|
294
|
+
const rank = (dir) => {
|
|
295
|
+
if (dir.kind === "param") return 1;
|
|
296
|
+
if (dir.kind !== "group") return 0;
|
|
297
|
+
const children = dir.children.map(rank);
|
|
298
|
+
if (dir.page !== null) children.push(0);
|
|
299
|
+
if (dir.notFound !== null) children.push(2);
|
|
300
|
+
return Math.min(...children, 2);
|
|
301
|
+
};
|
|
302
|
+
/**
|
|
303
|
+
* Literal segments before parameters, and otherwise the order the directories
|
|
304
|
+
* came in. The table matches in declaration order, and the directories arrive
|
|
305
|
+
* sorted by name — under which `[slug]` precedes `about`, because `[` sorts
|
|
306
|
+
* before letters. Left alone, the most ordinary layout there is would make
|
|
307
|
+
* `/about` unreachable behind `/:slug`.
|
|
308
|
+
*
|
|
309
|
+
* A directory tree has no order of its own to honour, so the framework has to
|
|
310
|
+
* choose one; this is the only choice that makes every declared route
|
|
311
|
+
* reachable. Where it still cannot — a group holding both kinds — the
|
|
312
|
+
* unreachable route is reported rather than shipped.
|
|
313
|
+
*/
|
|
314
|
+
const order = (children) => children.toSorted((a, b) => rank(a) - rank(b));
|
|
315
|
+
const buildTable = (tree, resolve) => {
|
|
316
|
+
const entries = (dir) => {
|
|
317
|
+
const record = {};
|
|
318
|
+
const own = placeOf(dir);
|
|
319
|
+
if (own !== null) record["/"] = resolve(own);
|
|
320
|
+
for (const child of order(dir.children)) record[child.key] = node(child);
|
|
321
|
+
if (dir.notFound !== null) record["/*"] = resolve(dir.notFound);
|
|
322
|
+
return record;
|
|
323
|
+
};
|
|
324
|
+
const node = (dir) => {
|
|
325
|
+
if (isLeaf(dir)) return resolve(placeOf(dir));
|
|
326
|
+
const branch = { children: entries(dir) };
|
|
327
|
+
if (dir.layout !== null) branch.layout = resolve(dir.layout);
|
|
328
|
+
if (dir.error !== null) branch.error = resolve(dir.error);
|
|
329
|
+
if (dir.loading !== null) branch.loading = resolve(dir.loading);
|
|
330
|
+
return branch;
|
|
331
|
+
};
|
|
332
|
+
return tree.layout === null && tree.error === null && tree.loading === null ? entries(tree) : { "/": node(tree) };
|
|
333
|
+
};
|
|
334
|
+
/**
|
|
335
|
+
* Every pattern the directories declare, in the order the matcher will try
|
|
336
|
+
* them — the one walk every consumer of "which URLs does this site have"
|
|
337
|
+
* shares, so the build, the shadow check and the prerenderer never disagree
|
|
338
|
+
* about the order.
|
|
339
|
+
*/
|
|
340
|
+
const declaredPatterns = (dir, prefix = "") => {
|
|
341
|
+
const here = dir.kind === "root" ? "" : prefix;
|
|
342
|
+
const own = here === "" ? "/" : here;
|
|
343
|
+
const found = [];
|
|
344
|
+
if (dir.page !== null) found.push({
|
|
345
|
+
pattern: own,
|
|
346
|
+
file: dir.page,
|
|
347
|
+
kind: "page"
|
|
348
|
+
});
|
|
349
|
+
else if (dir.route !== null) found.push({
|
|
350
|
+
pattern: own,
|
|
351
|
+
file: dir.route,
|
|
352
|
+
kind: "route"
|
|
353
|
+
});
|
|
354
|
+
else if (dir.redirect !== null) found.push({
|
|
355
|
+
pattern: own,
|
|
356
|
+
file: dir.redirect,
|
|
357
|
+
kind: "redirect"
|
|
358
|
+
});
|
|
359
|
+
for (const child of order(dir.children)) found.push(...declaredPatterns(child, child.kind === "group" ? here : `${here}${child.key}`));
|
|
360
|
+
if (dir.notFound !== null) found.push({
|
|
361
|
+
pattern: `${here}/*`,
|
|
362
|
+
file: dir.notFound,
|
|
363
|
+
kind: "notFound"
|
|
364
|
+
});
|
|
365
|
+
return found;
|
|
366
|
+
};
|
|
367
|
+
/** Every `redirect.ts`, with the pattern its directory puts it under. */
|
|
368
|
+
const declaredRedirects = (dir) => declaredPatterns(dir).filter((each) => each.kind === "redirect");
|
|
369
|
+
/** Every `route.ts`, with the pattern its directory puts it under. */
|
|
370
|
+
const declaredRouteFiles = (dir) => declaredPatterns(dir).filter((each) => each.kind === "route");
|
|
371
|
+
/**
|
|
372
|
+
* Routes that exist and can never render, because something declared earlier
|
|
373
|
+
* answers their URL. Ordering fixes the common shape — a literal beside a
|
|
374
|
+
* parameter — but a group holds URLs of both kinds under one key, and a table
|
|
375
|
+
* cannot interleave across it. Where the order cannot be made right, saying so
|
|
376
|
+
* is the only honest option left: the alternative is a page that is simply
|
|
377
|
+
* never served, with nothing to see in the directory tree.
|
|
378
|
+
*/
|
|
379
|
+
const unreachableRoutes = (tree) => {
|
|
380
|
+
const all = declaredPatterns(tree);
|
|
381
|
+
const problems = [];
|
|
382
|
+
for (const [index, route] of all.entries()) {
|
|
383
|
+
if (route.pattern.includes(":") || route.pattern.includes("*")) continue;
|
|
384
|
+
const shadow = all.slice(0, index).find((earlier) => earlier.pattern !== route.pattern && new URLPattern({ pathname: earlier.pattern }).test({ pathname: route.pattern }));
|
|
385
|
+
if (shadow === void 0) continue;
|
|
386
|
+
problems.push({
|
|
387
|
+
path: route.file,
|
|
388
|
+
message: `"${route.pattern}" can never match — "${shadow.pattern}" (${shadow.file}) is declared first and answers it`
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
return problems;
|
|
392
|
+
};
|
|
393
|
+
/** What holds a route.ts's or a redirect.ts's place in the table. */
|
|
394
|
+
const ANSWERED = "answered";
|
|
395
|
+
/**
|
|
396
|
+
* What the generated files import from the router, through the framework:
|
|
397
|
+
* the application installs the router, but only ever names the framework.
|
|
398
|
+
*/
|
|
399
|
+
const GENERATED_FROM = `${FRAMEWORK}/generated`;
|
|
400
|
+
const ROUTE_REQUEST_FROM = `${FRAMEWORK}/server`;
|
|
401
|
+
const I18N = "@k8ordo/i18n";
|
|
402
|
+
/** Where an application declares its locale set, from its root. */
|
|
403
|
+
const LOCALES_MODULE = "src/i18n.ts";
|
|
404
|
+
const bannerFrom = (...sources) => `// Generated by ${FRAMEWORK} from ${sources.join(" and ")}. Do not edit.`;
|
|
405
|
+
const sanitize = (path) => {
|
|
406
|
+
const base = path.replace(/\.[jt]sx?$/u, "").replaceAll(/[^A-Za-z0-9]+/gu, "_").replaceAll(/^_+|_+$/gu, "");
|
|
407
|
+
return base === "" ? "route" : base;
|
|
408
|
+
};
|
|
409
|
+
const createNamer = () => {
|
|
410
|
+
const names = /* @__PURE__ */ new Map();
|
|
411
|
+
const used = /* @__PURE__ */ new Set();
|
|
412
|
+
return {
|
|
413
|
+
names,
|
|
414
|
+
take: (file) => {
|
|
415
|
+
const existing = names.get(file);
|
|
416
|
+
if (existing !== void 0) return existing;
|
|
417
|
+
const base = sanitize(file);
|
|
418
|
+
let name = base;
|
|
419
|
+
for (let n = 2; used.has(name); n += 1) name = `${base}_${n}`;
|
|
420
|
+
used.add(name);
|
|
421
|
+
names.set(file, name);
|
|
422
|
+
return name;
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
};
|
|
426
|
+
const pad = (depth) => " ".repeat(depth);
|
|
427
|
+
const isBranch = (node) => typeof node !== "string";
|
|
428
|
+
const renderNode = (node, depth, asserted) => {
|
|
429
|
+
if (!isBranch(node)) return believed(node, asserted);
|
|
430
|
+
const lines = ["{"];
|
|
431
|
+
if (node.layout !== void 0) lines.push(`${pad(depth + 1)}layout: ${believed(node.layout, asserted)},`);
|
|
432
|
+
if (node.error !== void 0) lines.push(`${pad(depth + 1)}error: ${believed(node.error, asserted)},`);
|
|
433
|
+
if (node.loading !== void 0) lines.push(`${pad(depth + 1)}loading: ${believed(node.loading, asserted)},`);
|
|
434
|
+
lines.push(`${pad(depth + 1)}children: {`);
|
|
435
|
+
for (const [key, child] of Object.entries(node.children)) lines.push(`${pad(depth + 2)}'${key}': ${renderNode(child, depth + 2, asserted)},`);
|
|
436
|
+
lines.push(`${pad(depth + 1)}},`, `${pad(depth)}}`);
|
|
437
|
+
return lines.join("\n");
|
|
438
|
+
};
|
|
439
|
+
const believed = (name, asserted) => {
|
|
440
|
+
const type = asserted.get(name);
|
|
441
|
+
return type === void 0 ? name : `${name} satisfies ${type}`;
|
|
442
|
+
};
|
|
443
|
+
/**
|
|
444
|
+
* What each route file is promised, by the pattern the directories put it
|
|
445
|
+
* under: a page's own pattern, and for a layout the prefix every route below
|
|
446
|
+
* it shares. Keyed by file, so the emitter can state the belief where the
|
|
447
|
+
* component is used and let the compiler check the props the file declared —
|
|
448
|
+
* the alternative is asking every route file to restate a pattern its own
|
|
449
|
+
* directory already states.
|
|
450
|
+
*
|
|
451
|
+
* A page's belief also carries the `paramsSchema` exports that run before it
|
|
452
|
+
* renders: every layout's above it that declared one, then its own. A
|
|
453
|
+
* not-found's carries the layouts' above it, which run for what they write to
|
|
454
|
+
* the render's context and never refuse it — a catch-all answers what nothing
|
|
455
|
+
* else did, so its params stay strings. A fallback's carries the layouts'
|
|
456
|
+
* above it too: a shell runs them over the params it fills, and its page's
|
|
457
|
+
* own never, since a shell has no value.
|
|
458
|
+
*/
|
|
459
|
+
const beliefs = (tree, withParams) => {
|
|
460
|
+
const found = /* @__PURE__ */ new Map();
|
|
461
|
+
const walk = (dir, prefix, inherited) => {
|
|
462
|
+
const here = dir.kind === "root" ? "" : prefix;
|
|
463
|
+
const own = here === "" ? "/" : here;
|
|
464
|
+
const layoutSchemas = dir.layout !== null && withParams.has(dir.layout) ? [...inherited, dir.layout] : inherited;
|
|
465
|
+
if (dir.layout !== null) found.set(dir.layout, {
|
|
466
|
+
pattern: own,
|
|
467
|
+
kind: "layout",
|
|
468
|
+
schemas: layoutSchemas
|
|
469
|
+
});
|
|
470
|
+
const answers = ownFile(dir);
|
|
471
|
+
if (answers !== null) found.set(answers, {
|
|
472
|
+
pattern: own,
|
|
473
|
+
kind: dir.page === null ? "route" : "page",
|
|
474
|
+
schemas: withParams.has(answers) ? [...layoutSchemas, answers] : layoutSchemas
|
|
475
|
+
});
|
|
476
|
+
if (dir.notFound !== null) found.set(dir.notFound, {
|
|
477
|
+
pattern: `${here}/*`,
|
|
478
|
+
kind: "notFound",
|
|
479
|
+
schemas: layoutSchemas
|
|
480
|
+
});
|
|
481
|
+
if (dir.error !== null) found.set(dir.error, {
|
|
482
|
+
pattern: own,
|
|
483
|
+
kind: "error",
|
|
484
|
+
schemas: []
|
|
485
|
+
});
|
|
486
|
+
if (dir.loading !== null) found.set(dir.loading, {
|
|
487
|
+
pattern: own,
|
|
488
|
+
kind: "loading",
|
|
489
|
+
schemas: []
|
|
490
|
+
});
|
|
491
|
+
if (dir.fallback !== null) found.set(dir.fallback, {
|
|
492
|
+
pattern: own,
|
|
493
|
+
kind: "fallback",
|
|
494
|
+
schemas: layoutSchemas
|
|
495
|
+
});
|
|
496
|
+
for (const child of dir.children) walk(child, child.kind === "group" ? here : `${here}${child.key}`, layoutSchemas);
|
|
497
|
+
};
|
|
498
|
+
walk(tree, "", []);
|
|
499
|
+
return found;
|
|
500
|
+
};
|
|
501
|
+
const schemaName = (componentName) => `${componentName}_params`;
|
|
502
|
+
/**
|
|
503
|
+
* The guards along each pattern's directories. A redirect is left out: it
|
|
504
|
+
* answers before any guard runs, since the URL it answers has no page to
|
|
505
|
+
* guard (the pages below its directory are guarded as usual). `/*` always
|
|
506
|
+
* carries the root's — a URL nothing answers is
|
|
507
|
+
* still below the root, and the framework's own 404 is answered under them.
|
|
508
|
+
*/
|
|
509
|
+
const guardsOf = (tree) => {
|
|
510
|
+
const stacks = /* @__PURE__ */ new Map();
|
|
511
|
+
const own = /* @__PURE__ */ new Map();
|
|
512
|
+
const walk = (dir, prefix, inherited) => {
|
|
513
|
+
const here = dir.kind === "root" ? "" : prefix;
|
|
514
|
+
const pattern = here === "" ? "/" : here;
|
|
515
|
+
const stack = dir.guard === null ? inherited : [...inherited, dir.guard];
|
|
516
|
+
if (dir.guard !== null) own.set(dir.guard, pattern);
|
|
517
|
+
if (stack.length > 0) {
|
|
518
|
+
if (ownFile(dir) !== null) stacks.set(pattern, stack);
|
|
519
|
+
if (dir.notFound !== null) stacks.set(`${here}/*`, stack);
|
|
520
|
+
}
|
|
521
|
+
for (const child of dir.children) walk(child, child.kind === "group" ? here : `${here}${child.key}`, stack);
|
|
522
|
+
};
|
|
523
|
+
walk(tree, "", []);
|
|
524
|
+
if (tree.guard !== null && !stacks.has("/*")) stacks.set("/*", [tree.guard]);
|
|
525
|
+
return {
|
|
526
|
+
stacks,
|
|
527
|
+
own
|
|
528
|
+
};
|
|
529
|
+
};
|
|
530
|
+
/**
|
|
531
|
+
* The slots a request reaches one file at a time: the page or the not-found
|
|
532
|
+
* that answers it, a route.ts, a page's shell. The table reads each of them
|
|
533
|
+
* when a request reaches it — imported with the table, it would be in the
|
|
534
|
+
* handler's own chunk, and what it renders in the browser and the CSS it
|
|
535
|
+
* imports would be in what every page loads. A layout, an error and a
|
|
536
|
+
* loading are the frame of every page below them, and a guard and a redirect
|
|
537
|
+
* answer before anything renders, so those are imported with the table.
|
|
538
|
+
*/
|
|
539
|
+
const LATE = /* @__PURE__ */ new Set([
|
|
540
|
+
"page",
|
|
541
|
+
"notFound",
|
|
542
|
+
"route",
|
|
543
|
+
"fallback"
|
|
544
|
+
]);
|
|
545
|
+
const isLate = (file) => {
|
|
546
|
+
const slot = slotOf(file);
|
|
547
|
+
return slot !== null && LATE.has(slot);
|
|
548
|
+
};
|
|
549
|
+
const emitRoutesModule = (tree, options) => {
|
|
550
|
+
const namer = createNamer();
|
|
551
|
+
const valueOf = (file) => isLate(file) ? `lazy(${namer.take(file)})` : namer.take(file);
|
|
552
|
+
const table = buildTable(tree, (file) => slotOf(file) === "route" || slotOf(file) === "redirect" ? ANSWERED : valueOf(file));
|
|
553
|
+
const routeFiles = declaredRouteFiles(tree).map((route) => ({
|
|
554
|
+
pattern: route.pattern,
|
|
555
|
+
name: namer.take(route.file)
|
|
556
|
+
}));
|
|
557
|
+
const redirects = declaredRedirects(tree).map((redirect) => ({
|
|
558
|
+
pattern: redirect.pattern,
|
|
559
|
+
name: namer.take(redirect.file)
|
|
560
|
+
}));
|
|
561
|
+
const shells = options.mode === "static" ? fallbackShapes(tree) : [];
|
|
562
|
+
for (const shape of shells) namer.take(shape.file);
|
|
563
|
+
const guarded = guardsOf(tree);
|
|
564
|
+
const guardStacks = new Map([...guarded.stacks].map(([pattern, files]) => [pattern, files.map((file) => namer.take(file))]));
|
|
565
|
+
const guardChecks = [...guarded.own].map(([file, pattern]) => `${pad(1)}Checked<typeof ${namer.take(file)}, Guard<'${pattern}'>>,`);
|
|
566
|
+
const hasGuards = guardChecks.length > 0;
|
|
567
|
+
const withParams = options.withParams ?? /* @__PURE__ */ new Set();
|
|
568
|
+
const withSearch = options.withSearch ?? /* @__PURE__ */ new Set();
|
|
569
|
+
const byFile = beliefs(tree, withParams);
|
|
570
|
+
const asserted = /* @__PURE__ */ new Map();
|
|
571
|
+
const stacks = /* @__PURE__ */ new Map();
|
|
572
|
+
const catchAllStacks = /* @__PURE__ */ new Map();
|
|
573
|
+
const searchReaders = /* @__PURE__ */ new Map();
|
|
574
|
+
for (const [file, name] of namer.names) {
|
|
575
|
+
const belief = byFile.get(file);
|
|
576
|
+
if (belief === void 0) continue;
|
|
577
|
+
const value = valueOf(file);
|
|
578
|
+
const layouts = belief.schemas.filter((schema) => schema !== file).map((schema) => schemaName(namer.take(schema)));
|
|
579
|
+
if (belief.kind === "layout") asserted.set(value, `Layout<'${belief.pattern}'>`);
|
|
580
|
+
else if (belief.kind === "error") asserted.set(value, "ErrorComponent");
|
|
581
|
+
else if (belief.kind === "loading") asserted.set(value, "ComponentType");
|
|
582
|
+
else if (belief.kind === "notFound") {
|
|
583
|
+
asserted.set(value, `Page<'${belief.pattern}'>`);
|
|
584
|
+
if (layouts.length > 0) catchAllStacks.set(belief.pattern, layouts);
|
|
585
|
+
} else if (belief.kind === "page" || belief.kind === "route") {
|
|
586
|
+
const { pattern } = belief;
|
|
587
|
+
if (withParams.has(file)) {
|
|
588
|
+
const module = belief.kind === "page" ? "page" : "route";
|
|
589
|
+
stacks.set(pattern, `(${module}: Loaded<typeof ${name}>) => [${[...layouts, `${module}.paramsSchema`].join(", ")}] as const`);
|
|
590
|
+
} else if (layouts.length > 0) stacks.set(pattern, `() => [${layouts.join(", ")}] as const`);
|
|
591
|
+
if (belief.kind === "route") continue;
|
|
592
|
+
if (withSearch.has(file)) searchReaders.set(pattern, `(page: Loaded<typeof ${name}>) => urlReader(page.search)`);
|
|
593
|
+
const typedBy = stacks.has(pattern) ? `ParamSchemas['${pattern}']` : "[]";
|
|
594
|
+
asserted.set(value, withSearch.has(file) ? `Page<'${pattern}', ${typedBy}, { search: SearchReads['${pattern}'] }>` : stacks.has(pattern) ? `Page<'${pattern}', ${typedBy}>` : `Page<'${pattern}'>`);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
const body = Object.entries(table).map(([key, node]) => `${pad(1)}'${key}': ${renderNode(node, 1, asserted)},`);
|
|
598
|
+
const hasLayout = [...asserted.values()].some((type) => type.startsWith("Layout<"));
|
|
599
|
+
const hasLazy = [...namer.names.keys()].some((file) => slotOf(file) === "page" || slotOf(file) === "notFound");
|
|
600
|
+
const schemaChecks = [...namer.names].filter(([file]) => withParams.has(file)).map(([file, name]) => {
|
|
601
|
+
const belief = byFile.get(file);
|
|
602
|
+
const schema = isLate(file) ? `Loaded<typeof ${name}>['paramsSchema']` : `typeof ${schemaName(name)}`;
|
|
603
|
+
return `${pad(1)}Checked<${schema}, ParamsSchemaFor<'${belief.pattern}'>>,`;
|
|
604
|
+
});
|
|
605
|
+
const routeChecks = routeFiles.map(({ pattern, name }) => stacks.has(pattern) ? `${pad(1)}Checked<Loaded<typeof ${name}>, RouteModule<'${pattern}', ParamSchemas['${pattern}']>>,` : `${pad(1)}Checked<Loaded<typeof ${name}>, RouteModule<'${pattern}'>>,`);
|
|
606
|
+
const fallbackChecks = shells.map(({ file }) => `${pad(1)}Checked<Loaded<typeof ${namer.take(file)}>['default'], ComponentType>,`);
|
|
607
|
+
const hasChecks = schemaChecks.length + routeChecks.length + fallbackChecks.length + guardChecks.length > 0;
|
|
608
|
+
const readsLate = routeFiles.length > 0 || shells.length > 0 || searchReaders.size > 0 || [...namer.names.keys()].some((file) => withParams.has(file) && isLate(file));
|
|
609
|
+
const hasRoutes = routeFiles.length > 0;
|
|
610
|
+
const hasError = [...asserted.values()].includes("ErrorComponent");
|
|
611
|
+
const withRequest = options.mode === "server";
|
|
612
|
+
const requestLine = withRequest ? [" request: RouteRequest;"] : [];
|
|
613
|
+
const specifier = (file) => `'${options.importPrefix}/${file.replace(/\.[jt]sx?$/u, "")}'`;
|
|
614
|
+
const importLines = [...namer.names].filter(([file]) => !isLate(file)).map(([file, name]) => withParams.has(file) ? `import ${name}, { paramsSchema as ${schemaName(name)} } from ${specifier(file)};` : `import ${name} from ${specifier(file)};`);
|
|
615
|
+
const loaderLines = [...namer.names].filter(([file]) => isLate(file)).map(([file, name]) => `const ${name} = () => import(${specifier(file)});`);
|
|
616
|
+
const toMap = (map) => [...map].map(([pattern, schemas]) => `${pad(1)}'${pattern}': [${schemas.join(", ")}],`);
|
|
617
|
+
const toFunctions = (map) => [...map].map(([pattern, made]) => `${pad(1)}'${pattern}': ${made},`);
|
|
618
|
+
const typeImports = [
|
|
619
|
+
...hasError ? ["ErrorComponent"] : [],
|
|
620
|
+
...hasGuards ? ["Guard"] : [],
|
|
621
|
+
...hasLayout ? ["ParamsOf"] : [],
|
|
622
|
+
...schemaChecks.length > 0 ? ["ParamsSchemaFor"] : [],
|
|
623
|
+
"ParsedParams",
|
|
624
|
+
...redirects.length > 0 ? ["RedirectTarget"] : []
|
|
625
|
+
];
|
|
626
|
+
return [
|
|
627
|
+
bannerFrom("routes/"),
|
|
628
|
+
"",
|
|
629
|
+
`import { defineRoutes } from '${GENERATED_FROM}';`,
|
|
630
|
+
...searchReaders.size > 0 ? [`import { urlReader } from '@k8ordo/state';`] : [],
|
|
631
|
+
`import type { ${typeImports.join(", ")} } from '${GENERATED_FROM}';`,
|
|
632
|
+
...hasLazy ? [`import { lazy } from 'react';`] : [],
|
|
633
|
+
`import type { ComponentType${hasLayout ? ", ReactNode" : ""} } from 'react';`,
|
|
634
|
+
"",
|
|
635
|
+
...importLines.length > 0 ? [...importLines, ""] : [],
|
|
636
|
+
...withRequest ? [
|
|
637
|
+
"// What a page may read of the request, under a running server only.",
|
|
638
|
+
`import type { RouteRequest } from '${ROUTE_REQUEST_FROM}';`,
|
|
639
|
+
""
|
|
640
|
+
] : [],
|
|
641
|
+
...loaderLines.length > 0 ? [
|
|
642
|
+
"// The files a request reaches one at a time, read when it does: what",
|
|
643
|
+
"// each renders in the browser, and the CSS it imports, goes only to the",
|
|
644
|
+
"// pages that render it.",
|
|
645
|
+
...loaderLines,
|
|
646
|
+
""
|
|
647
|
+
] : [],
|
|
648
|
+
"// What the renderer passes. `satisfies` below is where a route file's",
|
|
649
|
+
"// own props are checked against the pattern its directory puts it under,",
|
|
650
|
+
"// and where its params take the types the `paramsSchema` exports along",
|
|
651
|
+
"// its stack produce.",
|
|
652
|
+
"type Page<",
|
|
653
|
+
" P extends string,",
|
|
654
|
+
" S extends readonly unknown[] = [],",
|
|
655
|
+
" Q = Record<never, never>,",
|
|
656
|
+
"> = ComponentType<",
|
|
657
|
+
" {",
|
|
658
|
+
" params: ParsedParams<P, S>;",
|
|
659
|
+
" pathname: string;",
|
|
660
|
+
...requestLine.map((line) => ` ${line}`),
|
|
661
|
+
" } & Q",
|
|
662
|
+
">;",
|
|
663
|
+
...hasLayout ? [
|
|
664
|
+
"type Layout<P extends string> = ComponentType<{",
|
|
665
|
+
" params: ParamsOf<P>;",
|
|
666
|
+
" pathname: string;",
|
|
667
|
+
...requestLine,
|
|
668
|
+
" children: ReactNode;",
|
|
669
|
+
"}>;"
|
|
670
|
+
] : [],
|
|
671
|
+
...readsLate ? [
|
|
672
|
+
"",
|
|
673
|
+
"// A file read when a request reaches it, as the module it is read as.",
|
|
674
|
+
"type Loaded<L extends () => Promise<unknown>> = Awaited<ReturnType<L>>;"
|
|
675
|
+
] : [],
|
|
676
|
+
...hasChecks ? [
|
|
677
|
+
"",
|
|
678
|
+
"// `satisfies`, for an export the table holds no value of: compiles only",
|
|
679
|
+
"// when T is assignable to U.",
|
|
680
|
+
"type Checked<T extends U, U> = T;"
|
|
681
|
+
] : [],
|
|
682
|
+
"",
|
|
683
|
+
...schemaChecks.length > 0 ? [
|
|
684
|
+
"// The `paramsSchema` exports the route files declared, each checked against",
|
|
685
|
+
"// the pattern its file sits under.",
|
|
686
|
+
"export type SchemaChecks = [",
|
|
687
|
+
...schemaChecks,
|
|
688
|
+
"];",
|
|
689
|
+
""
|
|
690
|
+
] : [],
|
|
691
|
+
...hasGuards ? [
|
|
692
|
+
"// The guard.ts exports, each checked against the pattern its directory",
|
|
693
|
+
"// puts it under.",
|
|
694
|
+
"export type GuardChecks = [",
|
|
695
|
+
...guardChecks,
|
|
696
|
+
"];",
|
|
697
|
+
""
|
|
698
|
+
] : [],
|
|
699
|
+
"// Per page pattern, the schemas that run before it renders — every",
|
|
700
|
+
"// layout above it that declared one, then its own, read off the file the",
|
|
701
|
+
"// handler read for it. The handler runs them; a schema that refuses makes",
|
|
702
|
+
"// the pattern not answer the pathname.",
|
|
703
|
+
"export const paramSchemas = {",
|
|
704
|
+
...toFunctions(stacks),
|
|
705
|
+
"} as const;",
|
|
706
|
+
"",
|
|
707
|
+
"// The same stacks, as the router types a page's params and links to it.",
|
|
708
|
+
"export type ParamSchemas = {",
|
|
709
|
+
" readonly [P in keyof typeof paramSchemas]: (typeof paramSchemas)[P] extends (...args: never) => infer S ? S : never;",
|
|
710
|
+
"};",
|
|
711
|
+
"",
|
|
712
|
+
"// Per catch-all pattern, the schemas of the layouts above its not-found.",
|
|
713
|
+
"// The handler runs them for what they write to the render (the locale a",
|
|
714
|
+
"// 404 is in); a refusal does not stop a catch-all from answering.",
|
|
715
|
+
"export const catchAllSchemas = {",
|
|
716
|
+
...toMap(catchAllStacks),
|
|
717
|
+
"} as const;",
|
|
718
|
+
"",
|
|
719
|
+
...hasRoutes ? [
|
|
720
|
+
"// What a route.ts exports: a function per request method it answers,",
|
|
721
|
+
"// handed the request and the params, answering with a Response.",
|
|
722
|
+
"type RouteHandler<",
|
|
723
|
+
" P extends string,",
|
|
724
|
+
" S extends readonly unknown[] = [],",
|
|
725
|
+
"> = (context: {",
|
|
726
|
+
" readonly request: Request;",
|
|
727
|
+
" readonly params: ParsedParams<P, S>;",
|
|
728
|
+
"}) => Response | Promise<Response>;",
|
|
729
|
+
"type RouteModule<P extends string, S extends readonly unknown[] = []> = {",
|
|
730
|
+
` readonly [M in ${ROUTE_METHODS.map((method) => `'${method}'`).join(" | ")}]?: RouteHandler<P, S>;`,
|
|
731
|
+
"};",
|
|
732
|
+
"",
|
|
733
|
+
"// The route.ts modules, each checked against the pattern its directory",
|
|
734
|
+
"// puts it under.",
|
|
735
|
+
"export type RouteChecks = [",
|
|
736
|
+
...routeChecks,
|
|
737
|
+
"];",
|
|
738
|
+
""
|
|
739
|
+
] : [],
|
|
740
|
+
...hasRoutes || redirects.length > 0 ? [
|
|
741
|
+
"// A route.ts or a redirect.ts in the table: the handler answers it from",
|
|
742
|
+
"// `routeModules` or `redirects` before anything renders, so its place",
|
|
743
|
+
"// here is only where it matches.",
|
|
744
|
+
`const ${ANSWERED} = (): null => null;`,
|
|
745
|
+
""
|
|
746
|
+
] : [],
|
|
747
|
+
"// Per page pattern that exports `search`, what reads it out of the URL —",
|
|
748
|
+
"// @k8ordo/state's reading of a url schema, made from the page's module.",
|
|
749
|
+
"// The page receives what it read, and a client navigation that changes",
|
|
750
|
+
"// the search loads it again.",
|
|
751
|
+
"export const searchReaders = {",
|
|
752
|
+
...toFunctions(searchReaders),
|
|
753
|
+
"} as const;",
|
|
754
|
+
"",
|
|
755
|
+
"// What each of those pages receives as `search`.",
|
|
756
|
+
"export type SearchReads = {",
|
|
757
|
+
" readonly [P in keyof typeof searchReaders]: (typeof searchReaders)[P] extends (...args: never) => (...args: never) => infer R ? R : never;",
|
|
758
|
+
"};",
|
|
759
|
+
"",
|
|
760
|
+
"// Per pattern, what reads the page or the not-found that answers it. The",
|
|
761
|
+
"// handler renders what it read in the place `lazy()` holds below.",
|
|
762
|
+
"export const pageModules = {",
|
|
763
|
+
...[...namer.names].filter(([file]) => slotOf(file) === "page" || slotOf(file) === "notFound").map(([file, name]) => `${pad(1)}'${byFile.get(file).pattern}': ${name},`),
|
|
764
|
+
"} as const;",
|
|
765
|
+
"",
|
|
766
|
+
"// Per pattern, what reads the route.ts that answers it, by the methods it",
|
|
767
|
+
"// exports.",
|
|
768
|
+
"export const routeModules = {",
|
|
769
|
+
...routeFiles.map(({ pattern, name }) => `${pad(1)}'${pattern}': ${name},`),
|
|
770
|
+
"} as const;",
|
|
771
|
+
"",
|
|
772
|
+
"// Per pattern, the guards that run before it answers — outer first. `/*`",
|
|
773
|
+
"// carries the root's, for a URL nothing answers.",
|
|
774
|
+
"export const guards = {",
|
|
775
|
+
...toMap(guardStacks),
|
|
776
|
+
"} as const;",
|
|
777
|
+
"",
|
|
778
|
+
"// Per pattern, where a redirect.ts sends the visitor, once the table",
|
|
779
|
+
"// matched the pattern: a directory that redirects has no page to render.",
|
|
780
|
+
"export const redirects = {",
|
|
781
|
+
...redirects.map(({ pattern, name }) => `${pad(1)}'${pattern}': ${name} satisfies RedirectTarget,`),
|
|
782
|
+
"} as const;",
|
|
783
|
+
"",
|
|
784
|
+
...options.mode === "static" ? [
|
|
785
|
+
"// Per page pattern with a fallback.tsx: what reads its shell for a value",
|
|
786
|
+
"// the build did not write, the params a shell may leave to the browser, and",
|
|
787
|
+
"// the schemas of the layouts above it, which run over the params it fills.",
|
|
788
|
+
"export const fallbacks = {",
|
|
789
|
+
...shells.flatMap(({ pattern, file, open }) => [
|
|
790
|
+
`${pad(1)}'${pattern}': {`,
|
|
791
|
+
`${pad(2)}load: ${namer.take(file)},`,
|
|
792
|
+
`${pad(2)}open: [${open.map((param) => `'${param}'`).join(", ")}],`,
|
|
793
|
+
`${pad(2)}schemas: [${byFile.get(file).schemas.map((layout) => schemaName(namer.take(layout))).join(", ")}],`,
|
|
794
|
+
`${pad(1)}},`
|
|
795
|
+
]),
|
|
796
|
+
"} as const;",
|
|
797
|
+
...fallbackChecks.length > 0 ? [
|
|
798
|
+
"",
|
|
799
|
+
"// The fallback.tsx files, each checked as a component handed nothing.",
|
|
800
|
+
"export type FallbackChecks = [",
|
|
801
|
+
...fallbackChecks,
|
|
802
|
+
"];"
|
|
803
|
+
] : []
|
|
804
|
+
] : ["// A running server renders every value with its page: no shells.", "export const fallbacks = {} as const;"],
|
|
805
|
+
"",
|
|
806
|
+
"export const routes = defineRoutes({",
|
|
807
|
+
...body,
|
|
808
|
+
"});",
|
|
809
|
+
""
|
|
810
|
+
].join("\n");
|
|
811
|
+
};
|
|
812
|
+
/**
|
|
813
|
+
* Both packages read the app's route table through declaration merging, so
|
|
814
|
+
* the app gets typed paths everywhere without writing the ceremony itself.
|
|
815
|
+
* The router's `Register` is augmented through the framework's re-export of
|
|
816
|
+
* it, which TypeScript merges into the router's own declaration. The locale
|
|
817
|
+
* set reaches `@k8ordo/i18n`'s `Register` the same way, so every message is
|
|
818
|
+
* held to it.
|
|
819
|
+
*/
|
|
820
|
+
const emitRegisterModule = (options) => {
|
|
821
|
+
const wantsState = options.stateModule !== null && options.stateModule !== void 0;
|
|
822
|
+
const localesModule = options.localesModule ?? null;
|
|
823
|
+
const withRequest = options.mode === "server";
|
|
824
|
+
const lines = [
|
|
825
|
+
localesModule === null ? bannerFrom("routes/") : bannerFrom("routes/", LOCALES_MODULE),
|
|
826
|
+
"",
|
|
827
|
+
`import type { ParsedParamsMap } from '${GENERATED_FROM}';`,
|
|
828
|
+
...withRequest ? [`import type { RouteRequest } from '${ROUTE_REQUEST_FROM}';`] : [],
|
|
829
|
+
...localesModule === null ? [] : [`import type { LocaleOf } from '${I18N}';`],
|
|
830
|
+
...wantsState ? [`import type {} from '${options.stateModule}';`] : [],
|
|
831
|
+
...localesModule === null ? [] : [`import type { locales } from '${localesModule}';`],
|
|
832
|
+
`import type { ParamSchemas, routes, SearchReads } from '${options.routesModule}';`,
|
|
833
|
+
"",
|
|
834
|
+
`declare module '${GENERATED_FROM}' {`,
|
|
835
|
+
" interface Register {",
|
|
836
|
+
" routes: typeof routes;",
|
|
837
|
+
" // A link takes a param as the page receives it — typed by its schema.",
|
|
838
|
+
" params: ParsedParamsMap<ParamSchemas>;",
|
|
839
|
+
" // A page that exports `search` receives what it reads.",
|
|
840
|
+
" search: SearchReads;",
|
|
841
|
+
...withRequest ? [" // A route file receives the request: this is a running server.", " request: RouteRequest;"] : [],
|
|
842
|
+
" }",
|
|
843
|
+
"}"
|
|
844
|
+
];
|
|
845
|
+
if (wantsState) lines.push("", `declare module '${options.stateModule}' {`, " interface Register {", " routes: typeof routes;", " }", "}");
|
|
846
|
+
if (localesModule !== null) lines.push("", `declare module '${I18N}' {`, " interface Register {", " locale: LocaleOf<typeof locales>;", " }", "}");
|
|
847
|
+
lines.push("");
|
|
848
|
+
return lines.join("\n");
|
|
849
|
+
};
|
|
850
|
+
// ../framework-engine/dist/runtime/pathname.mjs
|
|
851
|
+
/**
|
|
852
|
+
* A pathname as the URL carries it, decoded for the filesystem — the one
|
|
853
|
+
* thing the static writer and the server's file lookup both have to do
|
|
854
|
+
* before deciding whether the result may name a file. `null` for an escape
|
|
855
|
+
* that cannot be decoded or a NUL byte, neither of which is a name.
|
|
856
|
+
*/
|
|
857
|
+
const decodePathname = (pathname) => {
|
|
858
|
+
let decoded;
|
|
859
|
+
try {
|
|
860
|
+
decoded = decodeURIComponent(pathname);
|
|
861
|
+
} catch {
|
|
862
|
+
return null;
|
|
863
|
+
}
|
|
864
|
+
return decoded.includes("\0") ? null : decoded;
|
|
865
|
+
};
|
|
866
|
+
/**
|
|
867
|
+
* A segment no route declares: a pathname that only a catch-all answers is
|
|
868
|
+
* built with it — the static build's `404.html`, and the handler's search
|
|
869
|
+
* for the not-found nearest a page that said `notFound()`.
|
|
870
|
+
*/
|
|
871
|
+
const NOT_FOUND_SEGMENT = "__k8ordo-not-found__";
|
|
872
|
+
/**
|
|
873
|
+
* The segment a shell is written under, in place of each value it leaves to
|
|
874
|
+
* the browser: `/ja/posts/!fallback`. No route directory can be named it (`!`
|
|
875
|
+
* is outside the grammar's literal segments), and neither
|
|
876
|
+
* `encodeURIComponent` nor the URL parser rewrites `!`, so a host that
|
|
877
|
+
* re-encodes a rewrite target finds the directory under the same spelling.
|
|
878
|
+
*/
|
|
879
|
+
const FALLBACK_SEGMENT = "!fallback";
|
|
880
|
+
// ../framework-engine/dist/runtime/payload.mjs
|
|
881
|
+
/**
|
|
882
|
+
* Said by the handler under mode: 'static' alone, on the not-found a page
|
|
883
|
+
* answered with `notFound()`: the build tells it apart from a param a schema
|
|
884
|
+
* refused, which is a 404 as well.
|
|
885
|
+
*/
|
|
886
|
+
const NOT_FOUND_HEADER = "x-k8ordo-not-found";
|
|
887
|
+
/**
|
|
888
|
+
* Said by the handler under mode: 'static' alone, on a page's HTML: the
|
|
889
|
+
* nonce its inline scripts were signed with, which the build turns into the
|
|
890
|
+
* hashes a `Content-Security-Policy` names. A file cannot carry a nonce —
|
|
891
|
+
* everyone reads the same one.
|
|
892
|
+
*/
|
|
893
|
+
const NONCE_HEADER = "x-k8ordo-nonce";
|
|
894
|
+
/**
|
|
895
|
+
* Said by the handler under mode: 'static' alone, on a shell's HTML and
|
|
896
|
+
* payload: the pattern whose fallback.tsx rendered it. The table walks in its
|
|
897
|
+
* own order, so a shell pathname can be answered by another pattern than the
|
|
898
|
+
* one the build asked for, and the build compares instead of guessing.
|
|
899
|
+
*/
|
|
900
|
+
const SHELL_HEADER = "x-k8ordo-shell";
|
|
901
|
+
/**
|
|
902
|
+
* Said by the handler under mode: 'static' alone, on a page's HTML: every
|
|
903
|
+
* client module the payload it rendered names (`clientDepsHeader`) — what
|
|
904
|
+
* the HTML render was handed to link — which the build lists in
|
|
905
|
+
* `CLIENT_FILES_PATH`.
|
|
906
|
+
*/
|
|
907
|
+
const CLIENT_DEPS_HEADER = "x-k8ordo-client-deps";
|
|
908
|
+
/** What `clientDepsHeader` said. */
|
|
909
|
+
const readClientDeps = (value) => JSON.parse(decodeURIComponent(value));
|
|
910
|
+
/**
|
|
911
|
+
* Where a static build lists the files each page's client components need,
|
|
912
|
+
* at the root of the site under Vite's `base`. A navigation links them as it
|
|
913
|
+
* asks for the payload, instead of once the payload has named them — a
|
|
914
|
+
* round trip sooner.
|
|
915
|
+
*/
|
|
916
|
+
const CLIENT_FILES_PATH = "/client-files.json";
|
|
917
|
+
// src/paths.ts
|
|
918
|
+
/**
|
|
919
|
+
* Every pattern the table declares — pages, redirects and catch-alls — in
|
|
920
|
+
* the order the matcher will try them. The engine's one walk, so the build
|
|
921
|
+
* and the prerenderer agree; a redirect is a URL the site has, so it is a
|
|
922
|
+
* file the site writes.
|
|
923
|
+
*/
|
|
924
|
+
const patternsOf = (dir) => declaredPatterns(dir).map((each) => each.pattern);
|
|
925
|
+
/** A `:name` segment: a parameter a pattern, or a shell location, leaves open. */
|
|
926
|
+
const PARAM_SEGMENT = /^:[A-Za-z_]\w*$/u;
|
|
927
|
+
const isParamSegment = (segment) => PARAM_SEGMENT.test(segment);
|
|
928
|
+
/**
|
|
929
|
+
* A pathname with nothing left to fill: no `:name` segment and no `*`. A `:`
|
|
930
|
+
* inside a segment (`/posts/a:b`) is a value like any other.
|
|
931
|
+
*/
|
|
932
|
+
const isConcrete = (pattern) => !pattern.includes("*") && !pattern.split("/").some((segment) => isParamSegment(segment));
|
|
933
|
+
/**
|
|
934
|
+
* Every catch-all the table declares. A static host answers every URL it does
|
|
935
|
+
* not have from **one** file, so a table with a nested `not-found.tsx` cannot
|
|
936
|
+
* be represented: whichever one the build picked, the other would never be
|
|
937
|
+
* served. The build says so rather than choosing.
|
|
938
|
+
*/
|
|
939
|
+
const catchAllPatterns = (dir) => patternsOf(dir).filter((pattern) => pattern.endsWith("/*"));
|
|
940
|
+
/** A table with more than one catch-all, which no static host can serve. */
|
|
941
|
+
const catchAllRefusals = (dir) => {
|
|
942
|
+
const catchAlls = catchAllPatterns(dir);
|
|
943
|
+
return catchAlls.length > 1 ? [`a static host answers every unknown URL from one file, so only one not-found.tsx can be represented — this table declares ${catchAlls.join(", ")}`] : [];
|
|
944
|
+
};
|
|
945
|
+
/**
|
|
946
|
+
* A pathname the table can only answer with its catch-all, so the build can
|
|
947
|
+
* render `not-found.tsx` without waiting for a visitor to find it.
|
|
948
|
+
*
|
|
949
|
+
* Built from the catch-all's own prefix — its literal segments kept, its
|
|
950
|
+
* parameters filled with a segment no literal uses — and then taken one
|
|
951
|
+
* segment deeper than the longest concrete pattern. Keeping the literals is
|
|
952
|
+
* what reaches a `not-found.tsx` that sits under a named directory; going
|
|
953
|
+
* deeper is what stops any real page from answering first, since parameters
|
|
954
|
+
* consume exactly one segment each. Returns null when there is no catch-all;
|
|
955
|
+
* which one is never in question, because the build refuses a table with more
|
|
956
|
+
* than one.
|
|
957
|
+
*/
|
|
958
|
+
const catchAllPath = (dir) => {
|
|
959
|
+
const [pattern] = catchAllPatterns(dir);
|
|
960
|
+
if (pattern === void 0) return null;
|
|
961
|
+
const prefix = pattern.slice(0, -2).split("/").filter(Boolean).map((segment) => segment.startsWith(":") ? NOT_FOUND_SEGMENT : segment);
|
|
962
|
+
const depth = Math.max(prefix.length + 1, ...patternsOf(dir).filter((each) => !each.endsWith("/*")).map((each) => each.split("/").filter(Boolean).length + 1));
|
|
963
|
+
const filler = Array.from({ length: depth - prefix.length }, () => NOT_FOUND_SEGMENT);
|
|
964
|
+
return `/${[...prefix, ...filler].join("/")}`;
|
|
965
|
+
};
|
|
966
|
+
/**
|
|
967
|
+
* The patterns the build cannot answer on its own. A catch-all is excluded:
|
|
968
|
+
* it is rendered as the not-found file, never as a page of its own.
|
|
969
|
+
*/
|
|
970
|
+
const patternsNeedingPaths = (dir) => patternsOf(dir).filter((pattern) => !isConcrete(pattern) && !pattern.endsWith("/*"));
|
|
971
|
+
/**
|
|
972
|
+
* A shell location's pathname: each segment it leaves to the browser replaced
|
|
973
|
+
* by the reserved one. `/ja/posts/:id` → `/ja/posts/!fallback`.
|
|
974
|
+
*/
|
|
975
|
+
const shellPathname = (location) => location.split("/").map((segment) => isParamSegment(segment) ? FALLBACK_SEGMENT : segment).join("/");
|
|
976
|
+
/** The params a shell location still holds, in order. */
|
|
977
|
+
const unknownOf = (location) => location.split("/").filter((segment) => isParamSegment(segment)).map((segment) => segment.slice(1));
|
|
978
|
+
/**
|
|
979
|
+
* Whether a location is one the pattern answers, segment by segment: a
|
|
980
|
+
* literal needs the same literal; a parameter takes a value, or the same
|
|
981
|
+
* `:name` left open — any `:name`, when names are not compared.
|
|
982
|
+
*/
|
|
983
|
+
const fits = (pattern, location, byName = true) => {
|
|
984
|
+
const wanted = pattern.split("/");
|
|
985
|
+
const given = location.split("/");
|
|
986
|
+
if (wanted.length !== given.length) return false;
|
|
987
|
+
return wanted.every((segment, index) => {
|
|
988
|
+
const at = given[index];
|
|
989
|
+
if (!isParamSegment(segment)) return segment === at;
|
|
990
|
+
return !isParamSegment(at) || !byName || at === segment;
|
|
991
|
+
});
|
|
992
|
+
};
|
|
993
|
+
/**
|
|
994
|
+
* Static rendering cannot invent parameter values, and quietly shipping a
|
|
995
|
+
* site missing half its pages is worse than refusing to build one. Every
|
|
996
|
+
* parameterised pattern must be covered by a supplied path — or, for a page
|
|
997
|
+
* with a fallback.tsx beside it, by its shell, which answers the values the
|
|
998
|
+
* build did not write.
|
|
999
|
+
*
|
|
1000
|
+
* The other direction counts too: a supplied path nothing matched is a typo
|
|
1001
|
+
* that would cost exactly the page it was meant to add, and a supplied value
|
|
1002
|
+
* that still contains a parameter (`/ja/blog/:slug` — what expanding only one
|
|
1003
|
+
* of two parameters leaves behind) would be written to disk as a directory
|
|
1004
|
+
* literally named `:slug` — unless its page has a fallback.tsx, when it is
|
|
1005
|
+
* where that shell stands. URLPattern accepts both, so this has to say no.
|
|
1006
|
+
*
|
|
1007
|
+
* A location goes to the first pattern in table order it fits, which is the
|
|
1008
|
+
* pattern whose URLs a host's rule for it will catch.
|
|
1009
|
+
*/
|
|
1010
|
+
const planPaths = (tree, supplied) => {
|
|
1011
|
+
const patterns = patternsOf(tree);
|
|
1012
|
+
const declared = declaredPatterns(tree).filter((each) => each.kind !== "notFound");
|
|
1013
|
+
const shapes = new Map(fallbackShapes(tree).map((shape) => [shape.pattern, shape]));
|
|
1014
|
+
const paths = patterns.filter((pattern) => isConcrete(pattern));
|
|
1015
|
+
const unresolved = [];
|
|
1016
|
+
const unusable = [];
|
|
1017
|
+
const held = [];
|
|
1018
|
+
const misnamed = [];
|
|
1019
|
+
const closed = [];
|
|
1020
|
+
const reserved = [];
|
|
1021
|
+
const located = /* @__PURE__ */ new Map();
|
|
1022
|
+
const offered = /* @__PURE__ */ new Set();
|
|
1023
|
+
const usable = [];
|
|
1024
|
+
for (const raw of supplied) {
|
|
1025
|
+
const path = normalizePathname(raw);
|
|
1026
|
+
if (path.split("/").some((segment) => decodePathname(segment) === "!fallback")) {
|
|
1027
|
+
reserved.push(path);
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
if (isConcrete(path)) {
|
|
1031
|
+
usable.push(path);
|
|
1032
|
+
continue;
|
|
1033
|
+
}
|
|
1034
|
+
if (path.includes("*")) {
|
|
1035
|
+
unusable.push(path);
|
|
1036
|
+
continue;
|
|
1037
|
+
}
|
|
1038
|
+
const first = declared.find((each) => fits(each.pattern, path));
|
|
1039
|
+
if (first === void 0) {
|
|
1040
|
+
const loosely = declared.find((each) => fits(each.pattern, path, false));
|
|
1041
|
+
if (loosely === void 0) unusable.push(path);
|
|
1042
|
+
else misnamed.push({
|
|
1043
|
+
location: path,
|
|
1044
|
+
pattern: loosely.pattern
|
|
1045
|
+
});
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
const shape = shapes.get(first.pattern);
|
|
1049
|
+
if (shape === void 0) {
|
|
1050
|
+
held.push({
|
|
1051
|
+
location: path,
|
|
1052
|
+
file: first.file
|
|
1053
|
+
});
|
|
1054
|
+
continue;
|
|
1055
|
+
}
|
|
1056
|
+
offered.add(first.pattern);
|
|
1057
|
+
const outside = unknownOf(path).filter((name) => !shape.open.includes(name));
|
|
1058
|
+
if (outside.length > 0) {
|
|
1059
|
+
closed.push({
|
|
1060
|
+
location: path,
|
|
1061
|
+
params: outside,
|
|
1062
|
+
layout: shape.layout ?? "",
|
|
1063
|
+
supplied: true
|
|
1064
|
+
});
|
|
1065
|
+
continue;
|
|
1066
|
+
}
|
|
1067
|
+
located.set(first.pattern, [...located.get(first.pattern) ?? [], {
|
|
1068
|
+
pattern: first.pattern,
|
|
1069
|
+
location: path,
|
|
1070
|
+
pathname: shellPathname(path)
|
|
1071
|
+
}]);
|
|
1072
|
+
}
|
|
1073
|
+
const used = new Set(paths);
|
|
1074
|
+
const shells = [];
|
|
1075
|
+
for (const pattern of patterns) {
|
|
1076
|
+
if (isConcrete(pattern) || pattern.endsWith("/*")) continue;
|
|
1077
|
+
const matcher = new URLPattern({ pathname: pattern });
|
|
1078
|
+
const covered = usable.filter((path) => matcher.test({ pathname: path }));
|
|
1079
|
+
paths.push(...covered);
|
|
1080
|
+
for (const path of covered) used.add(path);
|
|
1081
|
+
const shape = shapes.get(pattern);
|
|
1082
|
+
if (shape === void 0) {
|
|
1083
|
+
if (covered.length === 0) unresolved.push(pattern);
|
|
1084
|
+
continue;
|
|
1085
|
+
}
|
|
1086
|
+
const assigned = located.get(pattern) ?? [];
|
|
1087
|
+
if (assigned.length > 0) {
|
|
1088
|
+
shells.push(...assigned);
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
if (offered.has(pattern)) continue;
|
|
1092
|
+
const left = shape.params.filter((name) => !shape.open.includes(name));
|
|
1093
|
+
if (left.length === 0) shells.push({
|
|
1094
|
+
pattern,
|
|
1095
|
+
location: pattern,
|
|
1096
|
+
pathname: shellPathname(pattern)
|
|
1097
|
+
});
|
|
1098
|
+
else closed.push({
|
|
1099
|
+
location: pattern,
|
|
1100
|
+
params: left,
|
|
1101
|
+
layout: shape.layout ?? "",
|
|
1102
|
+
supplied: false
|
|
1103
|
+
});
|
|
1104
|
+
}
|
|
1105
|
+
unusable.push(...usable.filter((path) => !used.has(path)));
|
|
1106
|
+
return {
|
|
1107
|
+
paths: [...new Set(paths)],
|
|
1108
|
+
shells: shells.filter((shell, index) => shells.findIndex((each) => each.pathname === shell.pathname) === index),
|
|
1109
|
+
unresolved,
|
|
1110
|
+
unusable,
|
|
1111
|
+
held,
|
|
1112
|
+
misnamed,
|
|
1113
|
+
closed,
|
|
1114
|
+
reserved
|
|
1115
|
+
};
|
|
1116
|
+
};
|
|
1117
|
+
/**
|
|
1118
|
+
* Shells whose host rule would answer URLs the table gives a pattern declared
|
|
1119
|
+
* before theirs — a page, route.ts or redirect.ts with a parameter and no
|
|
1120
|
+
* fallback.tsx of its own. A host matches the shell's location alone, so the
|
|
1121
|
+
* table's order does not reach it. Only real conflicts: where both hold a
|
|
1122
|
+
* parameter at one position, infinitely many URLs; where the two meet in one
|
|
1123
|
+
* URL, only when the build did not write it, since the written file answers.
|
|
1124
|
+
*/
|
|
1125
|
+
const shadowedShells = (tree, shells, built) => {
|
|
1126
|
+
const declared = declaredPatterns(tree).filter((each) => each.kind !== "notFound");
|
|
1127
|
+
const shapes = new Map(fallbackShapes(tree).map((shape) => [shape.pattern, shape]));
|
|
1128
|
+
const found = [];
|
|
1129
|
+
for (const shell of shells) {
|
|
1130
|
+
const shape = shapes.get(shell.pattern);
|
|
1131
|
+
if (shape === void 0) continue;
|
|
1132
|
+
const before = declared.slice(0, declared.findIndex((each) => each.pattern === shell.pattern));
|
|
1133
|
+
for (const earlier of before) {
|
|
1134
|
+
if (shapes.has(earlier.pattern) || isConcrete(earlier.pattern)) continue;
|
|
1135
|
+
const url = overlapOf(shell.location, earlier);
|
|
1136
|
+
if (url === void 0) continue;
|
|
1137
|
+
if (url !== null && built.has(url)) continue;
|
|
1138
|
+
found.push({
|
|
1139
|
+
location: shell.location,
|
|
1140
|
+
fallback: shape.file,
|
|
1141
|
+
pattern: earlier.pattern,
|
|
1142
|
+
file: earlier.file,
|
|
1143
|
+
url
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
return found;
|
|
1148
|
+
};
|
|
1149
|
+
/**
|
|
1150
|
+
* Where a location and a pattern meet: `undefined` when they never do, `null`
|
|
1151
|
+
* when a parameter on both sides at one position makes it infinitely many
|
|
1152
|
+
* URLs, and otherwise the one URL, each position fixed by one side.
|
|
1153
|
+
*/
|
|
1154
|
+
const overlapOf = (location, earlier) => {
|
|
1155
|
+
const mine = location.split("/");
|
|
1156
|
+
const theirs = earlier.pattern.split("/");
|
|
1157
|
+
if (mine.length !== theirs.length) return void 0;
|
|
1158
|
+
const url = [];
|
|
1159
|
+
for (const [index, segment] of mine.entries()) {
|
|
1160
|
+
const other = theirs[index];
|
|
1161
|
+
const open = isParamSegment(segment);
|
|
1162
|
+
const otherOpen = isParamSegment(other);
|
|
1163
|
+
if (open && otherOpen) return null;
|
|
1164
|
+
if (!open && !otherOpen && segment !== other) return void 0;
|
|
1165
|
+
url.push(open ? other : segment);
|
|
1166
|
+
}
|
|
1167
|
+
return url.join("/");
|
|
1168
|
+
};
|
|
1169
|
+
/** How a pathname is named in a message: its file, as a person finds it. */
|
|
1170
|
+
const isPage = (file) => file === "page.tsx" || file.endsWith("/page.tsx");
|
|
1171
|
+
const paramList = (params) => params.map((name) => `:${name}`).join(", ");
|
|
1172
|
+
/**
|
|
1173
|
+
* What the build refuses in a plan, each kind its own message, so fixing one
|
|
1174
|
+
* is not what reveals the next. `vite dev` logs the same words as a warning.
|
|
1175
|
+
*/
|
|
1176
|
+
const planRefusals = (plan, shadowed) => {
|
|
1177
|
+
const bare = plan.closed.filter((each) => !each.supplied);
|
|
1178
|
+
const suppliedClosed = plan.closed.filter((each) => each.supplied);
|
|
1179
|
+
return [
|
|
1180
|
+
...plan.unresolved.length > 0 ? [`static build needs pathnames for ${plan.unresolved.join(", ")} — supply them with the "paths" option`] : [],
|
|
1181
|
+
...plan.unusable.length > 0 ? [`the "paths" option supplied pathnames no route wants: ${plan.unusable.join(", ")}`] : [],
|
|
1182
|
+
...plan.held.length > 0 ? [`the "paths" option supplied pathnames that still hold a parameter, and only a page with a fallback.tsx beside it takes one: ${plan.held.map(({ location, file }) => `${location} (${file} ${isPage(file) ? "has none" : "cannot have one"})`).join(", ")}`] : [],
|
|
1183
|
+
...plan.misnamed.length > 0 ? [`the "paths" option supplied shell locations whose parameter names are not their pattern's: ${plan.misnamed.map(({ location, pattern }) => `${location} (${pattern})`).join(", ")}`] : [],
|
|
1184
|
+
...suppliedClosed.length > 0 ? [`the "paths" option supplied shell locations that leave out a parameter a layout above their fallback.tsx receives: ${suppliedClosed.map(({ location, params, layout }) => `${location} (${paramList(params)}, received by ${layout})`).join(", ")}`] : [],
|
|
1185
|
+
...bare.length > 0 ? [bare.map(({ location, params, layout }) => `static build needs shell locations for ${location} — ${layout} receives ${paramList(params)}, so the "paths" option has to fill ${params.length === 1 ? "it" : "them"}, as in ${location.split("/").map((segment) => params.some((name) => segment === `:${name}`) ? `<${segment.slice(1)}>` : segment).join("/")}`).join("\n")] : [],
|
|
1186
|
+
...plan.reserved.length > 0 ? [`the "paths" option supplied pathnames with a segment named ${FALLBACK_SEGMENT}, which the build keeps for shells: ${plan.reserved.join(", ")}`] : [],
|
|
1187
|
+
...shadowed.length > 0 ? [shadowed.map(({ location, fallback, pattern, file, url }) => url === null ? `the shell for ${location} (${fallback}) would also answer URLs ${pattern} (${file}) is declared first for — ${isPage(file) ? `give ${file} a fallback.tsx too, or supply` : "supply"} shell locations it cannot match` : `the shell for ${location} (${fallback}) would also answer ${url}, which ${file} is declared first for and the build did not write — list ${url} in "paths", or supply shell locations it cannot match`).join("\n")] : []
|
|
1188
|
+
];
|
|
1189
|
+
};
|
|
1190
|
+
/**
|
|
1191
|
+
* The directory a rendered pathname is written to. A supplied path is
|
|
1192
|
+
* URL-escaped — `/products/caf%C3%A9` — so writing it verbatim would
|
|
1193
|
+
* make a directory literally named with the escapes, which no host would then
|
|
1194
|
+
* match. Decoding is also the moment a path that leaves the output directory
|
|
1195
|
+
* has to be refused: `..` is a real URL segment and would otherwise be
|
|
1196
|
+
* resolved by `path.join`.
|
|
1197
|
+
*/
|
|
1198
|
+
const dirFor = (pathname) => {
|
|
1199
|
+
const decoded = decodePathname(pathname);
|
|
1200
|
+
if (decoded === null) throw new Error(`the "paths" option supplied a pathname with a malformed escape: ${pathname}`);
|
|
1201
|
+
if (decoded.split("/").some((segment) => segment === "..")) throw new Error(`the "paths" option supplied a pathname that leaves the output: ${pathname}`);
|
|
1202
|
+
return decoded;
|
|
1203
|
+
};
|
|
1204
|
+
/** Where a pathname's file lands inside the client build, `/`-separated. */
|
|
1205
|
+
const fileAt = (pathname, name = "") => posix.join(dirFor(pathname), name).slice(1);
|
|
1206
|
+
/**
|
|
1207
|
+
* What answers each pathname the build writes: the first declared pattern
|
|
1208
|
+
* that matches it, in the matcher's order. The catch-all never answers a
|
|
1209
|
+
* pathname the build was given.
|
|
1210
|
+
*/
|
|
1211
|
+
const answersOf = (dir, pathnames) => {
|
|
1212
|
+
const declared = declaredPatterns(dir).filter((each) => each.kind !== "notFound");
|
|
1213
|
+
return new Map(pathnames.flatMap((pathname) => {
|
|
1214
|
+
const answer = declared.find((each) => new URLPattern({ pathname: each.pattern }).test({ pathname }));
|
|
1215
|
+
return answer === void 0 ? [] : [[pathname, answer]];
|
|
1216
|
+
}));
|
|
1217
|
+
};
|
|
1218
|
+
/**
|
|
1219
|
+
* Each route.ts the build cannot write as the file its GET answers, in one
|
|
1220
|
+
* message: at `/`, below which every file goes; where something else is
|
|
1221
|
+
* written below it; or where the build writes a file of its own, after the
|
|
1222
|
+
* routes' files — a page's beside them — so one would replace the other
|
|
1223
|
+
* without a word.
|
|
1224
|
+
*/
|
|
1225
|
+
const routeFileRefusals = (tree, plan, answers, { site, named }) => {
|
|
1226
|
+
const written = /* @__PURE__ */ new Map();
|
|
1227
|
+
for (const [pathname, answer] of answers) {
|
|
1228
|
+
if (answer.kind === "route") continue;
|
|
1229
|
+
const by = `${named(answer.file)} is written there`;
|
|
1230
|
+
written.set(fileAt(pathname, "index.html"), by);
|
|
1231
|
+
if (answer.kind === "page") written.set(fileAt(pathname, "index.rsc"), by);
|
|
1232
|
+
}
|
|
1233
|
+
const notFound = declaredPatterns(tree).find((each) => each.kind === "notFound");
|
|
1234
|
+
if (notFound !== void 0) written.set("404.html", `${named(notFound.file)} is written there`);
|
|
1235
|
+
if (site) written.set("sitemap.xml", "the \"site\" option writes it");
|
|
1236
|
+
written.set(CLIENT_FILES_PATH.slice(1), "the build lists there what each page’s client components need");
|
|
1237
|
+
if (plan.shells.length > 0) {
|
|
1238
|
+
const fallbacks = fallbackShapes(tree).filter((shape) => plan.shells.some((shell) => shell.pattern === shape.pattern)).map((shape) => named(shape.file));
|
|
1239
|
+
written.set("_redirects", `the shells of ${fallbacks.join(", ")} are reached through it — rules of your own go in public/_redirects, which the build adds to its own`);
|
|
1240
|
+
}
|
|
1241
|
+
const directories = [...plan.paths, ...plan.shells.map((shell) => shell.pathname)];
|
|
1242
|
+
const lines = [...answers].flatMap(([pathname, answer]) => {
|
|
1243
|
+
if (answer.kind !== "route") return [];
|
|
1244
|
+
const route = named(answer.file);
|
|
1245
|
+
if (pathname === "/") return [`/: ${route}, and a static host serves / from index.html`];
|
|
1246
|
+
const file = fileAt(pathname);
|
|
1247
|
+
const by = written.get(file);
|
|
1248
|
+
if (by !== void 0) return [`${file}: ${route}, and ${by}`];
|
|
1249
|
+
const below = directories.find((each) => each.startsWith(`${pathname}/`));
|
|
1250
|
+
return below === void 0 ? [] : [`${file}: ${route}, and ${below} is written below it`];
|
|
1251
|
+
}).toSorted();
|
|
1252
|
+
return lines.length === 0 ? [] : [`static build writes a route.ts as the file its GET answers, and these cannot be written — remove the route.ts, or what else is written there:\n${lines.map((line) => ` ${line}`).join("\n")}`];
|
|
1253
|
+
};
|
|
1254
|
+
// src/static-file.ts
|
|
1255
|
+
/**
|
|
1256
|
+
* Where a request pathname is allowed to land inside the build output.
|
|
1257
|
+
* Traversal is not a case to weigh at request time: a URL may only ever name
|
|
1258
|
+
* a file under the client build, and anything else resolves to nothing.
|
|
1259
|
+
*/
|
|
1260
|
+
const safeJoin = (root, pathname) => {
|
|
1261
|
+
const decoded = decodePathname(pathname);
|
|
1262
|
+
if (decoded === null) return null;
|
|
1263
|
+
const resolved = path.resolve(root, `.${path.posix.normalize(decoded)}`);
|
|
1264
|
+
if (resolved !== root && !resolved.startsWith(root + path.sep)) return null;
|
|
1265
|
+
return resolved;
|
|
1266
|
+
};
|
|
1267
|
+
const isFile = async (candidate) => {
|
|
1268
|
+
try {
|
|
1269
|
+
return (await stat(candidate)).isFile();
|
|
1270
|
+
} catch {
|
|
1271
|
+
return false;
|
|
1272
|
+
}
|
|
1273
|
+
};
|
|
1274
|
+
export { slotOf as A, emitRegisterModule as C, ROUTE_METHODS as D, FRAMEWORK as E, fallbackShapes as O, LOCALES_MODULE as S, unreachableRoutes as T, NOT_FOUND_HEADER as _, catchAllRefusals as a, FALLBACK_SEGMENT as b, isParamSegment as c, planRefusals as d, routeFileRefusals as f, NONCE_HEADER as g, CLIENT_FILES_PATH as h, catchAllPath as i, parseRouteTree as k, patternsNeedingPaths as l, CLIENT_DEPS_HEADER as m, safeJoin as n, dirFor as o, shadowedShells as p, answersOf as r, fileAt as s, isFile as t, planPaths as u, SHELL_HEADER as v, emitRoutesModule as w, decodePathname as x, readClientDeps as y };
|