@k8ordo/framework 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,10 +35,10 @@ dependencies in either mode: the build bundles what the application runs.
35
35
 
36
36
  | Package | Version | Required | Needed for |
37
37
  | --------------------- | -------- | -------- | ------------------------------------------ |
38
- | `@k8ordo/router` | ^1.2.1 | yes | routing, re-exported by the framework |
38
+ | `@k8ordo/router` | ^1.3.0 | yes | routing, re-exported by the framework |
39
39
  | `react` | ≥19.3.0 | yes | rendering |
40
40
  | `react-dom` | ≥19.3.0 | yes | rendering |
41
- | `vite` | ≥8.0.0 | yes | the build (`framework()` is a Vite plugin) |
41
+ | `vite` | ≥8.1.0 | yes | the build (`framework()` is a Vite plugin) |
42
42
  | `oxc-transform-react` | ^0.152.0 | optional | `reactCompiler: true` (React Compiler) |
43
43
 
44
44
  <!-- /peers -->
@@ -6,9 +6,10 @@ export declare const setDocumentClient: (client: string) => void;
6
6
  export declare const navigationsApplied: () => number;
7
7
  /**
8
8
  * What a Server Action's answer does to the document, once it is read.
9
- * `sent` is `navigationsApplied()` as the action was sent.
9
+ * `sent` is `navigationsApplied()` as the action was sent, and `url` where
10
+ * it was posted: the answer is that page.
10
11
  */
11
- export declare const answerAction: (payload: Payload, sent: number) => Promise<unknown>;
12
+ export declare const answerAction: (payload: Payload, sent: number, url: string) => Promise<unknown>;
12
13
  export declare const setPayloadReader: (read: (stream: ReadableStream<Uint8Array>) => Promise<Payload>) => void;
13
14
  /**
14
15
  * The client half under the framework: the tree comes from the server, so
@@ -5,7 +5,8 @@ import { ShowNotFound } from "./fallback-boundary.mjs";
5
5
  import { isPayload } from "./is-payload.mjs";
6
6
  import { createPrefetchCache, prefetchTargetOf } from "./prefetch.mjs";
7
7
  import { Recover, markNavigated, reloadInstead } from "./recover.mjs";
8
- import { NavigationGeneration, PathnameProvider, useInterceptedNavigation, withoutBase } from "@k8ordo/router";
8
+ import { TreePathname } from "./tree-pathname.mjs";
9
+ import { NavigationGeneration, PathnameProvider, normalizePathname, useInterceptedNavigation, withoutBase } from "@k8ordo/router";
9
10
  import { startTransition, useDeferredValue, useEffect, useRef, useState } from "react";
10
11
  import { jsx } from "react/jsx-runtime";
11
12
  //#region src/runtime/app-router.tsx
@@ -54,9 +55,10 @@ let navigations = 0;
54
55
  const navigationsApplied = () => navigations;
55
56
  /**
56
57
  * What a Server Action's answer does to the document, once it is read.
57
- * `sent` is `navigationsApplied()` as the action was sent.
58
+ * `sent` is `navigationsApplied()` as the action was sent, and `url` where
59
+ * it was posted: the answer is that page.
58
60
  */
59
- const answerAction = async (payload, sent) => {
61
+ const answerAction = async (payload, sent, url) => {
60
62
  mounted?.forgetPrefetched();
61
63
  if (payload.redirect !== void 0) {
62
64
  await navigation.navigate(payload.redirect).finished;
@@ -64,7 +66,7 @@ const answerAction = async (payload, sent) => {
64
66
  }
65
67
  if (!canRender(payload)) return reloadInstead();
66
68
  await whenClientReady([payload.tree, payload.notFound], WHEN_APPLIED);
67
- if (navigations === sent) mounted?.apply(payload);
69
+ if (navigations === sent) mounted?.apply(payload, normalizePathname(new URL(url).pathname));
68
70
  return payload.returnValue;
69
71
  };
70
72
  let readPayload = () => Promise.reject(/* @__PURE__ */ new Error("k8ordo: payloads are read in the browser only"));
@@ -115,7 +117,7 @@ let applies = 0;
115
117
  * Takes over the request of a payload whose tree is being applied, and
116
118
  * returns what applying it puts in state.
117
119
  */
118
- const hold = (streaming, payload) => {
120
+ const hold = (streaming, payload, pathname) => {
119
121
  applies += 1;
120
122
  const stream = streams.get(payload);
121
123
  if (stream !== void 0) {
@@ -129,7 +131,8 @@ const hold = (streaming, payload) => {
129
131
  return {
130
132
  tree: payload.tree,
131
133
  notFound: payload.notFound,
132
- order: applies
134
+ order: applies,
135
+ pathname
133
136
  };
134
137
  };
135
138
  /**
@@ -164,7 +167,8 @@ function AppRouter({ pathname, search, tree, notFound }) {
164
167
  const [latest, setLatest] = useState(() => ({
165
168
  tree,
166
169
  notFound,
167
- order: 0
170
+ order: 0,
171
+ pathname: typeof location === "undefined" ? null : normalizePathname(location.pathname)
168
172
  }));
169
173
  const current = useDeferredValue(latest);
170
174
  const prefetched = useRef(null);
@@ -181,9 +185,9 @@ function AppRouter({ pathname, search, tree, notFound }) {
181
185
  }, [latest, current]);
182
186
  useEffect(() => {
183
187
  mounted = {
184
- apply: (payload) => {
188
+ apply: (payload, postedTo) => {
185
189
  searchApplied.current = payload.search;
186
- const next = hold(streaming.current, payload);
190
+ const next = hold(streaming.current, payload, postedTo);
187
191
  startTransition(() => {
188
192
  setLatest(next);
189
193
  });
@@ -216,7 +220,7 @@ function AppRouter({ pathname, search, tree, notFound }) {
216
220
  if (!canRender(payload)) return reloadInstead();
217
221
  markNavigated();
218
222
  navigations += 1;
219
- const next = hold(streaming.current, payload);
223
+ const next = hold(streaming.current, payload, normalizePathname(new URL(url).pathname));
220
224
  searchApplied.current = payload.search;
221
225
  startTransition(() => {
222
226
  setLatest(next);
@@ -260,16 +264,19 @@ function AppRouter({ pathname, search, tree, notFound }) {
260
264
  signal.throwIfAborted();
261
265
  if (payload === null) return await reloadInstead();
262
266
  if (!canRender(payload)) return await reloadInstead();
263
- return payload;
267
+ return {
268
+ payload,
269
+ pathname: normalizePathname(url.pathname)
270
+ };
264
271
  } finally {
265
272
  loading.current -= 1;
266
273
  }
267
274
  },
268
- apply: (next) => {
275
+ apply: (loaded) => {
269
276
  markNavigated();
270
277
  navigations += 1;
271
- searchApplied.current = next.search;
272
- setLatest(hold(streaming.current, next));
278
+ searchApplied.current = loaded.payload.search;
279
+ setLatest(hold(streaming.current, loaded.payload, loaded.pathname));
273
280
  },
274
281
  refresh: (url) => searchApplied.current !== void 0 && url.search !== searchApplied.current
275
282
  });
@@ -277,9 +284,9 @@ function AppRouter({ pathname, search, tree, notFound }) {
277
284
  const show = () => {
278
285
  if (loading.current > 0) return false;
279
286
  setLatest((previous) => previous === shown ? {
287
+ ...shown,
280
288
  tree: shown.notFound,
281
- notFound: void 0,
282
- order: shown.order
289
+ notFound: void 0
283
290
  } : previous);
284
291
  return true;
285
292
  };
@@ -287,10 +294,13 @@ function AppRouter({ pathname, search, tree, notFound }) {
287
294
  pathname,
288
295
  children: /* @__PURE__ */ jsx(NavigationGeneration, {
289
296
  value: generation,
290
- children: /* @__PURE__ */ jsx(Recover, { children: /* @__PURE__ */ jsx(ShowNotFound, {
291
- value: current.notFound === void 0 ? null : show,
292
- children: current.tree
293
- }) })
297
+ children: /* @__PURE__ */ jsx(TreePathname, {
298
+ value: current.pathname,
299
+ children: /* @__PURE__ */ jsx(Recover, { children: /* @__PURE__ */ jsx(ShowNotFound, {
300
+ value: current.notFound === void 0 ? null : show,
301
+ children: current.tree
302
+ }) })
303
+ })
294
304
  })
295
305
  });
296
306
  }
@@ -11,13 +11,14 @@ const connectAppRouter = () => {
11
11
  setPayloadReader((stream) => createFromReadableStream(stream));
12
12
  setServerCallback(async (id, args) => {
13
13
  const sent = navigationsApplied();
14
+ const url = location.href;
14
15
  const temporaryReferences = createTemporaryReferenceSet();
15
- const payload = await createFromFetch(fetch(location.href, {
16
+ const payload = await createFromFetch(fetch(url, {
16
17
  method: "POST",
17
18
  headers: { [ACTION_ID_HEADER]: id },
18
19
  body: await encodeReply(args, { temporaryReferences })
19
20
  }), { temporaryReferences });
20
- return answerAction(payload, sent);
21
+ return answerAction(payload, sent, url);
21
22
  });
22
23
  };
23
24
  //#endregion
@@ -2,7 +2,7 @@ import { fileRequest, routeRequestOf } from "./request.mjs";
2
2
  import { answer, inPhase, signingNonce, withRequest, writingFile } from "./request-scope.mjs";
3
3
  import { methodNotAllowed, routeAnswerFor, runRoute } from "./route.mjs";
4
4
  import { NOT_FOUND_SEGMENT } from "./pathname.mjs";
5
- import { ACTION_ID_HEADER, NONCE_HEADER, NOT_FOUND_DIGEST, NOT_FOUND_HEADER, SHELL_HEADER } from "./payload.mjs";
5
+ import { ACTION_ID_HEADER, CLIENT_DEPS_HEADER, NONCE_HEADER, NOT_FOUND_DIGEST, NOT_FOUND_HEADER, SHELL_HEADER, clientDepsHeader } from "./payload.mjs";
6
6
  import { isPayloadPath, pagePathFor } from "./payload-path.mjs";
7
7
  import { isRedirect } from "./redirect.mjs";
8
8
  import { noticeCancel } from "./cancel.mjs";
@@ -349,9 +349,12 @@ const respond = async (request) => {
349
349
  }
350
350
  });
351
351
  if (import.meta.env.K8ORDO_MODE === "static") {
352
+ const [forHtml, forNamed] = rendered.stream.tee();
353
+ await drain(forNamed);
354
+ const named = [...rendered.named.values()];
352
355
  let body;
353
356
  try {
354
- const html = await enter(() => ssr.renderHtml(rendered.stream, signingNonce(), showsPage, action.formState !== void 0));
357
+ const html = await enter(() => ssr.renderHtml(forHtml, signingNonce(), showsPage, action.formState !== void 0, named));
355
358
  body = await new Response(html).arrayBuffer();
356
359
  } catch (error) {
357
360
  return renderFailed(rendered.failures[0] ?? error);
@@ -363,12 +366,13 @@ const respond = async (request) => {
363
366
  headers: {
364
367
  "content-type": HTML_TYPE,
365
368
  [NONCE_HEADER]: signingNonce(),
369
+ [CLIENT_DEPS_HEADER]: clientDepsHeader(rendered.named.values()),
366
370
  ...saidByPage,
367
371
  ...shellSaid
368
372
  }
369
373
  });
370
374
  }
371
- const html = await enter(() => ssr.renderHtml(rendered.stream, signingNonce(), showsPage, action.formState !== void 0));
375
+ const html = await enter(() => ssr.renderHtml(rendered.stream, signingNonce(), showsPage, action.formState !== void 0, []));
372
376
  return new Response(html, {
373
377
  status,
374
378
  headers: { "content-type": HTML_TYPE }
@@ -397,6 +401,7 @@ const matchNotFound = (pathname, forShell) => {
397
401
  };
398
402
  const renderPayload = (payload, enter, temporaryReferences) => {
399
403
  const failures = [];
404
+ const named = /* @__PURE__ */ new Map();
400
405
  let said = false;
401
406
  const { promise: saidNotFound, resolve } = Promise.withResolvers();
402
407
  const controller = new AbortController();
@@ -413,11 +418,19 @@ const renderPayload = (payload, enter, temporaryReferences) => {
413
418
  failures.push(error);
414
419
  console.error("k8ordo: rendering %s failed", payload.pathname, error);
415
420
  }
416
- }));
421
+ }, import.meta.env.K8ORDO_MODE === "static" ? { onClientReference: ({ id, name, deps }) => {
422
+ named.set(`${id}#${name}`, {
423
+ id,
424
+ name,
425
+ js: deps.js,
426
+ css: deps.css
427
+ });
428
+ } } : void 0));
417
429
  return {
418
430
  stream: noticeCancel(flight, (reason) => {
419
431
  controller.abort(reason);
420
432
  }),
433
+ named,
421
434
  failures,
422
435
  notFound: () => said,
423
436
  saidNotFound,
@@ -1,3 +1,4 @@
1
+ import { ClientDeps } from "./payload.mjs";
1
2
  //#region src/runtime/entry.ssr.d.ts
2
3
  /**
3
4
  * The script every page's HTML loads, and so the client every payload is
@@ -12,5 +13,5 @@ export declare const clientEntry: string;
12
13
  * one round trip. It is also what lets a prerendered `404.html` come alive —
13
14
  * there is no payload file at a URL the application does not have.
14
15
  */
15
- export declare function renderHtml(rscStream: ReadableStream<Uint8Array>, nonce: string, showsPage: boolean, carriesFormState: boolean): Promise<ReadableStream>;
16
+ export declare function renderHtml(rscStream: ReadableStream<Uint8Array>, nonce: string, showsPage: boolean, carriesFormState: boolean, named: readonly ClientDeps[]): Promise<ReadableStream>;
16
17
  //#endregion
@@ -1,12 +1,15 @@
1
+ import { SERVER_STYLESHEETS, STYLESHEET_ORDER_HREF } from "./payload.mjs";
1
2
  import { whenClientReady } from "./client-ready.mjs";
2
3
  import { AppRouter } from "./app-router.mjs";
3
4
  import { noticeCancel } from "./cancel.mjs";
4
5
  import { PageShownContext } from "./page-shown.mjs";
5
6
  import { use } from "react";
6
- import { jsx } from "react/jsx-runtime";
7
+ import { jsx, jsxs } from "react/jsx-runtime";
7
8
  import { createFromReadableStream, getClientEntryUrl } from "@vitejs/plugin-rsc/ssr";
9
+ import { preinit, preloadModule } from "react-dom";
8
10
  import { renderToReadableStream } from "react-dom/server.edge";
9
11
  import { injectRSCPayload } from "rsc-html-stream/server";
12
+ import assetsManifest from "virtual:vite-rsc/assets-manifest";
10
13
  //#region src/runtime/entry.ssr.tsx
11
14
  /**
12
15
  * The script every page's HTML loads, and so the client every payload is
@@ -14,6 +17,31 @@ import { injectRSCPayload } from "rsc-html-stream/server";
14
17
  * the RSC plugin names the client entry to this environment only.
15
18
  */
16
19
  const clientEntry = getClientEntryUrl();
20
+ const entryScripts = new Set(assetsManifest.clientEntryDeps?.js);
21
+ /**
22
+ * Asks React to link what each client component needs as the RSC plugin
23
+ * asks when the HTML render reads one — its scripts preloaded as modules,
24
+ * the client entry's own at the default priority and the rest low, its
25
+ * stylesheets under the plugin's precedence — so a file is written the same
26
+ * whichever of the two asked first: React writes it as first asked for.
27
+ */
28
+ const linkClientDeps = (named) => {
29
+ for (const { js, css } of named) {
30
+ for (const href of js) {
31
+ const options = {
32
+ as: "script",
33
+ crossOrigin: "",
34
+ ...entryScripts.has(href) ? {} : { fetchPriority: "low" }
35
+ };
36
+ preloadModule(href, options);
37
+ }
38
+ for (const href of css) preinit(href, {
39
+ as: "style",
40
+ crossOrigin: "anonymous",
41
+ precedence: "vite-rsc/client-reference"
42
+ });
43
+ }
44
+ };
17
45
  /**
18
46
  * The payload turned into HTML, with the payload itself written into that
19
47
  * HTML. Hydration then reads what this render read, rather than asking the
@@ -21,7 +49,7 @@ const clientEntry = getClientEntryUrl();
21
49
  * one round trip. It is also what lets a prerendered `404.html` come alive —
22
50
  * there is no payload file at a URL the application does not have.
23
51
  */
24
- async function renderHtml(rscStream, nonce, showsPage, carriesFormState) {
52
+ async function renderHtml(rscStream, nonce, showsPage, carriesFormState, named) {
25
53
  const [forRender, forHydration] = rscStream.tee();
26
54
  let forHtml = forRender;
27
55
  let formState;
@@ -33,6 +61,7 @@ async function renderHtml(rscStream, nonce, showsPage, carriesFormState) {
33
61
  let payload;
34
62
  let ready;
35
63
  function Root() {
64
+ linkClientDeps(named);
36
65
  payload ??= createFromReadableStream(forHtml, { nonce });
37
66
  const { notFound, pathname, search, tree } = use(payload);
38
67
  ready ??= whenClientReady([tree, notFound], { rows: import.meta.env.K8ORDO_MODE === "static" ? "wait" : "follow" });
@@ -46,12 +75,20 @@ async function renderHtml(rscStream, nonce, showsPage, carriesFormState) {
46
75
  }
47
76
  const shown = Promise.withResolvers();
48
77
  let readerLeft = false;
49
- const htmlStream = await renderToReadableStream(/* @__PURE__ */ jsx(PageShownContext, {
78
+ const styleNonce = import.meta.env.K8ORDO_MODE === "static" ? void 0 : nonce;
79
+ const htmlStream = await renderToReadableStream(/* @__PURE__ */ jsxs(PageShownContext, {
50
80
  value: () => shown.resolve(void 0),
51
- children: /* @__PURE__ */ jsx(Root, {})
81
+ children: [/* @__PURE__ */ jsx("style", {
82
+ href: STYLESHEET_ORDER_HREF,
83
+ precedence: SERVER_STYLESHEETS,
84
+ nonce: styleNonce
85
+ }), /* @__PURE__ */ jsx(Root, {})]
52
86
  }), {
53
87
  bootstrapModules: [clientEntry],
54
- nonce,
88
+ nonce: styleNonce === void 0 ? nonce : {
89
+ script: nonce,
90
+ style: styleNonce
91
+ },
55
92
  formState,
56
93
  progressiveChunkSize: Number.POSITIVE_INFINITY,
57
94
  onError: (error) => {
@@ -67,6 +67,18 @@ export declare const NOT_FOUND_HEADER = "x-k8ordo-not-found";
67
67
  * everyone reads the same one.
68
68
  */
69
69
  export declare const NONCE_HEADER = "x-k8ordo-nonce";
70
+ /**
71
+ * The `href` of the one `<style>` the HTML render writes itself, empty, under
72
+ * the precedence the RSC plugin links a Server Component's stylesheets with.
73
+ * React orders the precedences in `<head>` as each is first asked for, and
74
+ * puts a stylesheet loaded later after the last of its own; asked for first,
75
+ * this keeps the Server Components' stylesheets before the client
76
+ * components'. Under mode: 'static' it carries no nonce, and the build names
77
+ * it by hash where the policy decides a style element.
78
+ */
79
+ export declare const STYLESHEET_ORDER_HREF = "k8ordo-stylesheet-order";
80
+ /** The precedence the RSC plugin links a Server Component's stylesheet with. */
81
+ export declare const SERVER_STYLESHEETS = "vite-rsc/importer-resources";
70
82
  /**
71
83
  * Said by the handler under mode: 'static' alone, on a shell's HTML and
72
84
  * payload: the pattern whose fallback.tsx rendered it. The table walks in its
@@ -74,4 +86,29 @@ export declare const NONCE_HEADER = "x-k8ordo-nonce";
74
86
  * one the build asked for, and the build compares instead of guessing.
75
87
  */
76
88
  export declare const SHELL_HEADER = "x-k8ordo-shell";
89
+ /**
90
+ * A client component a payload names — the id the build's manifest keys its
91
+ * module with, and its export's name: two exports are two components — and
92
+ * the stylesheets and scripts the manifest says it needs.
93
+ */
94
+ export type ClientDeps = {
95
+ readonly id: string;
96
+ readonly name: string;
97
+ readonly js: readonly string[];
98
+ readonly css: readonly string[];
99
+ };
100
+ /**
101
+ * Said by the handler under mode: 'static' alone, on a page's HTML: every
102
+ * client component the payload it rendered names (`clientDepsHeader`) — what
103
+ * the HTML render was handed to link — which the build checks the HTML
104
+ * links.
105
+ */
106
+ export declare const CLIENT_DEPS_HEADER = "x-k8ordo-client-deps";
107
+ /**
108
+ * The value of `CLIENT_DEPS_HEADER`. Encoded, because a header's value is
109
+ * bytes, and a chunk is named after a module, whose name need not be ASCII.
110
+ */
111
+ export declare const clientDepsHeader: (named: Iterable<ClientDeps>) => string;
112
+ /** What `clientDepsHeader` said. */
113
+ export declare const readClientDeps: (value: string) => ClientDeps[];
77
114
  //#endregion
@@ -20,11 +20,37 @@ const NOT_FOUND_HEADER = "x-k8ordo-not-found";
20
20
  */
21
21
  const NONCE_HEADER = "x-k8ordo-nonce";
22
22
  /**
23
+ * The `href` of the one `<style>` the HTML render writes itself, empty, under
24
+ * the precedence the RSC plugin links a Server Component's stylesheets with.
25
+ * React orders the precedences in `<head>` as each is first asked for, and
26
+ * puts a stylesheet loaded later after the last of its own; asked for first,
27
+ * this keeps the Server Components' stylesheets before the client
28
+ * components'. Under mode: 'static' it carries no nonce, and the build names
29
+ * it by hash where the policy decides a style element.
30
+ */
31
+ const STYLESHEET_ORDER_HREF = "k8ordo-stylesheet-order";
32
+ /** The precedence the RSC plugin links a Server Component's stylesheet with. */
33
+ const SERVER_STYLESHEETS = "vite-rsc/importer-resources";
34
+ /**
23
35
  * Said by the handler under mode: 'static' alone, on a shell's HTML and
24
36
  * payload: the pattern whose fallback.tsx rendered it. The table walks in its
25
37
  * own order, so a shell pathname can be answered by another pattern than the
26
38
  * one the build asked for, and the build compares instead of guessing.
27
39
  */
28
40
  const SHELL_HEADER = "x-k8ordo-shell";
41
+ /**
42
+ * Said by the handler under mode: 'static' alone, on a page's HTML: every
43
+ * client component the payload it rendered names (`clientDepsHeader`) — what
44
+ * the HTML render was handed to link — which the build checks the HTML
45
+ * links.
46
+ */
47
+ const CLIENT_DEPS_HEADER = "x-k8ordo-client-deps";
48
+ /**
49
+ * The value of `CLIENT_DEPS_HEADER`. Encoded, because a header's value is
50
+ * bytes, and a chunk is named after a module, whose name need not be ASCII.
51
+ */
52
+ const clientDepsHeader = (named) => encodeURIComponent(JSON.stringify([...named]));
53
+ /** What `clientDepsHeader` said. */
54
+ const readClientDeps = (value) => JSON.parse(decodeURIComponent(value));
29
55
  //#endregion
30
- export { ACTION_ID_HEADER, NONCE_HEADER, NOT_FOUND_DIGEST, NOT_FOUND_HEADER, SHELL_HEADER };
56
+ export { ACTION_ID_HEADER, CLIENT_DEPS_HEADER, NONCE_HEADER, NOT_FOUND_DIGEST, NOT_FOUND_HEADER, SERVER_STYLESHEETS, SHELL_HEADER, STYLESHEET_ORDER_HREF, clientDepsHeader, readClientDeps };
@@ -0,0 +1,4 @@
1
+ import { Context } from "react";
2
+ //#region src/runtime/tree-pathname.d.ts
3
+ export declare const TreePathname: Context<string | null>;
4
+ //#endregion
@@ -0,0 +1,12 @@
1
+ "use client";
2
+ import { createContext } from "react";
3
+ //#region src/runtime/tree-pathname.ts
4
+ /**
5
+ * `@k8ordo/router`'s context for the pathname each tree was applied for,
6
+ * which `<Router>` provides and `@k8ordo/state` reads to keep a page state's
7
+ * values with the tree on screen. `AppRouter` provides it the same way.
8
+ */
9
+ const KEY = Symbol.for("@k8ordo/router/tree-pathname");
10
+ const TreePathname = globalThis[KEY] ??= createContext(null);
11
+ //#endregion
12
+ export { TreePathname };
package/dist/vite.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { _ as pagePathFor, a as cloudflareCounts, b as NOT_FOUND_SEGMENT, c as rewriteFor, d as ENCODINGS, f as SUFFIX, g as isPayloadPath, i as builtRules, l as rulesOf, n as resolveStatic, o as cloudflareMatches, p as isCompressible, s as formatRedirects, t as readRules, u as shellRules, v as payloadPathFor, x as decodePathname, y as FALLBACK_SEGMENT } from "./static-host-dgtttTuZ.mjs";
2
2
  import { t as sharedDir } from "./shared-dir-CkF4QCWc.mjs";
3
- import { findPackageJSON } from "node:module";
3
+ import { createRequire, findPackageJSON } from "node:module";
4
4
  import { normalizePathname, withBase, withoutBase } from "@k8ordo/router";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
@@ -890,12 +890,31 @@ const NOT_FOUND_HEADER = "x-k8ordo-not-found";
890
890
  */
891
891
  const NONCE_HEADER = "x-k8ordo-nonce";
892
892
  /**
893
+ * The `href` of the one `<style>` the HTML render writes itself, empty, under
894
+ * the precedence the RSC plugin links a Server Component's stylesheets with.
895
+ * React orders the precedences in `<head>` as each is first asked for, and
896
+ * puts a stylesheet loaded later after the last of its own; asked for first,
897
+ * this keeps the Server Components' stylesheets before the client
898
+ * components'. Under mode: 'static' it carries no nonce, and the build names
899
+ * it by hash where the policy decides a style element.
900
+ */
901
+ const STYLESHEET_ORDER_HREF = "k8ordo-stylesheet-order";
902
+ /**
893
903
  * Said by the handler under mode: 'static' alone, on a shell's HTML and
894
904
  * payload: the pattern whose fallback.tsx rendered it. The table walks in its
895
905
  * own order, so a shell pathname can be answered by another pattern than the
896
906
  * one the build asked for, and the build compares instead of guessing.
897
907
  */
898
908
  const SHELL_HEADER = "x-k8ordo-shell";
909
+ /**
910
+ * Said by the handler under mode: 'static' alone, on a page's HTML: every
911
+ * client component the payload it rendered names (`clientDepsHeader`) — what
912
+ * the HTML render was handed to link — which the build checks the HTML
913
+ * links.
914
+ */
915
+ const CLIENT_DEPS_HEADER = "x-k8ordo-client-deps";
916
+ /** What `clientDepsHeader` said. */
917
+ const readClientDeps = (value) => JSON.parse(decodeURIComponent(value));
899
918
  //#endregion
900
919
  //#region ../framework-engine/dist/generate/write.mjs
901
920
  /** The filesystem edge: everything below it is a pure function of this list. */
@@ -1112,6 +1131,22 @@ const CLIENT_UNBUNDLED = [
1112
1131
  */
1113
1132
  const FAMILY = /^@k8ordo\//u;
1114
1133
  /**
1134
+ * The client-reference groups of the RSC entry's own chunk: the client
1135
+ * components of every layout, error and loading file, which the table
1136
+ * imports with the entry, and the framework's own boundaries. Every page
1137
+ * renders some of them, so every page loads their chunk. Read off the RSC
1138
+ * plugin's manager — experimental, as `server-actions.ts` says — once the
1139
+ * client build has loaded the reference groups: the RSC build ran first and
1140
+ * grouped its references by the RSC chunk they are in.
1141
+ */
1142
+ const frameGroupsOf = (config) => {
1143
+ const manager = getPluginApi(config)?.manager;
1144
+ const entry = Object.values(manager?.bundles.rsc ?? {}).find((output) => output.type === "chunk" && output.isEntry);
1145
+ if (manager === void 0 || entry?.type !== "chunk") return [];
1146
+ const inEntry = new Set(entry.moduleIds);
1147
+ return [...new Set(Object.entries(manager.clientReferenceMetaMap).flatMap(([id, meta]) => inEntry.has(id) && meta.groupChunkId !== void 0 ? [meta.groupChunkId] : []))];
1148
+ };
1149
+ /**
1115
1150
  * The machinery both modes stand on: the route grammar compiled into a
1116
1151
  * table, the RSC pipeline configured, and the execution boundary enforced.
1117
1152
  * The framework's static and server modes add only what makes them
@@ -1125,6 +1160,7 @@ const engine = (options, host) => {
1125
1160
  let logger;
1126
1161
  let devServer;
1127
1162
  let generating = Promise.resolve();
1163
+ const frame = /* @__PURE__ */ new Set();
1128
1164
  const runtime = (name) => path.join(host.runtimeDir, `${name}.mjs`);
1129
1165
  const routesModule = () => path.join(outDir, "routes.gen.ts");
1130
1166
  const generateOptions = () => ({
@@ -1172,7 +1208,18 @@ const engine = (options, host) => {
1172
1208
  include: CLIENT_DEPS,
1173
1209
  exclude: CLIENT_UNBUNDLED
1174
1210
  },
1175
- build: { rolldownOptions: { input: { index: runtime("entry.browser") } } }
1211
+ build: { rolldownOptions: {
1212
+ input: { index: runtime("entry.browser") },
1213
+ output: { codeSplitting: { groups: [{
1214
+ name: "index",
1215
+ tags: ["$initial"],
1216
+ priority: 2
1217
+ }, {
1218
+ name: "frame",
1219
+ test: (id) => frame.has(id),
1220
+ priority: 1
1221
+ }] } }
1222
+ } }
1176
1223
  }
1177
1224
  }
1178
1225
  };
@@ -1209,6 +1256,11 @@ const engine = (options, host) => {
1209
1256
  async buildStart() {
1210
1257
  await api.generate();
1211
1258
  },
1259
+ buildEnd() {
1260
+ if (this.environment.name !== "client") return;
1261
+ frame.clear();
1262
+ for (const group of frameGroupsOf(this.environment.config)) frame.add(group);
1263
+ },
1212
1264
  configureServer(server) {
1213
1265
  server.watcher.add(routesDir);
1214
1266
  devServer = server;
@@ -1435,6 +1487,22 @@ const elementDirectivesOf = (policy) => {
1435
1487
  return [...elements === void 0 ? [] : [["script-src-elem", elements]], ...scripts === null ? [] : [scripts]];
1436
1488
  };
1437
1489
  /**
1490
+ * What decides a style element: `style-src-elem`, `style-src`, or
1491
+ * `default-src` without either.
1492
+ */
1493
+ const styleElementDirectiveOf = (policy) => {
1494
+ for (const name of [
1495
+ "style-src-elem",
1496
+ "style-src",
1497
+ "default-src"
1498
+ ]) {
1499
+ const sources = policy[name];
1500
+ if (sources !== void 0) return [name, sources];
1501
+ }
1502
+ return null;
1503
+ };
1504
+ const allowsInline = (sources) => sources.includes("'unsafe-inline'") && !sources.some((source) => /^'(?:nonce|sha256|sha384|sha512)-/u.test(source));
1505
+ /**
1438
1506
  * What would make a policy wrong to write into every page, named at once:
1439
1507
  * a directive that works only from a header, a source that is not one, and
1440
1508
  * `'strict-dynamic'`, under which the framework's module script — allowed by
@@ -1452,6 +1520,7 @@ const policyProblems = (policy) => {
1452
1520
  return problems;
1453
1521
  };
1454
1522
  const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script[\s/>]/giu;
1523
+ const ORDER_STYLE = new RegExp(`<style\\b[^>]*\\sdata-href="${STYLESHEET_ORDER_HREF}"[^>]*>([^<]*)</style>`, "u");
1455
1524
  const hashOf = (source) => `'sha256-${createHash("sha256").update(source.replaceAll("\r\n", "\n").replaceAll("\r", "\n")).digest("base64")}'`;
1456
1525
  /**
1457
1526
  * The policy as the page's `<meta>` says it: the application's directives,
@@ -1459,14 +1528,23 @@ const hashOf = (source) => `'sha256-${createHash("sha256").update(source.replace
1459
1528
  * `script-src-elem` when given, which overrides the rest for elements, and
1460
1529
  * `script-src`, made from `default-src` when only that was given (hashes
1461
1530
  * there would also turn off `'unsafe-inline'` for styles). None of them
1462
- * given, scripts are not restricted, and nothing is added.
1531
+ * given, scripts are not restricted, and nothing is added. The style hash
1532
+ * goes where a style element is decided, made into `style-src` from
1533
+ * `default-src` likewise, and only where the policy would refuse the style:
1534
+ * beside an `'unsafe-inline'` that allows it, a hash would turn it off for
1535
+ * every style attribute too.
1463
1536
  */
1464
- const serialize = (policy, hashes) => {
1537
+ const serialize = (policy, hashes, styleHash) => {
1465
1538
  const directives = new Map(Object.entries(policy));
1466
1539
  if (hashes.length > 0) for (const [name, sources] of elementDirectivesOf(policy)) {
1467
1540
  const into = name === "default-src" ? "script-src" : name;
1468
1541
  directives.set(into, [...sources, ...hashes]);
1469
1542
  }
1543
+ const styles = styleElementDirectiveOf(policy);
1544
+ if (styleHash !== null && styles !== null && !allowsInline(styles[1])) {
1545
+ const [name, sources] = styles;
1546
+ directives.set(name === "default-src" ? "style-src" : name, [...sources, styleHash]);
1547
+ }
1470
1548
  return [...directives].map(([name, sources]) => [name, ...sources].join(" ")).join("; ");
1471
1549
  };
1472
1550
  /**
@@ -1474,9 +1552,10 @@ const serialize = (policy, hashes) => {
1474
1552
  * — the payload, React's — with a nonce, and a file cannot carry one:
1475
1553
  * everyone reads the same file, so the nonce is taken off. With a policy,
1476
1554
  * what it signed is named by hash instead, in a `<meta>` ahead of everything
1477
- * the page loads; an inline script of the application's is the
1478
- * application's to allow, by its hash in that policy, and one that reached
1479
- * the page from content is refused.
1555
+ * the page loads, and so is the framework's one `<style>`, which keeps the
1556
+ * Server Components' stylesheets first; an inline script of the
1557
+ * application's is the application's to allow, by its hash in that policy,
1558
+ * and one that reached the page from content is refused.
1480
1559
  */
1481
1560
  const asFile = (html, nonce, policy) => {
1482
1561
  const signed = ` nonce="${nonce}"`;
@@ -1486,10 +1565,142 @@ const asFile = (html, nonce, policy) => {
1486
1565
  for (const [, attributes = "", source = ""] of html.matchAll(SCRIPT)) if (attributes.includes(signed) && !/\ssrc=/u.test(attributes)) hashes.add(hashOf(source));
1487
1566
  const head = /<head(?:\s[^>]*)?>/u.exec(unsigned);
1488
1567
  if (head === null) throw new Error("the \"csp\" option needs a <head> to put its <meta> in, and this page has none");
1568
+ const order = ORDER_STYLE.exec(unsigned);
1569
+ const styleHash = order === null ? null : hashOf(order[1] ?? "");
1489
1570
  const at = head.index + head[0].length;
1490
- const meta = `<meta http-equiv="Content-Security-Policy" content="${escapeMarkup(serialize(policy, [...hashes]))}">`;
1571
+ const meta = `<meta http-equiv="Content-Security-Policy" content="${escapeMarkup(serialize(policy, [...hashes], styleHash))}">`;
1491
1572
  return `${unsigned.slice(0, at)}${meta}${unsigned.slice(at)}`;
1492
1573
  };
1574
+ /**
1575
+ * What ends a tag's name in HTML: `<\/script` followed by anything else is
1576
+ * still the script's text.
1577
+ */
1578
+ const ENDS_TAG_NAME = /* @__PURE__ */ new Set([
1579
+ " ",
1580
+ "\n",
1581
+ "\f",
1582
+ "\r",
1583
+ " ",
1584
+ "/",
1585
+ ">"
1586
+ ]);
1587
+ /** Where the next `<script` or `<\/script` tag starts, in any case. */
1588
+ const tagAt = (html, tag, from) => {
1589
+ for (let at = html.indexOf("<", from); at !== -1; at = html.indexOf("<", at + 1)) if (html.slice(at, at + tag.length).toLowerCase() === tag && ENDS_TAG_NAME.has(html.charAt(at + tag.length))) return at;
1590
+ return -1;
1591
+ };
1592
+ /**
1593
+ * The HTML outside its script elements, in the order it is written — what a
1594
+ * layout wrote into the page, not the payload the page hydrates from. Scanned
1595
+ * rather than stripped with a pattern: an end tag may be `<\/SCRIPT >`, and a
1596
+ * pattern that misses one swallows the page up to the next script's.
1597
+ */
1598
+ const writtenOutsideScripts = (html) => {
1599
+ const written = [];
1600
+ for (let from = 0;;) {
1601
+ const open = tagAt(html, "<script", from);
1602
+ written.push(open === -1 ? html.slice(from) : html.slice(from, open));
1603
+ if (open === -1) return written;
1604
+ const close = tagAt(html, "<\/script", open + 1);
1605
+ if (close === -1) return written;
1606
+ const end = html.indexOf(">", close);
1607
+ if (end === -1) return written;
1608
+ from = end + 1;
1609
+ }
1610
+ };
1611
+ const REFERENCE = /&(?:amp|lt|gt|quot|#x27);/gu;
1612
+ const REFERENCED = /* @__PURE__ */ new Map([
1613
+ ["&amp;", "&"],
1614
+ ["&lt;", "<"],
1615
+ ["&gt;", ">"],
1616
+ ["&quot;", "\""],
1617
+ ["&#x27;", "'"]
1618
+ ]);
1619
+ const attributeOf = (tag, name) => new RegExp(`\\s${name}="([^"]*)"`, "u").exec(tag)?.[1]?.replaceAll(REFERENCE, (reference) => REFERENCED.get(reference) ?? "");
1620
+ /**
1621
+ * What of the client components a page's payload names its HTML does not
1622
+ * link: a stylesheet not linked as one in `<head>`, a script neither
1623
+ * preloaded as a module there nor loaded by a `<script>` — by component,
1624
+ * only those missing something. A `<link>` written into a script's text, or
1625
+ * into `<body>`, links nothing before the page has run; React hoists every
1626
+ * resource of a page it waited for into `<head>`. With no `</head>`, the
1627
+ * whole document is its head.
1628
+ */
1629
+ const unlinkedDeps = (html, named) => {
1630
+ const outside = writtenOutsideScripts(html).join("");
1631
+ const end = outside.indexOf("</head>");
1632
+ const head = end === -1 ? outside : outside.slice(0, end);
1633
+ const stylesheets = /* @__PURE__ */ new Set();
1634
+ const modules = /* @__PURE__ */ new Set();
1635
+ for (const [tag] of head.matchAll(/<link\b[^>]*>/gu)) {
1636
+ const href = attributeOf(tag, "href");
1637
+ if (href === void 0) continue;
1638
+ const rel = attributeOf(tag, "rel");
1639
+ if (rel === "stylesheet") stylesheets.add(href);
1640
+ if (rel === "modulepreload") modules.add(href);
1641
+ }
1642
+ for (const [, attributes = ""] of html.matchAll(SCRIPT)) {
1643
+ const src = attributeOf(attributes, "src");
1644
+ if (src !== void 0) modules.add(src);
1645
+ }
1646
+ return named.map((component) => ({
1647
+ ...component,
1648
+ js: component.js.filter((href) => !modules.has(href)),
1649
+ css: component.css.filter((href) => !stylesheets.has(href))
1650
+ })).filter(({ js, css }) => js.length > 0 || css.length > 0);
1651
+ };
1652
+ const counting = (count, one, many) => `${String(count)} ${count === 1 ? one : many}`;
1653
+ /** How many files the message names, before it counts the rest. */
1654
+ const LISTED = 20;
1655
+ /** How many pages a file's line names, before it counts the rest. */
1656
+ const EXAMPLES = 3;
1657
+ const pagesOf = (pages) => {
1658
+ const sorted = [...pages].toSorted();
1659
+ const named = sorted.slice(0, EXAMPLES).join(", ");
1660
+ return `${counting(sorted.length, "page", "pages")} (${sorted.length > EXAMPLES ? `${named}, …` : named})`;
1661
+ };
1662
+ /**
1663
+ * The error a static build stops with when HTML it wrote does not link
1664
+ * what the client components its payload names need: `unlinked` holds, by
1665
+ * page (its pathname, `404.html`, a shell's location), what each component
1666
+ * misses, or `null` when the handler did not say; `report` asks for the
1667
+ * report. Each file is named once, with how many pages miss it, a few of
1668
+ * them and a component that needs it, the files most pages miss first and
1669
+ * only so many: a component's files include what the client entry loads,
1670
+ * so a failure across the site would otherwise repeat the same files for
1671
+ * every page and component, past what a report can carry.
1672
+ */
1673
+ const unlinkedMessage = (unlinked, report) => {
1674
+ const unsaid = [];
1675
+ const missed = /* @__PURE__ */ new Map();
1676
+ for (const [page, components] of unlinked) {
1677
+ if (components === null) {
1678
+ unsaid.push(page);
1679
+ continue;
1680
+ }
1681
+ for (const { id, name, js, css } of components) for (const file of [...css, ...js]) {
1682
+ const by = missed.get(file) ?? {
1683
+ pages: /* @__PURE__ */ new Set(),
1684
+ components: /* @__PURE__ */ new Map()
1685
+ };
1686
+ by.pages.add(page);
1687
+ by.components.set(`${id}#${name}`, name);
1688
+ missed.set(file, by);
1689
+ }
1690
+ }
1691
+ const files = [...missed].toSorted(([a, { pages: x }], [b, { pages: y }]) => y.size - x.size || (a < b ? -1 : 1));
1692
+ const components = new Set(files.flatMap(([, { components: needing }]) => [...needing.keys()]));
1693
+ return [
1694
+ `static build wrote HTML that does not link everything the client components its payload names need: ${[...files.length > 0 ? [`${counting(unlinked.size - unsaid.length, "HTML file misses", "HTML files miss")} ${counting(files.length, "file", "files")} of ${counting(components.size, "component", "components")}`] : [], ...unsaid.length > 0 ? [`the handler did not say what the payload of ${counting(unsaid.length, "HTML file", "HTML files")} names`] : []].join(", and ")}`,
1695
+ report,
1696
+ ...unsaid.length > 0 ? [` ${pagesOf(unsaid)} — the handler did not say what its payload names`] : [],
1697
+ ...files.slice(0, LISTED).map(([file, { pages, components: needing }]) => {
1698
+ const [first = "", ...others] = [...needing.values()].toSorted();
1699
+ return ` ${file} — ${pagesOf(pages)}, for ${first}${others.length > 0 ? ` and ${String(others.length)} more` : ""}`;
1700
+ }),
1701
+ ...files.length > LISTED ? [` … and ${counting(files.length - LISTED, "more file", "more files")}`] : []
1702
+ ].join("\n");
1703
+ };
1493
1704
  //#endregion
1494
1705
  //#region src/paths.ts
1495
1706
  /**
@@ -1791,42 +2002,6 @@ const NO_SHELLS = {
1791
2002
  paths: /* @__PURE__ */ new Set(),
1792
2003
  shells: []
1793
2004
  };
1794
- /**
1795
- * What ends a tag's name in HTML: `<\/script` followed by anything else is
1796
- * still the script's text.
1797
- */
1798
- const ENDS_TAG_NAME = /* @__PURE__ */ new Set([
1799
- " ",
1800
- "\n",
1801
- "\f",
1802
- "\r",
1803
- " ",
1804
- "/",
1805
- ">"
1806
- ]);
1807
- /** Where the next `<script` or `<\/script` tag starts, in any case. */
1808
- const tagAt = (html, tag, from) => {
1809
- for (let at = html.indexOf("<", from); at !== -1; at = html.indexOf("<", at + 1)) if (html.slice(at, at + tag.length).toLowerCase() === tag && ENDS_TAG_NAME.has(html.charAt(at + tag.length))) return at;
1810
- return -1;
1811
- };
1812
- /**
1813
- * Whether `text` is in the HTML outside its script elements — what a layout
1814
- * wrote into the page, not the payload the page hydrates from. Scanned rather
1815
- * than stripped with a pattern: an end tag may be `<\/SCRIPT >`, and a pattern
1816
- * that misses one swallows the page up to the next script's.
1817
- */
1818
- const outsideScripts = (html, text) => {
1819
- for (let from = 0;;) {
1820
- const open = tagAt(html, "<script", from);
1821
- if ((open === -1 ? html.slice(from) : html.slice(from, open)).includes(text)) return true;
1822
- if (open === -1) return false;
1823
- const close = tagAt(html, "<\/script", open + 1);
1824
- if (close === -1) return false;
1825
- const end = html.indexOf(">", close);
1826
- if (end === -1) return false;
1827
- from = end + 1;
1828
- }
1829
- };
1830
2005
  /** Every file below a directory, relative to it, POSIX separators. */
1831
2006
  const filesBelow = async (dir) => (await readdir(dir, {
1832
2007
  recursive: true,
@@ -2148,6 +2323,10 @@ const staticMode = (options) => {
2148
2323
  const failed = [];
2149
2324
  const redirected = /* @__PURE__ */ new Set();
2150
2325
  const unanswered = [];
2326
+ const unlinkedPages = /* @__PURE__ */ new Map();
2327
+ const unlinks = (page, missing) => {
2328
+ if (missing === null || missing.length > 0) unlinkedPages.set(page, missing);
2329
+ };
2151
2330
  const types = /* @__PURE__ */ new Map();
2152
2331
  await inParallel(plan.paths.flatMap((pathname) => {
2153
2332
  if (byRoute.has(pathname)) return [async () => {
@@ -2158,7 +2337,8 @@ const staticMode = (options) => {
2158
2337
  }];
2159
2338
  const dir = path.join(clientDir, dirFor(pathname));
2160
2339
  return [async () => {
2161
- const { status, notFound } = await write(path.join(dir, "index.html"), handler, urlFor(pathname), csp, { notFoundIsPage: false });
2340
+ const { status, notFound, unlinked } = await write(path.join(dir, "index.html"), handler, urlFor(pathname), csp, { notFoundIsPage: false });
2341
+ unlinks(pathname, unlinked);
2162
2342
  if (status === 404) (notFound ? disowned : refused).push(pathname);
2163
2343
  if (status === 500) failed.push(pathname);
2164
2344
  if (status === 307 || status === 308) redirected.add(pathname);
@@ -2167,7 +2347,8 @@ const staticMode = (options) => {
2167
2347
  }));
2168
2348
  const unmatched = catchAllPath(tree);
2169
2349
  if (unmatched !== null) {
2170
- const { status } = await write(path.join(clientDir, "404.html"), handler, urlFor(unmatched), csp, { notFoundIsPage: true });
2350
+ const { status, unlinked } = await write(path.join(clientDir, "404.html"), handler, urlFor(unmatched), csp, { notFoundIsPage: true });
2351
+ unlinks("404.html", unlinked);
2171
2352
  if (status === 500) failed.push("404.html");
2172
2353
  }
2173
2354
  const fallbacks = new Map(fallbackShapes(tree).map((shape) => [shape.pattern, shape.file]));
@@ -2181,6 +2362,7 @@ const staticMode = (options) => {
2181
2362
  shell: shell.pattern
2182
2363
  });
2183
2364
  const named = `${shell.location} (${fallbacks.get(shell.pattern) ?? ""})`;
2365
+ unlinks(shell.location, answered.unlinked);
2184
2366
  if (answered.status === 500) failed.push(shell.location);
2185
2367
  else if (answered.status === 404) (answered.notFound ? shellDisowned : shellRefused).push(shell.location);
2186
2368
  else if (answered.shell === null) shellTaken.push(`the shell for ${named} was answered by another route, which took "${FALLBACK_SEGMENT}" as a value`);
@@ -2192,6 +2374,7 @@ const staticMode = (options) => {
2192
2374
  }));
2193
2375
  const unwritten = [
2194
2376
  ...failed.length > 0 ? [`static build could not render ${failed.toSorted().join(", ")} — see the error above`] : [],
2377
+ ...unlinkedPages.size > 0 ? [unlinkedMessage(unlinkedPages, bugReport())] : [],
2195
2378
  ...unanswered.length > 0 ? [`static build writes a route.ts from a GET that answers 200, and these did not: ${unanswered.toSorted().join(", ")}`] : [],
2196
2379
  ...refused.length > 0 ? [`the "paths" option supplied pathnames a params schema refused: ${refused.toSorted().join(", ")}`] : [],
2197
2380
  ...disowned.length > 0 ? [`the "paths" option supplied pathnames whose page called notFound(): ${disowned.toSorted().join(", ")}`] : [],
@@ -2202,7 +2385,7 @@ const staticMode = (options) => {
2202
2385
  if (unwritten.length > 0) throw new Error(unwritten.join("\n\n"));
2203
2386
  const leaking = await Promise.all(plan.shells.map(async (shell) => {
2204
2387
  const html = await readFile(path.join(clientDir, dirFor(shell.pathname), "index.html"), "utf8");
2205
- return outsideScripts(html, "!fallback") ? [shell.location] : [];
2388
+ return writtenOutsideScripts(html).some((written) => written.includes("!fallback")) ? [shell.location] : [];
2206
2389
  }));
2207
2390
  for (const location of leaking.flat()) builder.config.logger.warn(`k8ordo: the shell for ${location} has "${FALLBACK_SEGMENT}" in its HTML — a layout wrote the shell's pathname into the page (a link, a canonical URL); derive what depends on the URL in a client component`);
2208
2391
  if (options.site !== void 0) await writeFile(path.join(clientDir, "sitemap.xml"), sitemap(options.site, plan.paths.filter((pathname) => !redirected.has(pathname) && !byRoute.has(pathname)).map((pathname) => withBase(pathname, base))));
@@ -2230,6 +2413,22 @@ const staticMode = (options) => {
2230
2413
  }];
2231
2414
  };
2232
2415
  /**
2416
+ * Where a bug in the HTML is reported, and what the report names: this
2417
+ * package, and the React that rendered the HTML — a peer, whichever version
2418
+ * the application installed.
2419
+ */
2420
+ const bugReport = () => {
2421
+ const required = createRequire(import.meta.url);
2422
+ const manifestOf = (name) => required(`${name}/package.json`);
2423
+ const { bugs } = manifestOf("@k8ordo/framework");
2424
+ const versions = [
2425
+ "@k8ordo/framework",
2426
+ "react",
2427
+ "react-dom"
2428
+ ].map((name) => `${name} ${String(manifestOf(name).version)}`);
2429
+ return `This is a bug in @k8ordo/framework, not in this application: report it at ${bugs.url} with this message (${versions.join(", ")})`;
2430
+ };
2431
+ /**
2233
2432
  * A render is a whole page: components, their data, and whatever the app's
2234
2433
  * own highlighting or markdown does. Starting every one of them at once ties
2235
2434
  * peak memory to the size of the site, which is the number that grows. A
@@ -2256,7 +2455,8 @@ const write = async (file, handler, url, csp, { notFoundIsPage, shell }) => {
2256
2455
  const written = {
2257
2456
  status: response.status,
2258
2457
  notFound,
2259
- shell: answered
2458
+ shell: answered,
2459
+ unlinked: []
2260
2460
  };
2261
2461
  if (response.status === 500) {
2262
2462
  console.error(`k8ordo: ${url} — ${await response.text()}`);
@@ -2271,9 +2471,17 @@ const write = async (file, handler, url, csp, { notFoundIsPage, shell }) => {
2271
2471
  return written;
2272
2472
  }
2273
2473
  const nonce = response.headers.get(NONCE_HEADER);
2274
- if (nonce === null) await writeFile(file, Buffer.from(await response.arrayBuffer()));
2275
- else await writeFile(file, asFile(await response.text(), nonce, csp));
2276
- return written;
2474
+ if (nonce === null) {
2475
+ await writeFile(file, Buffer.from(await response.arrayBuffer()));
2476
+ return written;
2477
+ }
2478
+ const html = asFile(await response.text(), nonce, csp);
2479
+ await writeFile(file, html);
2480
+ const named = response.headers.get(CLIENT_DEPS_HEADER);
2481
+ return {
2482
+ ...written,
2483
+ unlinked: named === null ? null : unlinkedDeps(html, readClientDeps(named))
2484
+ };
2277
2485
  };
2278
2486
  /**
2279
2487
  * Writes what a route.ts's GET answered, as the file at its pathname, and
package/docs/llms.txt CHANGED
@@ -60,8 +60,12 @@ Start with GUIDE.md, then follow the reference most relevant to the task.
60
60
 
61
61
  - [Routing](references/routing.md): the `routes/` grammar and every refusal
62
62
  the build names, where a `fallback.tsx` may sit, how a page is sent in
63
- each mode (each page loads only its own client components and CSS, and
64
- the browser renders once they have loaded), `loading.tsx`, `route.ts` (methods and `405` under server
63
+ each mode (each page loads only its own client components and CSS, what
64
+ every page loads comes in at most two files — the entry's and the frame's,
65
+ which sets the client build's `codeSplitting` — and the browser renders
66
+ once they have loaded; Server Components' stylesheets
67
+ come before client components', and a stylesheet once loaded stays),
68
+ `loading.tsx`, `route.ts` (methods and `405` under server
65
69
  mode, a file under static mode), the generated `.k8ordo/` files (the
66
70
  route table, and the `Register`s: the table's, and `@k8ordo/i18n`'s when
67
71
  `src/i18n.ts` exports `locales` by name) and `k8ordo generate`, which
@@ -94,9 +98,9 @@ Start with GUIDE.md, then follow the reference most relevant to the task.
94
98
  `responseHeaders()`, `cookies()` and its defaults, and the read-only
95
99
  `request` a page receives.
96
100
  - [Content Security Policy](references/csp.md): `nonce()` in a header a
97
- guard writes under server mode; the `csp` option and
98
- `colorSchemeScriptHash()` under static mode, and `connect-src` for the
99
- data a `fallback.tsx`'s shell fetches.
101
+ guard writes under server mode, in `style-src` too for the framework's
102
+ one `<style>`; the `csp` option and `colorSchemeScriptHash()` under static
103
+ mode, and `connect-src` for the data a `fallback.tsx`'s shell fetches.
100
104
  - [Running and deploying](references/deploy.md): a static build's
101
105
  `dist/client/` (HTML, `index.rsc` payloads, shells, `404.html`,
102
106
  `sitemap.xml`, `_redirects`), the rewrites that reach a shell on Netlify,
@@ -113,7 +113,8 @@ const [{ q }, update] = useAppState(listState, ['q']);
113
113
 
114
114
  Changing the search does not change the page: the router leaves the route tree
115
115
  alone, nothing remounts, and the scroll position stays where the reader left
116
- it.
116
+ it. Going back or forward to an entry with another search restores the
117
+ position that entry was left at, as for any other entry.
117
118
 
118
119
  A page never sees the search: `useAppState` reads it in the browser, so a
119
120
  server render shows the url slot's defaults and the live URL takes over on
@@ -149,7 +150,9 @@ It receives that slot, parsed as `listState.parseUrl` parses it, as `search`
149
150
  component's `useAppState` as `initialUrl`, so the first render agrees with
150
151
  the URL. Because the page is rendered for the search it was given, a
151
152
  navigation that moves the search loads it again, in place: no scroll, no
152
- focus reset, nothing remounted. The generated table reads it through
153
+ focus reset, nothing remounted — but for going back or forward, where the
154
+ browser restores the position that entry was left at once the page loaded
155
+ again is on screen. The generated table reads it through
153
156
  `@k8ordo/state`, so the application depends on that. A layout never
154
157
  receives it.
155
158
 
@@ -2,7 +2,10 @@
2
2
 
3
3
  The framework decides no policy. It signs the inline scripts it writes
4
4
  itself — the payload it puts into the HTML for hydration, and React's own —
5
- and the policy that names them is the application's to write. An inline
5
+ and the one `<style>` it writes into `<head>`, empty, which keeps the
6
+ Server Components' stylesheets before the client components'
7
+ ([How a page is sent](routing.md#how-a-page-is-sent)); the policy that names
8
+ them is the application's to write. An inline
6
9
  script of the application's own, `@k8ordo/color-scheme`'s among them, is the
7
10
  application's to allow the same way.
8
11
 
@@ -53,6 +56,22 @@ under a policy without it every page load logs an error saying so. A
53
56
  production build never calls it, and `import.meta.env.DEV` keeps the source
54
57
  out of it.
55
58
 
59
+ The framework's `<style>` carries the nonce too, so a policy that restricts
60
+ styles names it in `style-src` as well. `vite dev` adds each stylesheet as a
61
+ `<style>` of its own, which nothing signs, so allow `'unsafe-inline'` there
62
+ instead — beside a nonce it would be ignored:
63
+
64
+ ```ts
65
+ const styles = import.meta.env.DEV
66
+ ? "'self' 'unsafe-inline'"
67
+ : `'self' 'nonce-${nonce()}'`;
68
+ ```
69
+
70
+ React, signing styles with the nonce, writes a `<style>` with `href` and
71
+ `precedence` into the HTML only when it carries the same nonce: give one a
72
+ Server Component renders `nonce={nonce()}`. One a client component renders
73
+ cannot read it, and is left out of the HTML.
74
+
56
75
  ## Static mode: hashes in a `<meta>`
57
76
 
58
77
  Static mode only. A file cannot carry a nonce — everyone reads the same
@@ -84,6 +103,12 @@ export default defineConfig({
84
103
  });
85
104
  ```
86
105
 
106
+ The framework's empty `<style>` is named by hash the same way, wherever a
107
+ style element is decided — `style-src-elem`, `style-src`, or `style-src`
108
+ made from `default-src` — unless the policy lets it in already with
109
+ `'unsafe-inline'`: a hash beside that would turn `'unsafe-inline'` off for
110
+ every `style` attribute as well.
111
+
87
112
  An inline script of the application's is allowed by its hash in that policy,
88
113
  as `colorSchemeScriptHash()` gives `@k8ordo/color-scheme`'s (pass it the
89
114
  `defaultPreference` the provider is given); any other inline script on the
@@ -100,7 +125,9 @@ a script element — `script-src` (`default-src` without it) and
100
125
  `script-src-elem` — allow `'self'` and `'unsafe-inline'` with no hash or
101
126
  nonce beside them (either turns `'unsafe-inline'` off), and keep `csp`,
102
127
  without `report-to`, for the `<meta>`, which allows inline scripts only by
103
- hash. Without `csp`, no policy is written. There is no `nonce()` for this
128
+ hash. The `<style>`'s hash is the same on every page —
129
+ `'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='`, an empty one's —
130
+ so a header that restricts styles can name it. Without `csp`, no policy is written. There is no `nonce()` for this
104
131
  mode: what an application signed with it would land in the file, and make
105
132
  every build differ.
106
133
 
@@ -57,6 +57,40 @@ above it, and the file is written; with none, it stops the build the same
57
57
  way. `error.tsx` under this mode is for what fails in the browser: a client
58
58
  component, after hydration.
59
59
 
60
+ The build also checks every HTML file it writes — each page, `404.html` and
61
+ each shell — against the client components its payload names: each one's
62
+ stylesheets have to be linked in `<head>` (`<link rel="stylesheet">`), and
63
+ its scripts preloaded there (`<link rel="modulepreload">`) or loaded by a
64
+ `<script>`. Without them, what the browser needs for those components is
65
+ asked for only once the page's script runs: a component the page renders
66
+ shows unstyled until then, and hydration waits a round trip longer. A file
67
+ that misses one stops the build once every file is written. The error
68
+ counts the HTML files, the files they miss and the components that need
69
+ them, asks for a report, then names each missing file once, those most
70
+ pages miss first and 20 at most: how many pages miss it, a few of them
71
+ (`404.html` for the not-found, a shell by its location), and a component
72
+ that needs it, by its export's name (`default` for a default export):
73
+
74
+ ```
75
+ static build wrote HTML that does not link everything the client components its payload names need: 2 HTML files miss 3 files of 2 components
76
+ This is a bug in @k8ordo/framework, not in this application: report it at https://github.com/k35o/k8ordo/issues with this message (@k8ordo/framework 1.2.2, react 19.3.1, react-dom 19.3.1)
77
+ /assets/Icon-MOWHoEeM.js — 1 page (/), for default
78
+ /assets/not-found-C2TfACgz.css — 1 page (404.html), for NotFound
79
+ /assets/not-found-xxQ43iW3.js — 1 page (404.html), for NotFound
80
+ ```
81
+
82
+ The framework has React write every one of those links as it renders the
83
+ page, whatever its components hold or render, so a file the error names is
84
+ a bug in k8ordo or in the React that wrote the HTML, not something the
85
+ application got wrong or can fix. Report it with the error as printed. If
86
+ the build started stopping right after an upgrade, go back to the previous
87
+ version of what you upgraded — `@k8ordo/framework`, or `react` and
88
+ `react-dom`, which decide where the links are written — until it is fixed.
89
+ The check does not cover the stylesheets of what a client component
90
+ imports dynamically (`React.lazy`, `import()`), nor a Server Component's
91
+ stylesheets, and it runs only in a static build: `vite dev` and server
92
+ mode render per request.
93
+
60
94
  ## A page that is not there
61
95
 
62
96
  A params schema decides what a URL's params look like; whether the thing they
@@ -101,12 +101,26 @@ as it checks every route file's.
101
101
  **Each page loads its own.** `page.tsx`, `not-found.tsx`, `route.ts` and
102
102
  `fallback.tsx` are imported when a request reaches them, so the client
103
103
  components each renders and the CSS each imports — its Server Components'
104
- CSS Modules included — go only to the pages that render it. What a
104
+ CSS Modules included — are loaded only once a page renders it, or, for a
105
+ client component, once a link to such a page is fetched ahead
106
+ ([Fetching the next page ahead](#fetching-the-next-page-ahead)). What a
105
107
  `layout.tsx`, `error.tsx` or `loading.tsx` imports, every page below it
106
108
  loads: import CSS every page needs in the root layout. A route file imported
107
109
  from anywhere else — a layout importing an export of a page — is in every
108
110
  page again, and the build warns, naming it.
109
111
 
112
+ **What every page loads comes in at most two files.** The client entry's —
113
+ React, the router and the framework's own code — and the frame's: the
114
+ client components of every `layout.tsx`, `error.tsx` and `loading.tsx`, and
115
+ the framework's own boundaries, with everything they import. A module a page
116
+ shares with the entry or the frame is in that file, since every page loads
117
+ it anyway; what pages share only among themselves stays in files of their
118
+ own, loaded by the pages that render it. The framework sets the client
119
+ build's `build.rolldownOptions.output.codeSplitting` to do this, so in the
120
+ client environment an application's own `manualChunks` is ignored, and a
121
+ `codeSplitting` group of its own takes a module from the entry or the frame
122
+ only with a `priority` above `2`.
123
+
110
124
  **Under `mode: 'server'` an async page answers, then streams.** The document
111
125
  waits for the page's own component — its data — before anything is sent,
112
126
  because the page may still say `notFound()`
@@ -127,6 +141,28 @@ it arrives.
127
141
  `<Suspense>` boundary on the page and writes each in place, so a file never
128
142
  carries a hole for a script to fill after hydration has started.
129
143
 
144
+ **A Server Component's stylesheet comes before a client component's.** In
145
+ `<head>`, every stylesheet Server Components import — the root layout's
146
+ first — comes before every one client components import, however the page
147
+ was reached: loaded as a document, by a client navigation, or streamed after
148
+ the shell under `mode: 'server'`. Where two rules of equal specificity set
149
+ the same property on one element, the client component's wins. To have a
150
+ Server Component's win, give it a higher specificity, or put the two in
151
+ cascade layers and declare their order at the top of the CSS the root layout
152
+ imports, the first file in `<head>` to name them:
153
+
154
+ ```css
155
+ /* src/styles/globals.css */
156
+ @layer base, components, overrides;
157
+ ```
158
+
159
+ No order is kept among client components' stylesheets: a file lists them in
160
+ the order the render named them, and a client navigation adds each as it
161
+ loads. Nor is one taken out: a stylesheet a page loaded, or a link fetched
162
+ ahead, applies to every page after it in the tab. Keep the selectors of the
163
+ CSS a page or a client component imports to its own elements — a CSS
164
+ Module's classes — and import what every page needs in the root layout.
165
+
130
166
  ## What the build refuses
131
167
 
132
168
  Every problem is reported, not just the first, and each names the file:
@@ -509,7 +545,10 @@ The client runtime listens on the whole document for a pointer moving onto a
509
545
  link, a link taking focus, and a press starting on one — `pointerover`,
510
546
  `focusin` and `pointerdown` — and fetches that page's payload there and then,
511
547
  so a click often finds the page already in hand. Nothing needs wiring: any
512
- `<a>` counts, the ones a component library renders included.
548
+ `<a>` counts, the ones a component library renders included. The fetch
549
+ loads the client components that page renders, as a navigation would, and
550
+ with them their stylesheets, which apply to the page on screen from then on
551
+ ([How a page is sent](#how-a-page-is-sent)).
513
552
 
514
553
  Only a link a click would load in place is fetched: the same origin and below
515
554
  Vite's `base`, no `download`, no `target` other than `_self`, and not the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k8ordo/framework",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "description": "The k8ordo framework: routes/ compiled into React Server Components, run with or without a server.",
5
5
  "keywords": [
6
6
  "k8ordo",
@@ -76,7 +76,7 @@
76
76
  "devDependencies": {
77
77
  "@arethetypeswrong/cli": "0.18.5",
78
78
  "@k8ordo/framework-engine": "^0.1.1",
79
- "@k8ordo/router": "^1.2.1",
79
+ "@k8ordo/router": "^1.3.0",
80
80
  "@types/compressible": "2.0.3",
81
81
  "@types/fresh": "0.5.3",
82
82
  "@types/mime-types": "3.0.1",
@@ -92,11 +92,11 @@
92
92
  "vitest": "5.0.5"
93
93
  },
94
94
  "peerDependencies": {
95
- "@k8ordo/router": "^1.2.1",
95
+ "@k8ordo/router": "^1.3.0",
96
96
  "oxc-transform-react": "^0.152.0",
97
97
  "react": ">=19.3.0",
98
98
  "react-dom": ">=19.3.0",
99
- "vite": ">=8.0.0"
99
+ "vite": ">=8.1.0"
100
100
  },
101
101
  "peerDependenciesMeta": {
102
102
  "oxc-transform-react": {