@k8ordo/framework 2.0.0 → 3.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.
@@ -25,18 +25,38 @@ export declare const prefetchTargetOf: (target: EventTarget | null) => URL | nul
25
25
  * returns what stops it.
26
26
  */
27
27
  export declare const prefetchOnIntent: (prefetch: (url: URL) => Promise<unknown>) => (() => void);
28
+ /**
29
+ * How long a link stays on screen before it is fetched ahead, in
30
+ * milliseconds. A link scrolled past is not one the visitor stopped at, and a
31
+ * link that just came into view may not be the one they tap.
32
+ */
33
+ export declare const IN_VIEW_DWELL = 1000;
34
+ /** What watches the links on screen. */
35
+ export type InView = {
36
+ /** Stops watching: nothing more is fetched. */
37
+ readonly stop: () => void;
38
+ /**
39
+ * Says where a page change is loading — a pathname in the table's terms,
40
+ * as `usePendingPathname` names it — or that none is (`null`). While one
41
+ * loads nothing more is fetched, and a prefetch on its way to another page
42
+ * is called off, its link put first in line again.
43
+ */
44
+ readonly pending: (pathname: string | null) => void;
45
+ };
28
46
  /**
29
47
  * Prefetches the links on screen (`prefetchInView`) while the primary pointer
30
- * is coarse, and returns what stops it.
48
+ * is coarse.
31
49
  */
32
- export declare const prefetchInViewUnderTouch: (prefetch: (url: URL) => Promise<unknown>) => (() => void);
50
+ export declare const prefetchInViewUnderTouch: (prefetch: (url: URL, signal: AbortSignal) => Promise<unknown>) => InView;
33
51
  /**
34
52
  * Prefetches the links on screen, one at a time, in the order they came into
35
- * view, and returns what stops it. A link that leaves before its turn is
36
- * passed over, so a fast scroll fetches little; one at a time, so a page
37
- * visited while they load shares the connection with one prefetch at most.
53
+ * view, once each has stayed there `IN_VIEW_DWELL` and the document has
54
+ * loaded. A link that leaves before its turn is passed over, so a fast
55
+ * scroll fetches little; one at a time, so a page visited while they load
56
+ * shares the connection with one prefetch at most, and with none once the
57
+ * page change is known (`pending`).
38
58
  */
39
- export declare const prefetchInView: (prefetch: (url: URL) => Promise<unknown>) => (() => void);
59
+ export declare const prefetchInView: (prefetch: (url: URL, signal: AbortSignal) => Promise<unknown>) => InView;
40
60
  /**
41
61
  * Where a page's load is handed to navigations from. Two kinds, by what a
42
62
  * page's payload is:
@@ -58,9 +78,10 @@ export declare const prefetchInView: (prefetch: (url: URL) => Promise<unknown>)
58
78
  export type PageCache<T> = {
59
79
  /**
60
80
  * Starts loading `key` unless a usable load of it is held, and returns the
61
- * held load.
81
+ * held load. `signal` aborting forgets a load this call started, while it
82
+ * is on its way and no navigation waits for it.
62
83
  */
63
- readonly prefetch: (key: string, priority: RequestPriority) => Promise<T>;
84
+ readonly prefetch: (key: string, priority: RequestPriority, signal?: AbortSignal) => Promise<T>;
64
85
  /**
65
86
  * What a navigation to `key` renders: a usable load held, or one started
66
87
  * for it. While it is on its way, `signal` aborting aborts it, as it would
@@ -64,55 +64,100 @@ const prefetchOnIntent = (prefetch) => {
64
64
  };
65
65
  };
66
66
  /**
67
+ * How long a link stays on screen before it is fetched ahead, in
68
+ * milliseconds. A link scrolled past is not one the visitor stopped at, and a
69
+ * link that just came into view may not be the one they tap.
70
+ */
71
+ const IN_VIEW_DWELL = 1e3;
72
+ /**
67
73
  * Prefetches the links on screen (`prefetchInView`) while the primary pointer
68
- * is coarse, and returns what stops it.
74
+ * is coarse.
69
75
  */
70
76
  const prefetchInViewUnderTouch = (prefetch) => {
71
77
  const coarse = matchMedia("(pointer: coarse)");
72
- let stop;
78
+ let inView;
79
+ let pending = null;
73
80
  const follow = () => {
74
- stop?.();
75
- stop = coarse.matches ? prefetchInView(prefetch) : void 0;
81
+ inView?.stop();
82
+ inView = coarse.matches ? prefetchInView(prefetch) : void 0;
83
+ inView?.pending(pending);
76
84
  };
77
85
  follow();
78
86
  coarse.addEventListener("change", follow);
79
- return () => {
80
- coarse.removeEventListener("change", follow);
81
- stop?.();
87
+ return {
88
+ stop: () => {
89
+ coarse.removeEventListener("change", follow);
90
+ inView?.stop();
91
+ },
92
+ pending: (pathname) => {
93
+ pending = pathname;
94
+ inView?.pending(pathname);
95
+ }
82
96
  };
83
97
  };
98
+ /** Resolves once the document has loaded, at once if it has. */
99
+ const documentLoaded = () => new Promise((resolve) => {
100
+ if (document.readyState === "complete") resolve();
101
+ else addEventListener("load", () => resolve(), { once: true });
102
+ });
84
103
  /**
85
104
  * Prefetches the links on screen, one at a time, in the order they came into
86
- * view, and returns what stops it. A link that leaves before its turn is
87
- * passed over, so a fast scroll fetches little; one at a time, so a page
88
- * visited while they load shares the connection with one prefetch at most.
105
+ * view, once each has stayed there `IN_VIEW_DWELL` and the document has
106
+ * loaded. A link that leaves before its turn is passed over, so a fast
107
+ * scroll fetches little; one at a time, so a page visited while they load
108
+ * shares the connection with one prefetch at most, and with none once the
109
+ * page change is known (`pending`).
89
110
  */
90
111
  const prefetchInView = (prefetch) => {
112
+ const onScreen = /* @__PURE__ */ new Map();
91
113
  const waiting = /* @__PURE__ */ new Set();
114
+ const loaded = documentLoaded();
115
+ let fetching;
116
+ let pending = null;
92
117
  let draining = false;
93
118
  let stopped = false;
94
119
  const drain = async () => {
95
120
  if (draining) return;
96
121
  draining = true;
122
+ await loaded;
97
123
  for (const link of waiting) {
124
+ if (stopped || pending !== null) break;
98
125
  waiting.delete(link);
99
126
  const url = prefetchTargetOf(link);
100
- if (url !== null) await prefetch(url).catch(() => void 0);
101
- if (stopped) break;
127
+ if (url === null) continue;
128
+ const controller = new AbortController();
129
+ fetching = {
130
+ link,
131
+ url,
132
+ controller
133
+ };
134
+ await prefetch(url, controller.signal).catch(() => void 0);
135
+ fetching = void 0;
102
136
  }
103
137
  draining = false;
104
138
  };
139
+ const leave = (link) => {
140
+ clearTimeout(onScreen.get(link));
141
+ onScreen.delete(link);
142
+ waiting.delete(link);
143
+ };
105
144
  const view = new IntersectionObserver((entries) => {
106
- for (const { isIntersecting, target } of entries) if (isIntersecting) waiting.add(target);
107
- else waiting.delete(target);
108
- drain();
145
+ for (const { isIntersecting, target } of entries) if (!isIntersecting) leave(target);
146
+ else if (!onScreen.has(target)) {
147
+ const stayed = setTimeout(() => {
148
+ onScreen.set(target, void 0);
149
+ waiting.add(target);
150
+ drain();
151
+ }, IN_VIEW_DWELL);
152
+ onScreen.set(target, stayed);
153
+ }
109
154
  });
110
155
  const linksIn = (node) => node instanceof Element ? [...node.matches("a[href]") ? [node] : [], ...node.querySelectorAll("a[href]")] : [];
111
156
  const tree = new MutationObserver((records) => {
112
157
  for (const { addedNodes, removedNodes } of records) {
113
158
  for (const node of removedNodes) for (const link of linksIn(node)) {
114
159
  view.unobserve(link);
115
- waiting.delete(link);
160
+ leave(link);
116
161
  }
117
162
  for (const node of addedNodes) for (const link of linksIn(node)) view.observe(link);
118
163
  }
@@ -122,11 +167,29 @@ const prefetchInView = (prefetch) => {
122
167
  subtree: true
123
168
  });
124
169
  for (const link of document.querySelectorAll("a[href]")) view.observe(link);
125
- return () => {
126
- stopped = true;
127
- tree.disconnect();
128
- view.disconnect();
129
- waiting.clear();
170
+ return {
171
+ stop: () => {
172
+ stopped = true;
173
+ tree.disconnect();
174
+ view.disconnect();
175
+ for (const link of onScreen.keys()) leave(link);
176
+ },
177
+ pending: (pathname) => {
178
+ pending = pathname;
179
+ if (pathname === null) {
180
+ drain();
181
+ return;
182
+ }
183
+ if (fetching === void 0) return;
184
+ const { pathname: fetched } = fetching.url;
185
+ if (normalizePathname(withoutBase(fetched) ?? fetched) === pathname) return;
186
+ if (onScreen.has(fetching.link)) {
187
+ const behind = [...waiting];
188
+ waiting.clear();
189
+ for (const link of [fetching.link, ...behind]) waiting.add(link);
190
+ }
191
+ fetching.controller.abort();
192
+ }
130
193
  };
131
194
  };
132
195
  const createPageCache = (load, { files }, now = () => performance.now()) => {
@@ -171,9 +234,17 @@ const createPageCache = (load, { files }, now = () => performance.now()) => {
171
234
  for (const [key, entry] of entries) if (!usable(entry)) forget(key, entry);
172
235
  };
173
236
  return {
174
- prefetch: (key, priority) => {
237
+ prefetch: (key, priority, signal) => {
175
238
  sweep();
176
- const entry = held(key) ?? start(key, priority);
239
+ let entry = held(key);
240
+ if (entry === void 0) {
241
+ const started = start(key, priority);
242
+ signal?.addEventListener("abort", () => {
243
+ if (started.settled || started.waiting > 0) return;
244
+ if (entries.get(key) === started) forget(key, started);
245
+ }, { once: true });
246
+ entry = started;
247
+ }
177
248
  hold(key, entry);
178
249
  return entry.value;
179
250
  },
@@ -212,4 +283,4 @@ const createPageCache = (load, { files }, now = () => performance.now()) => {
212
283
  }
213
284
  };
214
285
  };
215
- export { KEPT_PAGES, PREFETCH_LIFETIME, createPageCache, prefetchInView, prefetchInViewUnderTouch, prefetchOnIntent, prefetchTargetOf };
286
+ export { IN_VIEW_DWELL, KEPT_PAGES, PREFETCH_LIFETIME, createPageCache, prefetchInView, prefetchInViewUnderTouch, prefetchOnIntent, prefetchTargetOf };
package/dist/serve.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { n as safeJoin, t as isFile } from "./static-file-BAjwBMMl.mjs";
2
- import { f as ENCODINGS, g as streamingCompressor, h as negotiateEncoding, m as isCompressible, n as resolveStatic, p as SUFFIX, t as readRules } from "./static-host-B-1fAfAw.mjs";
1
+ import { n as safeJoin, t as isFile } from "./static-file-BEk_xO5y.mjs";
2
+ import { f as ENCODINGS, g as streamingCompressor, h as negotiateEncoding, m as isCompressible, n as resolveStatic, p as SUFFIX, t as readRules } from "./static-host-CyAmsL_7.mjs";
3
3
  import { withoutBase } from "@k8ordo/router";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { stat } from "node:fs/promises";
@@ -138,7 +138,8 @@ const sendAnswer = async (incoming, response, result) => {
138
138
  const serve = async (options = {}) => {
139
139
  const dist = path.resolve(process.cwd(), options.dist ?? "dist");
140
140
  const clientDir = path.join(dist, "client");
141
- const { default: handler, base, mode } = await import(pathToFileURL(path.join(dist, "rsc", "index.js")).href);
141
+ const { default: handler, base, mode, headers: declared } = await import(pathToFileURL(path.join(dist, "rsc", "index.js")).href);
142
+ const everywhere = Object.entries(declared);
142
143
  const rules = mode === "static" ? await readRules(clientDir) : null;
143
144
  const etags = /* @__PURE__ */ new Map();
144
145
  const etagOf = (file, { size, mtimeMs }) => {
@@ -225,6 +226,7 @@ const serve = async (options = {}) => {
225
226
  await sendFile(incoming, response, answer.file, answer.status);
226
227
  };
227
228
  const server = createServer((incoming, response) => {
229
+ for (const [name, value] of everywhere) response.setHeader(name, value);
228
230
  (async () => {
229
231
  const url = urlOf(incoming);
230
232
  if (url === null) {
@@ -10,6 +10,15 @@ type EngineOptions = {
10
10
  * `oxc-transform-react` installed. Server components are left as they are.
11
11
  */
12
12
  readonly reactCompiler?: boolean;
13
+ /**
14
+ * Headers every response carries, whatever answered — a page, a file of
15
+ * the build, a `404`, a redirect. Sent by `vite dev`, `vite preview` and
16
+ * `serve`, added by the request handler to its own answers under
17
+ * `mode: 'server'`, and written for the hosts that read them from the
18
+ * build. A header the answer already has under the same name — one a
19
+ * `guard.ts` or a `route.ts` set — is left as it is.
20
+ */
21
+ readonly headers?: Readonly<Record<string, string>>;
13
22
  };
14
23
  /**
15
24
  * The `Content-Security-Policy` an application wants on every page, as
@@ -24,27 +33,12 @@ type StaticOptions = EngineOptions & {
24
33
  * request API) builds.
25
34
  */
26
35
  readonly mode: 'static';
27
- /**
28
- * Pathnames for routes with parameters, in the table's terms — without
29
- * Vite's `base`. Static rendering cannot invent them, and a build that
30
- * quietly skipped half the site would be worse than one that refuses.
31
- *
32
- * The patterns that need covering are handed in, so a site whose parameter
33
- * takes the same values everywhere — a locale segment, say — expands them
34
- * rather than listing every page twice.
35
- *
36
- * For a page with a `fallback.tsx` beside it, a pathname that still holds
37
- * a parameter (`/ja/posts/:id`) is where its shell stands: the values the
38
- * build did not write are answered there. Without one, the bare pattern
39
- * is the shell's location.
40
- */
41
- readonly paths?: (patterns: readonly string[]) => readonly string[] | Promise<readonly string[]>;
42
36
  /**
43
37
  * The origin the site is served from — `https://example.com`. With it the
44
38
  * build also writes `sitemap.xml`, listing every page it rendered at its
45
39
  * URL, Vite's `base` included; without it, no sitemap, because a sitemap of
46
- * relative URLs is not one. A `route.ts` that writes `sitemap.xml` as well
47
- * stops the build, naming both: keep one of them.
40
+ * relative URLs is not one. A `route.ts` that writes `sitemap.xml` is the
41
+ * application's own list, and the build leaves the file to it.
48
42
  */
49
43
  readonly site?: string;
50
44
  /**
@@ -11,7 +11,8 @@ const CONVENTION = {
11
11
  "guard.ts": "guard",
12
12
  "route.ts": "route",
13
13
  "loading.tsx": "loading",
14
- "fallback.tsx": "fallback"
14
+ "fallback.tsx": "fallback",
15
+ "paths.ts": "paths"
15
16
  };
16
17
  const ROUTE_FILES = Object.keys(CONVENTION).join(", ");
17
18
  const PARAM = /^\[([A-Za-z_][A-Za-z0-9_]*)\]$/u;
@@ -116,6 +117,10 @@ const convert = (raw, name, path, kind, key, problems) => {
116
117
  path: slots.route,
117
118
  message: `"${here}" cannot both redirect and answer from route.ts — keep one`
118
119
  });
120
+ if (slots.paths !== void 0 && kind !== "param") problems.push({
121
+ path: slots.paths,
122
+ message: `paths.ts gives the values of its directory's parameter, and "${here}" is not a [param] directory — move it into the parameter's directory`
123
+ });
119
124
  const children = [...raw.dirs.entries()].map(([childName, childRaw]) => {
120
125
  const childPath = path === "" ? childName : `${path}/${childName}`;
121
126
  const classified = classify(childName, childPath, problems);
@@ -135,6 +140,7 @@ const convert = (raw, name, path, kind, key, problems) => {
135
140
  guard: slots.guard ?? null,
136
141
  route: slots.route ?? null,
137
142
  fallback: slots.fallback ?? null,
143
+ paths: slots.paths ?? null,
138
144
  children
139
145
  };
140
146
  };
@@ -154,6 +160,23 @@ const eachPattern = (dir, prefix, visit) => {
154
160
  eachPattern(child, next, visit);
155
161
  }
156
162
  };
163
+ /**
164
+ * Every `paths.ts` in a parameter's directory, outermost first. One in any
165
+ * other directory is a problem the parse reports, and is not listed.
166
+ */
167
+ const pathsFiles = (tree) => {
168
+ const found = [];
169
+ const walk = (dir, prefix) => {
170
+ const here = dir.kind === "root" ? "" : prefix;
171
+ if (dir.paths !== null && dir.kind === "param") found.push({
172
+ file: dir.paths,
173
+ pattern: here
174
+ });
175
+ for (const child of dir.children) walk(child, child.kind === "group" ? here : `${here}${child.key}`);
176
+ };
177
+ walk(tree, "");
178
+ return found;
179
+ };
157
180
  const checkFallback = (dir, file, pattern, params, above) => {
158
181
  const here = dir.path === "" ? "/" : dir.path;
159
182
  const refuse = (message) => ({ problem: {
@@ -164,7 +187,7 @@ const checkFallback = (dir, file, pattern, params, above) => {
164
187
  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
188
  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
189
  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`);
190
+ 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 return the values from a paths.ts`);
168
191
  return { shape: {
169
192
  pattern,
170
193
  file,
@@ -540,7 +563,8 @@ const LATE = /* @__PURE__ */ new Set([
540
563
  "page",
541
564
  "notFound",
542
565
  "route",
543
- "fallback"
566
+ "fallback",
567
+ "paths"
544
568
  ]);
545
569
  const isLate = (file) => {
546
570
  const slot = slotOf(file);
@@ -560,6 +584,8 @@ const emitRoutesModule = (tree, options) => {
560
584
  }));
561
585
  const shells = options.mode === "static" ? fallbackShapes(tree) : [];
562
586
  for (const shape of shells) namer.take(shape.file);
587
+ const supplies = options.mode === "static" ? pathsFiles(tree) : [];
588
+ for (const supply of supplies) namer.take(supply.file);
563
589
  const guarded = guardsOf(tree);
564
590
  const guardStacks = new Map([...guarded.stacks].map(([pattern, files]) => [pattern, files.map((file) => namer.take(file))]));
565
591
  const guardChecks = [...guarded.own].map(([file, pattern]) => `${pad(1)}Checked<typeof ${namer.take(file)}, Guard<'${pattern}'>>,`);
@@ -604,8 +630,9 @@ const emitRoutesModule = (tree, options) => {
604
630
  });
605
631
  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
632
  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));
633
+ const pathsChecks = supplies.map(({ pattern, file }) => `${pad(1)}Checked<Loaded<typeof ${namer.take(file)}>['default'], Paths<'${pattern}'>>,`);
634
+ const hasChecks = schemaChecks.length + routeChecks.length + fallbackChecks.length + pathsChecks.length + guardChecks.length > 0;
635
+ const readsLate = routeFiles.length > 0 || shells.length > 0 || supplies.length > 0 || searchReaders.size > 0 || [...namer.names.keys()].some((file) => withParams.has(file) && isLate(file));
609
636
  const hasRoutes = routeFiles.length > 0;
610
637
  const hasError = [...asserted.values()].includes("ErrorComponent");
611
638
  const withRequest = options.mode === "server";
@@ -621,6 +648,7 @@ const emitRoutesModule = (tree, options) => {
621
648
  ...hasLayout ? ["ParamsOf"] : [],
622
649
  ...schemaChecks.length > 0 ? ["ParamsSchemaFor"] : [],
623
650
  "ParsedParams",
651
+ ...supplies.length > 0 ? ["Paths"] : [],
624
652
  ...redirects.length > 0 ? ["RedirectTarget"] : []
625
653
  ];
626
654
  return [
@@ -803,6 +831,21 @@ const emitRoutesModule = (tree, options) => {
803
831
  ] : []
804
832
  ] : ["// A running server renders every value with its page: no shells.", "export const fallbacks = {} as const;"],
805
833
  "",
834
+ ...options.mode === "static" ? [
835
+ "// Per paths.ts, by its file: what reads the values its directory's",
836
+ "// parameter takes. Only the build asks.",
837
+ "export const paths = {",
838
+ ...supplies.map(({ file }) => `${pad(1)}'${file}': ${namer.take(file)},`),
839
+ "} as const;",
840
+ ...pathsChecks.length > 0 ? [
841
+ "",
842
+ "// The paths.ts files, each checked against the pattern of its directory.",
843
+ "export type PathsChecks = [",
844
+ ...pathsChecks,
845
+ "];"
846
+ ] : []
847
+ ] : ["// A running server renders whatever value arrives: no values to list.", "export const paths = {} as const;"],
848
+ "",
806
849
  "export const routes = defineRoutes({",
807
850
  ...body,
808
851
  "});",
@@ -908,10 +951,20 @@ const CLIENT_DEPS_HEADER = "x-k8ordo-client-deps";
908
951
  /** What `clientDepsHeader` said. */
909
952
  const readClientDeps = (value) => JSON.parse(decodeURIComponent(value));
910
953
  /**
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.
954
+ * Said by the handler under mode: 'static' alone, on a page's HTML: every
955
+ * stylesheet the Server Components of the payload it rendered link
956
+ * (`serverStylesheetsHeader`), which the build lists in `CLIENT_FILES_PATH`
957
+ * beside the client modules' files.
958
+ */
959
+ const SERVER_STYLESHEETS_HEADER = "x-k8ordo-server-stylesheets";
960
+ /** What `serverStylesheetsHeader` said. */
961
+ const readServerStylesheets = (value) => JSON.parse(decodeURIComponent(value));
962
+ /**
963
+ * Where a static build lists the files each page needs beyond its payload —
964
+ * its client components' scripts and stylesheets, and its Server Components'
965
+ * stylesheets — at the root of the site under Vite's `base`. A navigation
966
+ * links them as it asks for the payload, instead of once the payload has
967
+ * named them — a round trip sooner.
915
968
  */
916
969
  const CLIENT_FILES_PATH = "/client-files.json";
917
970
  // src/paths.ts
@@ -1115,6 +1168,84 @@ const planPaths = (tree, supplied) => {
1115
1168
  };
1116
1169
  };
1117
1170
  /**
1171
+ * A value as the segment of a pathname. Past `encodeURIComponent`, the two
1172
+ * characters this module reads a pathname by: `*`, and the `:` that would
1173
+ * make a value starting with one a parameter left open.
1174
+ */
1175
+ const segmentOf = (value) => encodeURIComponent(value).replaceAll("*", "%2A").replaceAll(":", "%3A");
1176
+ const valuesFrom = (returned) => Array.isArray(returned) && returned.every((value) => typeof value === "string" && value !== "") ? [...new Set(returned)] : null;
1177
+ /**
1178
+ * What the `paths.ts` files say the site holds: each is asked for its
1179
+ * directory's parameter, once per combination of the values above it, and
1180
+ * the values multiply down the tree — to the pages, and to the route.ts and
1181
+ * redirect.ts files, that sit below.
1182
+ *
1183
+ * A parameter no paths.ts gives values to stays open (`:name`), and an open
1184
+ * location is offered only where a fallback.tsx stands in for the page: that
1185
+ * is where its shell goes. So with `[locale]/paths.ts` and a fallback.tsx
1186
+ * under `[id]`, the shells stand at `/ja/posts/:id` and `/en/posts/:id`,
1187
+ * and `/fr/posts/1` is nobody's. A directory with both lists its values and
1188
+ * keeps a shell for the rest. Everything else is left for `planPaths` to
1189
+ * call unresolved.
1190
+ *
1191
+ * A value is the segment as a visitor reads it, escaped here for the URL.
1192
+ */
1193
+ const suppliedFrom = async (tree, valuesOf) => {
1194
+ const locations = [];
1195
+ const problems = /* @__PURE__ */ new Set();
1196
+ const walk = async (dir, ats) => {
1197
+ const answers = dir.page ?? dir.route ?? dir.redirect;
1198
+ const shell = dir.page !== null && dir.fallback !== null;
1199
+ if (answers !== null) {
1200
+ for (const at of ats) if (at.open ? shell : Object.keys(at.params).length > 0) locations.push(at.path);
1201
+ }
1202
+ await Promise.all(dir.children.map(async (child) => {
1203
+ if (child.kind === "group") return walk(child, ats);
1204
+ if (child.kind !== "param") return walk(child, ats.map((at) => ({
1205
+ ...at,
1206
+ path: `${at.path}${child.key}`
1207
+ })));
1208
+ const name = child.key.slice(2);
1209
+ const opened = (at) => ({
1210
+ ...at,
1211
+ path: `${at.path}/:${name}`,
1212
+ open: true
1213
+ });
1214
+ const { paths: file } = child;
1215
+ if (file === null) return walk(child, ats.map(opened));
1216
+ const below = await Promise.all(ats.map(async (at) => {
1217
+ if (at.open) {
1218
+ problems.add(`${file} is asked for its values once per value of the parameters above it, and ${at.path} still holds one — give that parameter's directory a paths.ts too`);
1219
+ return [];
1220
+ }
1221
+ const values = valuesFrom(await valuesOf(file, at.params));
1222
+ if (values === null) {
1223
+ problems.add(`${file} has to return an array of non-empty strings, the values of :${name}`);
1224
+ return [];
1225
+ }
1226
+ return [...values.map((value) => ({
1227
+ path: `${at.path}/${segmentOf(value)}`,
1228
+ params: {
1229
+ ...at.params,
1230
+ [name]: value
1231
+ },
1232
+ open: false
1233
+ })), ...child.page !== null && child.fallback !== null ? [opened(at)] : []];
1234
+ }));
1235
+ return walk(child, below.flat());
1236
+ }));
1237
+ };
1238
+ await walk(tree, [{
1239
+ path: "",
1240
+ params: {},
1241
+ open: false
1242
+ }]);
1243
+ return {
1244
+ locations,
1245
+ problems: [...problems]
1246
+ };
1247
+ };
1248
+ /**
1118
1249
  * Shells whose host rule would answer URLs the table gives a pattern declared
1119
1250
  * before theirs — a page, route.ts or redirect.ts with a parameter and no
1120
1251
  * fallback.tsx of its own. A host matches the shell's location alone, so the
@@ -1177,14 +1308,14 @@ const planRefusals = (plan, shadowed) => {
1177
1308
  const bare = plan.closed.filter((each) => !each.supplied);
1178
1309
  const suppliedClosed = plan.closed.filter((each) => each.supplied);
1179
1310
  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")] : []
1311
+ ...plan.unresolved.length > 0 ? [`static build needs the values of ${plan.unresolved.join(", ")} — a paths.ts in each parameter's directory returns them, and a fallback.tsx beside a page answers the ones the build does not write`] : [],
1312
+ ...plan.unusable.length > 0 ? [`the paths.ts files returned pathnames no route wants: ${plan.unusable.join(", ")}`] : [],
1313
+ ...plan.held.length > 0 ? [`these pathnames 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(", ")}`] : [],
1314
+ ...plan.misnamed.length > 0 ? [`these shell locations name parameters that are not their pattern's: ${plan.misnamed.map(({ location, pattern }) => `${location} (${pattern})`).join(", ")}`] : [],
1315
+ ...suppliedClosed.length > 0 ? [`these shells leave out a parameter a layout above their fallback.tsx receives, so its directory needs a paths.ts: ${suppliedClosed.map(({ location, params, layout }) => `${location} (${paramList(params)}, received by ${layout})`).join(", ")}`] : [],
1316
+ ...bare.length > 0 ? [bare.map(({ location, params, layout }) => `static build needs the values of ${paramList(params)} for the shell of ${location} — ${layout} receives ${params.length === 1 ? "it" : "them"}, so ${params.length === 1 ? "that parameter's directory needs" : "those parameters' directories need"} a paths.ts, which puts the shell at ${location.split("/").map((segment) => params.some((name) => segment === `:${name}`) ? `<${segment.slice(1)}>` : segment).join("/")}`).join("\n")] : [],
1317
+ ...plan.reserved.length > 0 ? [`a paths.ts returned ${FALLBACK_SEGMENT}, which the build keeps for shells: ${plan.reserved.join(", ")}`] : [],
1318
+ ...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 put` : "put"} the shell where it cannot match, with a paths.ts above it` : `the shell for ${location} (${fallback}) would also answer ${url}, which ${file} is declared first for and the build did not write — return its value from that parameter's paths.ts, or put the shell where it cannot match, with a paths.ts above it`).join("\n")] : []
1188
1319
  ];
1189
1320
  };
1190
1321
  /**
@@ -1197,12 +1328,14 @@ const planRefusals = (plan, shadowed) => {
1197
1328
  */
1198
1329
  const dirFor = (pathname) => {
1199
1330
  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}`);
1331
+ if (decoded === null) throw new Error(`a pathname to write has a malformed escape: ${pathname}`);
1332
+ if (decoded.split("/").some((segment) => segment === "..")) throw new Error(`a pathname to write leaves the output: ${pathname}`);
1202
1333
  return decoded;
1203
1334
  };
1204
1335
  /** Where a pathname's file lands inside the client build, `/`-separated. */
1205
1336
  const fileAt = (pathname, name = "") => posix.join(dirFor(pathname), name).slice(1);
1337
+ /** Where the build's own sitemap goes, unless a route.ts answers there. */
1338
+ const SITEMAP_PATHNAME = "/sitemap.xml";
1206
1339
  /**
1207
1340
  * What answers each pathname the build writes: the first declared pattern
1208
1341
  * that matches it, in the matcher's order. The catch-all never answers a
@@ -1220,9 +1353,10 @@ const answersOf = (dir, pathnames) => {
1220
1353
  * message: at `/`, below which every file goes; where something else is
1221
1354
  * written below it; or where the build writes a file of its own, after the
1222
1355
  * routes' files — a page's beside them — so one would replace the other
1223
- * without a word.
1356
+ * without a word. `sitemap.xml` is not among those: the build leaves it to a
1357
+ * route.ts that writes it.
1224
1358
  */
1225
- const routeFileRefusals = (tree, plan, answers, { site, named }) => {
1359
+ const routeFileRefusals = (tree, plan, answers, { named }) => {
1226
1360
  const written = /* @__PURE__ */ new Map();
1227
1361
  for (const [pathname, answer] of answers) {
1228
1362
  if (answer.kind === "route") continue;
@@ -1232,8 +1366,7 @@ const routeFileRefusals = (tree, plan, answers, { site, named }) => {
1232
1366
  }
1233
1367
  const notFound = declaredPatterns(tree).find((each) => each.kind === "notFound");
1234
1368
  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");
1369
+ written.set(CLIENT_FILES_PATH.slice(1), "the build lists there what each page loads beyond its payload");
1237
1370
  if (plan.shells.length > 0) {
1238
1371
  const fallbacks = fallbackShapes(tree).filter((shape) => plan.shells.some((shell) => shell.pattern === shape.pattern)).map((shape) => named(shape.file));
1239
1372
  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`);
@@ -1271,4 +1404,4 @@ const isFile = async (candidate) => {
1271
1404
  return false;
1272
1405
  }
1273
1406
  };
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 };
1407
+ export { emitRoutesModule as A, SHELL_HEADER as C, decodePathname as D, FALLBACK_SEGMENT as E, parseRouteTree as F, slotOf as I, FRAMEWORK as M, ROUTE_METHODS as N, LOCALES_MODULE as O, fallbackShapes as P, SERVER_STYLESHEETS_HEADER as S, readServerStylesheets as T, suppliedFrom as _, catchAllPath as a, NONCE_HEADER as b, fileAt as c, patternsNeedingPaths as d, patternsOf as f, shadowedShells as g, routeFileRefusals as h, answersOf as i, unreachableRoutes as j, emitRegisterModule as k, isConcrete as l, planRefusals as m, safeJoin as n, catchAllRefusals as o, planPaths as p, SITEMAP_PATHNAME as r, dirFor as s, isFile as t, isParamSegment as u, CLIENT_DEPS_HEADER as v, readClientDeps as w, NOT_FOUND_HEADER as x, CLIENT_FILES_PATH as y };
@@ -1,4 +1,4 @@
1
- import { b as FALLBACK_SEGMENT, c as isParamSegment, n as safeJoin, t as isFile } from "./static-file-BAjwBMMl.mjs";
1
+ import { E as FALLBACK_SEGMENT, n as safeJoin, t as isFile, u as isParamSegment } from "./static-file-BEk_xO5y.mjs";
2
2
  import { normalizePathname, withBase, withoutBase } from "@k8ordo/router";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import path from "node:path";
package/dist/vercel.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import "./static-DnbgGIoy.mjs";
1
+ import "./static-c-nX9Juk.mjs";
2
2
  import { Plugin } from "vite";
3
3
  /**
4
4
  * A route as Vercel's Build Output API (v3) reads it, written to