@k8ordo/framework 2.3.1 → 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.
package/README.md CHANGED
@@ -33,13 +33,13 @@ dependencies in either mode: the build bundles what the application runs.
33
33
 
34
34
  <!-- peers -->
35
35
 
36
- | Package | Version | Required | Needed for |
37
- | --------------------- | -------- | -------- | ------------------------------------------ |
38
- | `@k8ordo/router` | ^2.3.1 | yes | routing, re-exported by the framework |
39
- | `react` | ≥19.3.0 | yes | rendering |
40
- | `react-dom` | ≥19.3.0 | yes | rendering |
41
- | `vite` | ≥8.1.0 | yes | the build (`framework()` is a Vite plugin) |
42
- | `oxc-transform-react` | ^0.152.0 | optional | `reactCompiler: true` (React Compiler) |
36
+ | Package | Version | Required | Needed for |
37
+ | --------------------- | ----------------- | -------- | ------------------------------------------ |
38
+ | `@k8ordo/router` | ^3.0.0 | yes | routing, re-exported by the framework |
39
+ | `react` | ≥19.3.0 | yes | rendering |
40
+ | `react-dom` | ≥19.3.0 | yes | rendering |
41
+ | `vite` | ≥8.1.0 | yes | the build (`framework()` is a Vite plugin) |
42
+ | `oxc-transform-react` | ≥0.152.0 <0.157.0 | optional | `reactCompiler: true` (React Compiler) |
43
43
 
44
44
  <!-- /peers -->
45
45
 
@@ -54,8 +54,7 @@ export default defineConfig({
54
54
  plugins: [
55
55
  framework({
56
56
  mode: 'static',
57
- paths: () => ['/products/1', '/products/2'], // for routes with parameters
58
- site: 'https://example.com', // and a sitemap.xml
57
+ site: 'https://example.com', // writes a sitemap.xml too
59
58
  }),
60
59
  ],
61
60
  });
@@ -70,7 +69,8 @@ src/routes/
70
69
  error.tsx shown in place of what is below when it throws
71
70
  products/[id]/
72
71
  page.tsx /products/:id — `export const paramsSchema` types :id
73
- fallback.tsx static: the shell for the ids paths does not list
72
+ paths.ts static: the ids the build writes
73
+ fallback.tsx static: the shell for the ids paths.ts does not return
74
74
  old/redirect.ts /old sends the visitor elsewhere
75
75
  feed.xml/route.ts /feed.xml answered by its GET — a Response, not a page
76
76
  admin/guard.ts server mode: runs before everything under /admin
@@ -90,6 +90,16 @@ export default async function ProductPage({
90
90
  }
91
91
  ```
92
92
 
93
+ ```ts
94
+ // src/routes/products/[id]/paths.ts — static mode: the ids to write
95
+ import type { Paths } from '@k8ordo/framework';
96
+
97
+ const paths: Paths<'/products/:id'> = async () =>
98
+ (await listProducts()).map((product) => String(product.id));
99
+
100
+ export default paths;
101
+ ```
102
+
93
103
  ```bash
94
104
  vite dev # renders per request, with Fast Refresh
95
105
  vite build # static: dist/client/ is the site
@@ -132,8 +142,11 @@ whatever needs one — a `'use server'` module, a `guard.ts`, an import of
132
142
  `@k8ordo/framework/server` — in `vite dev` as well: `this application wants
133
143
  mode: 'server'`.
134
144
 
135
- A value `paths` does not list — a product added after the build — is
136
- answered by a `fallback.tsx` beside the page: the build writes it once as a
145
+ A parameter's values come from a `paths.ts` in its own directory: a function
146
+ that returns them, run with the modules the pages read their data through,
147
+ and applied to every page, `route.ts` and `redirect.ts` below it. A value it
148
+ does not return — a product added after the build — is answered by a
149
+ `fallback.tsx` beside the page: the build writes it once as a
137
150
  shell, the layouts in HTML, and the browser draws the page from the URL.
138
151
  The build also writes the `_redirects` through which Netlify and Cloudflare
139
152
  reach the shell, and `vercel()` the same rewrites for Vercel — around them,
@@ -1,3 +1,4 @@
1
+ import { t as Paths } from "./paths-type-DtsL8JuC.mjs";
1
2
  import { ErrorComponent, ParamsOf, ParamsOf as ParamsOf$1, ParamsSchemaFor, ParsedParams, ParsedParamsMap, Register, defineRoutes } from "@k8ordo/router";
2
3
  /**
3
4
  * What a `guard.ts` receives: the request, and the params of the pattern its
@@ -20,4 +21,4 @@ type RedirectTarget = string | {
20
21
  readonly to: string;
21
22
  readonly permanent?: boolean;
22
23
  };
23
- export { type ErrorComponent, type Guard, type ParamsOf, type ParamsSchemaFor, type ParsedParams, type ParsedParamsMap, type RedirectTarget, type Register, defineRoutes };
24
+ export { type ErrorComponent, type Guard, type ParamsOf, type ParamsSchemaFor, type ParsedParams, type ParsedParamsMap, type Paths, type RedirectTarget, type Register, defineRoutes };
@@ -0,0 +1,73 @@
1
+ import path from "node:path";
2
+ // ../framework-engine/dist/plugin/shared-dir.mjs
3
+ /** The deepest directory holding both `a` and `b`. */
4
+ const sharedDir = (a, b) => {
5
+ let dir = a;
6
+ while (path.relative(dir, b).startsWith("..")) dir = path.dirname(dir);
7
+ return dir;
8
+ };
9
+ // src/headers.ts
10
+ const PLUGIN = "k8ordo:headers";
11
+ /** A field name as HTTP spells one: a token. */
12
+ const NAME = /^[!#$%&'*+\-.^`|~\w]+$/u;
13
+ /** Bytes a field value cannot hold, a line break among them. */
14
+ const CONTROL = /[\u0000-\u0008\u000A-\u001F\u007F]/u;
15
+ /**
16
+ * What is wrong with the `headers` option, or `null`. A name or a value HTTP
17
+ * could not send is refused when the config loads rather than by whichever
18
+ * server meets it first — and a line break would start a rule of its own in
19
+ * the `_headers` file the build writes.
20
+ */
21
+ const headersRefusal = (given) => {
22
+ if (given === void 0) return null;
23
+ if (typeof given !== "object" || given === null || Array.isArray(given)) return "framework() takes headers as an object of names and values, sent with every response";
24
+ const seen = /* @__PURE__ */ new Set();
25
+ for (const [name, value] of Object.entries(given)) {
26
+ if (!NAME.test(name)) return `framework() cannot send a header named ${JSON.stringify(name)} — a header's name is letters, digits and the punctuation of a token`;
27
+ if (typeof value !== "string" || value === "" || value !== value.trim()) return `framework() needs the value of the header ${name} to be text, with nothing empty around it`;
28
+ if (CONTROL.test(value)) return `framework() cannot send the header ${name}: its value holds a control character`;
29
+ if (seen.has(name.toLowerCase())) return `framework() was given the header ${name} twice, in two spellings`;
30
+ seen.add(name.toLowerCase());
31
+ }
32
+ return null;
33
+ };
34
+ const HEADERS_COMMENT = "# @k8ordo/framework: the headers framework() declared for every response";
35
+ /**
36
+ * The `_headers` file Netlify and Cloudflare read: the declared headers for
37
+ * every path, then the application's own `public/_headers` verbatim. Both
38
+ * hosts send a response every rule that matches it, so a name in both is
39
+ * sent with both values.
40
+ */
41
+ const formatHeaders = (headers, own) => {
42
+ const ownText = own?.replace(/\s+$/u, "") ?? "";
43
+ return `${[
44
+ HEADERS_COMMENT,
45
+ "/*",
46
+ ...Object.entries(headers).map(([name, value]) => ` ${name}: ${value}`),
47
+ ...ownText === "" ? [] : ["", ownText]
48
+ ].join("\n")}\n`;
49
+ };
50
+ /**
51
+ * `vite dev` and `vite preview` sending the declared headers: set before
52
+ * anything answers, so they are on a module, a page, a file and an error
53
+ * alike, and whatever answers may still write the same name over them.
54
+ * Its `api` is where a host adapter reads what was declared.
55
+ */
56
+ const headersPlugin = (headers) => {
57
+ const declared = Object.entries(headers);
58
+ const send = (server) => {
59
+ server.middlewares.use((_request, response, next) => {
60
+ for (const [name, value] of declared) response.setHeader(name, value);
61
+ next();
62
+ });
63
+ };
64
+ return {
65
+ name: PLUGIN,
66
+ api: { headers },
67
+ configureServer: send,
68
+ configurePreviewServer: send
69
+ };
70
+ };
71
+ /** The headers the `framework()` among these plugins declared. */
72
+ const declaredHeaders = (plugins) => (plugins.find(({ name }) => name === PLUGIN)?.api)?.headers ?? {};
73
+ export { sharedDir as a, headersRefusal as i, formatHeaders as n, headersPlugin as r, declaredHeaders as t };
package/dist/index.d.mts CHANGED
@@ -1,2 +1,3 @@
1
+ import { t as Paths } from "./paths-type-DtsL8JuC.mjs";
1
2
  import { BoundLinks, BoundParams, ErrorProps, LayoutProps, MatchOptions, MatchablePattern, NavigateToOptions, PageProps, RegisteredNavigablePattern, RegisteredPageParams, RegisteredParams, RegisteredPattern, RouteContext, bindParams, href, isNotFound, matchPath, navigateTo, normalizePathname, notFound, useMatch, usePathname, usePendingPathname, withBase } from "@k8ordo/router";
2
- export { type BoundLinks, type BoundParams, type ErrorProps, type LayoutProps, type MatchOptions, type MatchablePattern, type NavigateToOptions, type PageProps, type RegisteredNavigablePattern, type RegisteredPageParams, type RegisteredParams, type RegisteredPattern, type RouteContext, bindParams, href, isNotFound, matchPath, navigateTo, normalizePathname, notFound, useMatch, usePathname, usePendingPathname, withBase };
3
+ export { type BoundLinks, type BoundParams, type ErrorProps, type LayoutProps, type MatchOptions, type MatchablePattern, type NavigateToOptions, type PageProps, type Paths, type RegisteredNavigablePattern, type RegisteredPageParams, type RegisteredParams, type RegisteredPattern, type RouteContext, bindParams, href, isNotFound, matchPath, navigateTo, normalizePathname, notFound, useMatch, usePathname, usePendingPathname, withBase };
@@ -0,0 +1,19 @@
1
+ import { ParamsOf } from "@k8ordo/router";
2
+ /** The parameter a pattern ends in: `id` of `/:locale/posts/:id`. */
3
+ type LastParam<Pattern extends string> = Pattern extends `${string}/:${infer Rest}` ? Rest extends `${string}/:${string}` ? LastParam<`/${Rest}`> : Rest : never;
4
+ /**
5
+ * What a `paths.ts` exports by default, under `mode: 'static'`: the values
6
+ * its directory's parameter takes, given the params of the directories above
7
+ * it — one call per combination of theirs. `Pattern` is the directory's own,
8
+ * ending in that parameter. A value is the segment as a visitor reads it
9
+ * (`café`, not `caf%C3%A9`); the build escapes it for the URL.
10
+ *
11
+ * ```ts
12
+ * // src/routes/[locale]/posts/[id]/paths.ts
13
+ * const paths: Paths<'/:locale/posts/:id'> = async ({ locale }) =>
14
+ * (await postsIn(locale)).map((post) => String(post.id));
15
+ * export default paths;
16
+ * ```
17
+ */
18
+ type Paths<Pattern extends string> = (params: Omit<ParamsOf<Pattern>, LastParam<Pattern>>) => readonly string[] | Promise<readonly string[]>;
19
+ export { Paths as t };
@@ -7,7 +7,7 @@ import { doneHydrating, whenHydrated } from "./hydrating-pathname.mjs";
7
7
  import { isPayload } from "./is-payload.mjs";
8
8
  import { createPageCache, prefetchInViewUnderTouch, prefetchOnIntent } from "./prefetch.mjs";
9
9
  import { Recover, markNavigated, navigationsApplied, reloadInstead } from "./recover.mjs";
10
- import { NavigationGeneration, PathnameProvider, TreePathname, normalizePathname, useInterceptedNavigation, withoutBase } from "@k8ordo/router";
10
+ import { NavigationGeneration, PathnameProvider, TreePathname, normalizePathname, useInterceptedNavigation, usePendingPathname, withoutBase } from "@k8ordo/router";
11
11
  import { createContext, startTransition, useDeferredValue, useEffect, useLayoutEffect, useRef, useState } from "react";
12
12
  import { jsx } from "react/jsx-runtime";
13
13
  // src/runtime/app-router.tsx
@@ -83,7 +83,7 @@ const streams = /* @__PURE__ */ new WeakMap();
83
83
  */
84
84
  const fetchPage = async (payloadPath, signal, priority = "auto") => {
85
85
  signal.throwIfAborted();
86
- preloadClientFiles(payloadPath);
86
+ preloadClientFiles(payloadPath, priority);
87
87
  const request = new AbortController();
88
88
  const cancel = () => {
89
89
  request.abort(signal.reason);
@@ -174,6 +174,8 @@ function AppRouter({ arrived, reread }) {
174
174
  const searchApplied = useRef(arrived.search);
175
175
  const streaming = useRef([]);
176
176
  const loading = useRef(0);
177
+ const inView = useRef(null);
178
+ const pendingPathname = usePendingPathname();
177
179
  useEffect(() => {
178
180
  if (!hydrating) return;
179
181
  startTransition(() => {
@@ -272,16 +274,27 @@ function AppRouter({ arrived, reread }) {
272
274
  useEffect(() => {
273
275
  if (!payloadsAreFiles()) return;
274
276
  cacheIn(prefetched).keep(payloadUrlFor(new URL(location.href)), arrived);
275
- readClientFiles();
276
277
  }, [arrived]);
277
278
  useEffect(() => {
278
- const prefetch = (priority) => (url) => cacheIn(prefetched).prefetch(payloadUrlFor(url), priority);
279
- const stops = payloadsAreFiles() ? [prefetchInViewUnderTouch(prefetch("low"))] : [];
280
- stops.push(prefetchOnIntent(prefetch("auto")));
279
+ const cache = cacheIn(prefetched);
280
+ const stopIntents = prefetchOnIntent((url) => cache.prefetch(payloadUrlFor(url), "auto"));
281
+ if (!payloadsAreFiles()) return stopIntents;
282
+ const listed = readClientFiles();
283
+ const watching = prefetchInViewUnderTouch(async (url, signal) => {
284
+ await listed;
285
+ signal.throwIfAborted();
286
+ return cache.prefetch(payloadUrlFor(url), "low", signal);
287
+ });
288
+ inView.current = watching;
281
289
  return () => {
282
- for (const stop of stops) stop();
290
+ stopIntents();
291
+ watching.stop();
292
+ inView.current = null;
283
293
  };
284
294
  }, []);
295
+ useEffect(() => {
296
+ inView.current?.pending(pendingPathname);
297
+ }, [pendingPathname]);
285
298
  const { generation } = useInterceptedNavigation({
286
299
  claim: (url) => url.origin === location.origin && withoutBase(url.pathname) !== null,
287
300
  load: async (url, signal) => {
@@ -1,11 +1,12 @@
1
1
  /**
2
- * Reads the static build's list of the files each page's client components
3
- * need. Without one — `vite dev`, a host that lost it — a payload names its
4
- * files as it is read, as it always does.
2
+ * Reads the static build's list of the files each page needs beyond its
3
+ * payload. Without one — `vite dev`, a host that lost it — a payload names
4
+ * its files as it is read, as it always does.
5
5
  */
6
6
  export declare const readClientFiles: () => Promise<void>;
7
7
  /**
8
8
  * Links what the page whose payload is at `payloadPath` needs: its scripts
9
- * as module preloads, its stylesheets as preloads.
9
+ * as module preloads, its stylesheets as preloads, each at the priority its
10
+ * payload is asked for at.
10
11
  */
11
- export declare const preloadClientFiles: (payloadPath: string) => void;
12
+ export declare const preloadClientFiles: (payloadPath: string, priority: RequestPriority) => void;
@@ -1,12 +1,13 @@
1
1
  import { CLIENT_FILES_PATH } from "./payload.mjs";
2
2
  import { withBase } from "@k8ordo/router";
3
+ import { preload } from "react-dom";
3
4
  // src/runtime/client-files.ts
4
5
  /** Each page's files, by its payload's path; empty until the list is read. */
5
6
  let listed = /* @__PURE__ */ new Map();
6
7
  /**
7
- * Reads the static build's list of the files each page's client components
8
- * need. Without one — `vite dev`, a host that lost it — a payload names its
9
- * files as it is read, as it always does.
8
+ * Reads the static build's list of the files each page needs beyond its
9
+ * payload. Without one — `vite dev`, a host that lost it — a payload names
10
+ * its files as it is read, as it always does.
10
11
  */
11
12
  const readClientFiles = async () => {
12
13
  let read;
@@ -21,20 +22,27 @@ const readClientFiles = async () => {
21
22
  };
22
23
  /**
23
24
  * Links what the page whose payload is at `payloadPath` needs: its scripts
24
- * as module preloads, its stylesheets as preloads.
25
+ * as module preloads, its stylesheets as preloads, each at the priority its
26
+ * payload is asked for at.
25
27
  */
26
- const preloadClientFiles = (payloadPath) => {
28
+ const preloadClientFiles = (payloadPath, priority) => {
27
29
  const files = listed.get(new URL(payloadPath, location.href).pathname);
28
30
  if (files === void 0) return;
29
31
  const present = new Set(Array.from(document.querySelectorAll("link[href]"), (link) => link.href));
30
32
  for (const href of files) {
31
33
  if (present.has(new URL(href, location.href).href)) continue;
32
- const link = document.createElement("link");
33
34
  if (new URL(href, location.href).pathname.endsWith(".css")) {
34
- link.rel = "preload";
35
- link.as = "style";
36
- } else link.rel = "modulepreload";
35
+ preload(href, {
36
+ as: "style",
37
+ crossOrigin: "",
38
+ fetchPriority: priority
39
+ });
40
+ continue;
41
+ }
42
+ const link = document.createElement("link");
43
+ link.rel = "modulepreload";
37
44
  link.crossOrigin = "";
45
+ link.fetchPriority = priority;
38
46
  link.href = href;
39
47
  document.head.append(link);
40
48
  }
@@ -1,3 +1,7 @@
1
+ type Element = {
2
+ readonly type: unknown;
3
+ readonly props: Readonly<Record<string, unknown>>;
4
+ };
1
5
  type ClientReadyOptions = {
2
6
  /**
3
7
  * What to do with a row still on its way: `'wait'` for it; `'leave'` one
@@ -7,6 +11,8 @@ type ClientReadyOptions = {
7
11
  * walk it once it arrives, as an HTML render streaming it does.
8
12
  */
9
13
  readonly rows: 'wait' | 'leave' | 'follow';
14
+ /** Handed every element walked, a row's once it arrives. */
15
+ readonly element?: (element: Element) => void;
10
16
  };
11
17
  /**
12
18
  * Settles once the client components a payload's trees name have loaded.
@@ -26,5 +32,5 @@ type ClientReadyOptions = {
26
32
  * render, a module that would not load — ends the wait there, for the
27
33
  * render to meet where an error boundary takes it.
28
34
  */
29
- export declare const whenClientReady: (trees: readonly unknown[], { rows }: ClientReadyOptions) => Promise<void>;
35
+ export declare const whenClientReady: (trees: readonly unknown[], { rows, element }: ClientReadyOptions) => Promise<void>;
30
36
  export {};
@@ -41,7 +41,7 @@ const whenSettled = (thenable) => new Promise((resolve) => {
41
41
  * render, a module that would not load — ends the wait there, for the
42
42
  * render to meet where an error boundary takes it.
43
43
  */
44
- const whenClientReady = async (trees, { rows }) => {
44
+ const whenClientReady = async (trees, { rows, element }) => {
45
45
  const seen = /* @__PURE__ */ new WeakSet();
46
46
  let waiting = [];
47
47
  const settle = async () => {
@@ -86,6 +86,7 @@ const whenClientReady = async (trees, { rows }) => {
86
86
  return;
87
87
  }
88
88
  if (isElement(value)) {
89
+ element?.(value);
89
90
  if (isLazy(value.type)) read(value.type, inside, true);
90
91
  const below = inside || value.type === SUSPENSE;
91
92
  for (const [key, prop] of Object.entries(value.props)) visit(prop, key === "fallback" ? inside : below);
@@ -10,6 +10,31 @@ export declare const base: string;
10
10
  * serves a build into files — as a static host would — or runs the handler.
11
11
  */
12
12
  export declare const mode: Mode;
13
+ /**
14
+ * The payload a document written into a file was rendered from: what a
15
+ * request for that page's payload would answer, byte for byte, without
16
+ * rendering the page a second time. The build into files writes it beside
17
+ * the HTML, so a page reads its data once per build, and the HTML and the
18
+ * payload of a page can never be two renders that disagree. Kept by the
19
+ * answer itself, which under `'static'` is the handler's own — nothing there
20
+ * can add a header or a cookie for `answer()` to rebuild it around.
21
+ * `undefined` for any other answer, a running server's included.
22
+ */
23
+ export declare const payloadOf: (response: Response) => ArrayBuffer | undefined;
24
+ /**
25
+ * The headers `framework({ headers })` declared for every response. Whatever
26
+ * serves the build's files reads them from here, since a file never passes
27
+ * through the handler.
28
+ */
29
+ declare const everyAnswer: Readonly<Record<string, string>>;
30
+ /**
31
+ * What a `paths.ts` answers when asked for its parameter's values, given the
32
+ * params above it. The build into files asks through here, from the built
33
+ * bundle, so the file runs as the pages do — the application's aliases, and
34
+ * the module instances the pages read their data through. Whatever it
35
+ * returned is handed back as it is: the build is what says a value is not one.
36
+ */
37
+ export declare const pathValues: (file: string, params: Readonly<Record<string, string>>) => Promise<unknown>;
13
38
  /**
14
39
  * The one entry both modes share: a request in, a page out. mode: 'server'
15
40
  * calls it per request; mode: 'static' calls it at build time, for each
@@ -17,4 +42,5 @@ export declare const mode: Mode;
17
42
  * What it knows of the mode is compiled in (`K8ORDO_MODE`): whether a page
18
43
  * gets the request, and whether a failed render may still stream.
19
44
  */
20
- export default function handler(request: Request): Promise<Response>;
45
+ export default function handler(request: Request): Promise<Response>;
46
+ export { everyAnswer as headers };
@@ -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, CLIENT_DEPS_HEADER, NONCE_HEADER, NOT_FOUND_DIGEST, NOT_FOUND_HEADER, SHELL_HEADER, clientDepsHeader } from "./payload.mjs";
5
+ import { ACTION_ID_HEADER, CLIENT_DEPS_HEADER, NONCE_HEADER, NOT_FOUND_DIGEST, NOT_FOUND_HEADER, SERVER_STYLESHEETS_HEADER, SHELL_HEADER, clientDepsHeader, serverStylesheetsHeader } from "./payload.mjs";
6
6
  import { isPayloadPath, pagePathFor } from "./payload-path.mjs";
7
7
  import { noticeCancel } from "./cancel.mjs";
8
8
  import { runGuards } from "./guard.mjs";
@@ -15,7 +15,7 @@ import { shellParams } from "./shell.mjs";
15
15
  import { isNotFound, normalizePathname, withBase, withoutBase } from "@k8ordo/router";
16
16
  import { jsx } from "react/jsx-runtime";
17
17
  import { createTemporaryReferenceSet, decodeAction, decodeFormState, decodeReply, loadServerAction, renderToReadableStream } from "@vitejs/plugin-rsc/rsc/server";
18
- import { catchAllSchemas, fallbacks, guards, pageModules, paramSchemas, redirects, routeModules, routes, searchReaders } from "virtual:k8ordo/routes";
18
+ import { catchAllSchemas, fallbacks, guards, pageModules, paramSchemas, paths, redirects, routeModules, routes, searchReaders } from "virtual:k8ordo/routes";
19
19
  // src/runtime/entry.rsc.tsx
20
20
  const redirectFor = resolveRedirects(redirects);
21
21
  const redirectResponse = (to, status) => new Response(null, {
@@ -33,6 +33,56 @@ const base = import.meta.env.BASE_URL;
33
33
  * serves a build into files — as a static host would — or runs the handler.
34
34
  */
35
35
  const mode = import.meta.env.K8ORDO_MODE === "static" ? "static" : "server";
36
+ const filePayloads = /* @__PURE__ */ new WeakMap();
37
+ /**
38
+ * The payload a document written into a file was rendered from: what a
39
+ * request for that page's payload would answer, byte for byte, without
40
+ * rendering the page a second time. The build into files writes it beside
41
+ * the HTML, so a page reads its data once per build, and the HTML and the
42
+ * payload of a page can never be two renders that disagree. Kept by the
43
+ * answer itself, which under `'static'` is the handler's own — nothing there
44
+ * can add a header or a cookie for `answer()` to rebuild it around.
45
+ * `undefined` for any other answer, a running server's included.
46
+ */
47
+ const payloadOf = (response) => filePayloads.get(response);
48
+ /**
49
+ * The headers `framework({ headers })` declared for every response. Whatever
50
+ * serves the build's files reads them from here, since a file never passes
51
+ * through the handler.
52
+ */
53
+ const everyAnswer = import.meta.env.K8ORDO_HEADERS;
54
+ const declaredEntries = Object.entries(everyAnswer);
55
+ /**
56
+ * `response` carrying the declared headers it does not already have: what a
57
+ * guard.ts or a route.ts set for this request stays. Under `'static'` the
58
+ * answer becomes a file, which has no headers of its own to carry.
59
+ */
60
+ const withDeclared = (response) => {
61
+ if (import.meta.env.K8ORDO_MODE === "static") return response;
62
+ const missing = declaredEntries.filter(([name]) => !response.headers.has(name));
63
+ if (missing.length === 0) return response;
64
+ const merged = new Headers(response.headers);
65
+ for (const [name, value] of missing) merged.set(name, value);
66
+ return new Response(response.body, {
67
+ status: response.status,
68
+ statusText: response.statusText,
69
+ headers: merged
70
+ });
71
+ };
72
+ /**
73
+ * What a `paths.ts` answers when asked for its parameter's values, given the
74
+ * params above it. The build into files asks through here, from the built
75
+ * bundle, so the file runs as the pages do — the application's aliases, and
76
+ * the module instances the pages read their data through. Whatever it
77
+ * returned is handed back as it is: the build is what says a value is not one.
78
+ */
79
+ const pathValues = async (file, params) => {
80
+ const load = paths[file];
81
+ if (load === void 0) throw new Error(`${file} is not a paths.ts of this build`);
82
+ const { default: values } = await load();
83
+ if (typeof values !== "function") throw new TypeError(`${file} has to export default a function returning its parameter's values`);
84
+ return values(params);
85
+ };
36
86
  const NO_PARAMS = {
37
87
  params: {},
38
88
  enter: (fn) => fn()
@@ -198,10 +248,10 @@ const renderFailed = (error) => new Response(error instanceof Error ? error.mess
198
248
  * gets the request, and whether a failed render may still stream.
199
249
  */
200
250
  function handler(request) {
201
- return withRequest(request, async () => answer(await (import.meta.env.K8ORDO_MODE === "static" ? writingFile(() => respond(request).catch((error) => {
251
+ return withRequest(request, async () => withDeclared(answer(await (import.meta.env.K8ORDO_MODE === "static" ? writingFile(() => respond(request).catch((error) => {
202
252
  reportFailed("answering", new URL(request.url).pathname, error);
203
253
  return renderFailed(error);
204
- })) : respond(request))));
254
+ })) : respond(request)))));
205
255
  }
206
256
  const reportFailed = (doing, pathname, error) => {
207
257
  console.error(`k8ordo: ${doing} %s failed`, pathname, error);
@@ -398,15 +448,19 @@ const answerHtml = async (ssr, rendered, enter, { status, showsPage, carriesForm
398
448
  }
399
449
  });
400
450
  }
401
- const [forHtml, forNamed] = rendered.stream.tee();
402
- await drain(forNamed);
451
+ const [forHtml, forFile] = rendered.stream.tee();
452
+ const payload = await new Response(forFile).arrayBuffer();
453
+ const linked = /* @__PURE__ */ new Set();
403
454
  let body;
404
455
  try {
405
456
  const html = await enter(() => ssr.renderHtml(forHtml, {
406
457
  nonce: signingNonce(),
407
458
  showsPage,
408
459
  carriesFormState,
409
- named: [...rendered.named.values()]
460
+ named: [...rendered.named.values()],
461
+ linked: (href) => {
462
+ linked.add(href);
463
+ }
410
464
  }));
411
465
  body = await new Response(html).arrayBuffer();
412
466
  } catch (error) {
@@ -414,15 +468,18 @@ const answerHtml = async (ssr, rendered, enter, { status, showsPage, carriesForm
414
468
  }
415
469
  const failed = rendered.failures[0];
416
470
  if (failed !== void 0) return renderFailed(failed);
417
- return new Response(body, {
471
+ const response = new Response(body, {
418
472
  status,
419
473
  headers: {
420
474
  "content-type": HTML_TYPE,
421
475
  [NONCE_HEADER]: signingNonce(),
422
476
  [CLIENT_DEPS_HEADER]: clientDepsHeader(rendered.named.values()),
477
+ [SERVER_STYLESHEETS_HEADER]: serverStylesheetsHeader(linked),
423
478
  ...headers
424
479
  }
425
480
  });
481
+ filePayloads.set(response, payload);
482
+ return response;
426
483
  };
427
484
  /**
428
485
  * Where a page that said notFound() is sent: the catch-all the table answers
@@ -491,4 +548,4 @@ const renderPayload = (payload, enter, temporaryReferences) => {
491
548
  */
492
549
  const drain = (stream) => stream.pipeTo(new WritableStream()).catch(() => void 0);
493
550
  if (import.meta.hot) import.meta.hot.accept();
494
- export { base, handler as default, mode };
551
+ export { base, handler as default, everyAnswer as headers, mode, pathValues, payloadOf };
@@ -12,7 +12,7 @@ export declare const clientEntry: string;
12
12
  * one round trip. It is also what lets a prerendered `404.html` come alive —
13
13
  * there is no payload file at a URL the application does not have.
14
14
  */
15
- export declare function renderHtml(rscStream: ReadableStream<Uint8Array>, { nonce, showsPage, carriesFormState, named }: {
15
+ export declare function renderHtml(rscStream: ReadableStream<Uint8Array>, { nonce, showsPage, carriesFormState, named, linked }: {
16
16
  /**
17
17
  * The request's: every script written here carries it. What else does,
18
18
  * the application signed, and the policy that names it is the
@@ -32,4 +32,9 @@ export declare function renderHtml(rscStream: ReadableStream<Uint8Array>, { nonc
32
32
  * to its end: the HTML links each, rendered or not.
33
33
  */
34
34
  readonly named?: readonly ClientDeps[];
35
+ /**
36
+ * Under mode: 'static', handed each stylesheet a Server Component of the
37
+ * payload links, as the walk meets it: every one before the HTML is read.
38
+ */
39
+ readonly linked?: (href: string) => void;
35
40
  }): Promise<ReadableStream>;
@@ -6,9 +6,9 @@ import { DocumentRoot } from "./document-root.mjs";
6
6
  import { PageShownContext } from "./page-shown.mjs";
7
7
  import { scriptsBeforeStylesheetsStream } from "./head-scripts.mjs";
8
8
  import { use } from "react";
9
+ import { preinit, preloadModule } from "react-dom";
9
10
  import { jsx } from "react/jsx-runtime";
10
11
  import { createFromReadableStream, getClientEntryUrl } from "@vitejs/plugin-rsc/ssr";
11
- import { preinit, preloadModule } from "react-dom";
12
12
  import { renderToReadableStream } from "react-dom/server.edge";
13
13
  import { injectRSCPayload } from "rsc-html-stream/server";
14
14
  import assetsManifest from "virtual:vite-rsc/assets-manifest";
@@ -51,7 +51,7 @@ const linkClientDeps = (named) => {
51
51
  * one round trip. It is also what lets a prerendered `404.html` come alive —
52
52
  * there is no payload file at a URL the application does not have.
53
53
  */
54
- async function renderHtml(rscStream, { nonce, showsPage, carriesFormState, named = [] }) {
54
+ async function renderHtml(rscStream, { nonce, showsPage, carriesFormState, named = [], linked }) {
55
55
  const [forRender, forHydration] = rscStream.tee();
56
56
  let forHtml = forRender;
57
57
  let formState;
@@ -66,7 +66,12 @@ async function renderHtml(rscStream, { nonce, showsPage, carriesFormState, named
66
66
  linkClientDeps(named);
67
67
  reading ??= createFromReadableStream(forHtml, { nonce });
68
68
  const payload = use(reading);
69
- ready ??= whenClientReady([payload.tree, payload.notFound], { rows: import.meta.env.K8ORDO_MODE === "static" ? "wait" : "follow" });
69
+ ready ??= whenClientReady([payload.tree, payload.notFound], {
70
+ rows: import.meta.env.K8ORDO_MODE === "static" ? "wait" : "follow",
71
+ element: linked === void 0 ? void 0 : ({ type, props }) => {
72
+ if (type === "link" && props.precedence === "vite-rsc/importer-resources" && typeof props.href === "string") linked(props.href);
73
+ }
74
+ });
70
75
  use(ready);
71
76
  return /* @__PURE__ */ jsx(AppRouter, { arrived: payload });
72
77
  }
@@ -93,10 +93,25 @@ export declare const clientDepsHeader: (named: Iterable<ClientDeps>) => string;
93
93
  /** What `clientDepsHeader` said. */
94
94
  export declare const readClientDeps: (value: string) => ClientDeps[];
95
95
  /**
96
- * Where a static build lists the files each page's client components need,
97
- * at the root of the site under Vite's `base`. A navigation links them as it
98
- * asks for the payload, instead of once the payload has named them — a
99
- * round trip sooner.
96
+ * Said by the handler under mode: 'static' alone, on a page's HTML: every
97
+ * stylesheet the Server Components of the payload it rendered link
98
+ * (`serverStylesheetsHeader`), which the build lists in `CLIENT_FILES_PATH`
99
+ * beside the client modules' files.
100
+ */
101
+ export declare const SERVER_STYLESHEETS_HEADER = "x-k8ordo-server-stylesheets";
102
+ /**
103
+ * The value of `SERVER_STYLESHEETS_HEADER`, encoded as `clientDepsHeader`
104
+ * is, for a stylesheet is named after a module too.
105
+ */
106
+ export declare const serverStylesheetsHeader: (hrefs: Iterable<string>) => string;
107
+ /** What `serverStylesheetsHeader` said. */
108
+ export declare const readServerStylesheets: (value: string) => string[];
109
+ /**
110
+ * Where a static build lists the files each page needs beyond its payload —
111
+ * its client components' scripts and stylesheets, and its Server Components'
112
+ * stylesheets — at the root of the site under Vite's `base`. A navigation
113
+ * links them as it asks for the payload, instead of once the payload has
114
+ * named them — a round trip sooner.
100
115
  */
101
116
  export declare const CLIENT_FILES_PATH = "/client-files.json";
102
117
  /**
@@ -41,10 +41,25 @@ const clientDepsHeader = (named) => encodeURIComponent(JSON.stringify([...named]
41
41
  /** What `clientDepsHeader` said. */
42
42
  const readClientDeps = (value) => JSON.parse(decodeURIComponent(value));
43
43
  /**
44
- * Where a static build lists the files each page's client components need,
45
- * at the root of the site under Vite's `base`. A navigation links them as it
46
- * asks for the payload, instead of once the payload has named them — a
47
- * round trip sooner.
44
+ * Said by the handler under mode: 'static' alone, on a page's HTML: every
45
+ * stylesheet the Server Components of the payload it rendered link
46
+ * (`serverStylesheetsHeader`), which the build lists in `CLIENT_FILES_PATH`
47
+ * beside the client modules' files.
48
+ */
49
+ const SERVER_STYLESHEETS_HEADER = "x-k8ordo-server-stylesheets";
50
+ /**
51
+ * The value of `SERVER_STYLESHEETS_HEADER`, encoded as `clientDepsHeader`
52
+ * is, for a stylesheet is named after a module too.
53
+ */
54
+ const serverStylesheetsHeader = (hrefs) => encodeURIComponent(JSON.stringify([...hrefs]));
55
+ /** What `serverStylesheetsHeader` said. */
56
+ const readServerStylesheets = (value) => JSON.parse(decodeURIComponent(value));
57
+ /**
58
+ * Where a static build lists the files each page needs beyond its payload —
59
+ * its client components' scripts and stylesheets, and its Server Components'
60
+ * stylesheets — at the root of the site under Vite's `base`. A navigation
61
+ * links them as it asks for the payload, instead of once the payload has
62
+ * named them — a round trip sooner.
48
63
  */
49
64
  const CLIENT_FILES_PATH = "/client-files.json";
50
- export { ACTION_ID_HEADER, CLIENT_DEPS_HEADER, CLIENT_FILES_PATH, NONCE_HEADER, NOT_FOUND_DIGEST, NOT_FOUND_HEADER, SHELL_HEADER, clientDepsHeader, readClientDeps };
65
+ export { ACTION_ID_HEADER, CLIENT_DEPS_HEADER, CLIENT_FILES_PATH, NONCE_HEADER, NOT_FOUND_DIGEST, NOT_FOUND_HEADER, SERVER_STYLESHEETS_HEADER, SHELL_HEADER, clientDepsHeader, readClientDeps, readServerStylesheets, serverStylesheetsHeader };